Correctly written Windows apps that want to save their location from run to run will save the results of GetWindowPlacement()
before shutting down, then use SetWindowPlacement()
on startup to restore their position.
Frequently, apps will store the results of GetWindowPlacement()
in the registry as a REG_BINARY
for easy use.
The WINDOWPLACEMENT
route has many advantages over other methods:
SetWindowPlacement()
will automatically ensure that the window is not entirely offscreenFinally, programs that handle window restoration properly will take into account the nCmdShow
parameter passed in from the shell. This parameter is set in the shortcut that launches the application (Normal, Minimized, Maximize):
if(nCmdShow != SW_SHOWNORMAL)
placement.showCmd = nCmdShow; //allow shortcut to override
For non-Win32 applications, it's important to be sure that the method you're using to save/restore window position eventually uses the same underlying call, otherwise (like Java Swing's setBounds()
/getBounds()
problem) you'll end up writing a lot of extra code to re-implement functionality that's already there in the WINDOWPLACEMENT
functions.
The free version of TightVnc viewer (I have TightVnc Viewer 1.5.4 8/3/2011) build does not support this. What you need is RealVNC but VNC Enterprise Edition 4.2 or the Personal Edition. Unfortunately this is not free and you have to pay for a license.
From the RealVNC website [releasenote] http://www.realvnc.com/products/enterprise/4.2/release-notes.html
VNC Viewer: Full-screen mode can span monitors on a multi-monitor system.
can gridmove be of any assistance?
very handy tool on larger screens...
I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).
When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.
It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.
Get Screen Width and Height in terms of DP with some good decoration:
Step 1: Create interface
public interface ScreenInterface {
float getWidth();
float getHeight();
}
Step 2: Create implementer class
public class Screen implements ScreenInterface {
private Activity activity;
public Screen(Activity activity) {
this.activity = activity;
}
private DisplayMetrics getScreenDimension(Activity activity) {
DisplayMetrics displayMetrics = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
return displayMetrics;
}
private float getScreenDensity(Activity activity) {
return activity.getResources().getDisplayMetrics().density;
}
@Override
public float getWidth() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.widthPixels / getScreenDensity(activity);
}
@Override
public float getHeight() {
DisplayMetrics displayMetrics = getScreenDimension(activity);
return displayMetrics.heightPixels / getScreenDensity(activity);
}
}
Step 3: Get width and height in activity:
Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();
function page_properties($objPortal) {
$objPage->set_page_title($myrow['title']);
}
looks like different names of variables $objPortal vs $objPage
Tags can be either signed or unsigned; branches are never signed.
Signed tags can never move because they are cryptographically bound (with a signature) to a particular commit. Unsigned tags are not bound and it is possible to move them (but moving tags is not a normal use case).
Branches can not only move to a different commit but are expected to do so. You should use a branch for your local development project. It doesn't quite make sense to commit work to a Git repository "on a tag".
Here's the simplest solution with a clear selector:
function select_option(i) {
return $('span#span_id select option[value="' + i + '"]').html();
}
Set the columns Width
property to be a proportional width such as *
Pay close attention to the first part of the error: "variable is not declared"
Ignore the second part: "it may be inaccessible due to its protection level". It's a red herring.
Some questions... (the answers might be in that image you posted, but I can't seem to make it larger and my eyes don't read that small of print... Any chance you can post the code in a way these older eyes can read it? Makes it hard to know the total picture. In particular I am suspicious of your Page directives.)
We know that 1stReasonTypes is a listbox, but for some reason it seems like we don't know WHICH listbox. This is why I want to see your page directives.
But also, how are you calling the private method FormRefresh()? It's not an event handler, which makes me wonder if you are trying to reference a listbox in a form that is not handled properly in this code behind.
You may need to find the control 1stReasonTypes. Try maybe putting your listbox inside something like
<div id="MyFormDiv" runat="server">.....</div>
then in FormRefresh(), do a...
Dim 1stReasonTypesNew As listbox = MyFormDiv.FindControl("1stReasonTypes")
Or use an existing control, object, or page instead of a div. More info on FindControl: http://msdn.microsoft.com/en-us/library/486wc64h(v=vs.110).aspx
But no matter how you slice it, there is something funky going here such that 1stReasonTypes doesn't know which exact listbox it's supposed to be.
static_cast
is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. static_cast
performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example:
void func(void *data) {
// Conversion from MyClass* -> void* is implicit
MyClass *c = static_cast<MyClass*>(data);
...
}
int main() {
MyClass c;
start_thread(&func, &c) // func(&c) will be called
.join();
}
In this example, you know that you passed a MyClass
object, and thus there isn't any need for a runtime check to ensure this.
dynamic_cast
is useful when you don't know what the dynamic type of the object is. It returns a null pointer if the object referred to doesn't contain the type casted to as a base class (when you cast to a reference, a bad_cast
exception is thrown in that case).
if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {
...
} else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {
...
}
You cannot use dynamic_cast
if you downcast (cast to a derived class) and the argument type is not polymorphic. For example, the following code is not valid, because Base
doesn't contain any virtual function:
struct Base { };
struct Derived : Base { };
int main() {
Derived d; Base *b = &d;
dynamic_cast<Derived*>(b); // Invalid
}
An "up-cast" (cast to the base class) is always valid with both static_cast
and dynamic_cast
, and also without any cast, as an "up-cast" is an implicit conversion.
These casts are also called C-style cast. A C-style cast is basically identical to trying out a range of sequences of C++ casts, and taking the first C++ cast that works, without ever considering dynamic_cast
. Needless to say, this is much more powerful as it combines all of const_cast
, static_cast
and reinterpret_cast
, but it's also unsafe, because it does not use dynamic_cast
.
In addition, C-style casts not only allow you to do this, but they also allow you to safely cast to a private base-class, while the "equivalent" static_cast
sequence would give you a compile-time error for that.
Some people prefer C-style casts because of their brevity. I use them for numeric casts only, and use the appropriate C++ casts when user defined types are involved, as they provide stricter checking.
You can try simpleBootstrapDialog. Here you can pass title, message, callback options for cancel and submit etc...
To use this plugin include simpleBootstrapDialog.js file like below
<script type="text/javascript" src="/simpleDialog.js"></script>
Basic Usage
<script type="text/javascript>
$.simpleDialog();
</script>
Custom Title and description
$.simpleDialog({
title:"Alert Dialog",
message:"Alert Message"
});
With Callback
<script type="text/javascript>
$.simpleDialog({
onSuccess:function(){
alert("You confirmed");
},
onCancel:function(){
alert("You cancelled");
}
});
</script>
byte[] iso88591Data = theString.getBytes("ISO-8859-1");
Will do the trick. From your description it seems as if you're trying to "store an ISO-8859-1 String". String objects in Java are always implicitly encoded in UTF-16. There's no way to change that encoding.
What you can do, 'though is to get the bytes that constitute some other encoding of it (using the .getBytes()
method as shown above).
-1 isn't special in the sense that the sequence is read backwards, it rather wraps around the ends. Such that minus one means zero minus one, exclusive (and, for a positive step value, the sequence is read "from left to right".
so for i = [1, 2, 3, 4]
, i[2:-1]
means from item two to the beginning minus one (or, 'around to the end'), which results in [3]
.
The -1th element, or element 0 backwards 1 is the last 4
, but since it's exclusive, we get 3.
I hope this is somewhat understandable.
I think this code works on all browsers and requires the least overhead. It's really a hybrid of all the above answers. Let me know if you find a bug!
Add CSS:
.no_select { user-select: none; -o-user-select: none; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select:none;}
Add jQuery:
(function($){
$.fn.disableSelection = function()
{
$(this).addClass('no_select');
if($.browser.msie)
{
$(this).attr('unselectable', 'on').on('selectstart', false);
}
return this;
};
})(jQuery);
Optional: To disable selection for all children elements as well, you can change the IE block to:
$(this).each(function() {
$(this).attr('unselectable','on')
.bind('selectstart',function(){ return false; });
});
Usage:
$('.someclasshere').disableSelection();
Until I was really concerned about performance, I would use a function, that takes a base and returns its match:
char base_pair(char base)
{
switch(base) {
case 'T': return 'A';
... etc
default: // handle error
}
}
If I was concerned about performance, I would define a base as one fourth of a byte. 0 would represent A, 1 would represent G, 2 would represent C, and 3 would represent T. Then I would pack 4 bases into a byte, and to get their pairs, I would simply take the complement.
The GWT compiler is doing a lot of code analysis so it is going to be difficult to speed it up. This session from Google IO 2008 will give you a good idea of what GWT is doing and why it does take so long.
My recommendation is for development use Hosted Mode as much as possible and then only compile when you want to do your testing. This does sound like the solution you've come to already, but basically that's why Hosted Mode is there (well, that and debugging).
You can speed up the GWT compile but only compiling for some browsers, rather than 5 kinds which GWT does by default. If you want to use Hosted Mode make sure you compile for at least two browsers; if you compile for a single browser then the browser detection code is optimised away and then Hosted Mode doesn't work any more.
An easy way to configure compiling for fewer browsers is to create a second module which inherits from your main module:
<module rename-to="myproject">
<inherits name="com.mycompany.MyProject"/>
<!-- Compile for IE and Chrome -->
<!-- If you compile for only one browser, the browser detection javascript
is optimised away and then Hosted Mode doesn't work -->
<set-property name="user.agent" value="ie6,safari"/>
</module>
If the rename-to
attribute is set the same then the output files will be same as if you did a full compile
In case of someone else is doing it in Python and it is not working, try to set it before do the imports of pycuda and tensorflow.
I.e.:
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
...
import pycuda.autoinit
import tensorflow as tf
...
As saw here.
If you still can't access the management console after a fresh install, check if the management console was enabled. To enable it:
Go to the RabbitMQ command prompt.
Type:
rabbitmq-plugins enable rabbitmq_management
If you really want something like goto statements, you could always try breaking to named blocks.
You have to be within the scope of the block to break to the label:
namedBlock: {
if (j==2) {
// this will take you to the label above
break namedBlock;
}
}
I won't lecture you on why you should avoid goto's - I'm assuming you already know the answer to that.
cPickle
comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle
, you can do this:
>>> import _pickle as cPickle
However, in 3.x, it's easier just to use pickle
.
No need to install anything. If something requires cPickle
in python 3.x, then that's probably a bug.
I just solved this error for myself, but it was a bit silly on my part. Still worth checking if the above doesn't help you.
In my case, I was editing the config files in /etc/phpmyadmin
, my install was located in /usr/share/phpmyadmin
, and my install was not actually opening the /etc/phpmyadmin
config files, as I thought it would. So I just did this command:
ln -s /etc/phpmyadmin/conf* /usr/share/phpmyadmin
For those not in the know, ln -s
makes a soft link (basically a shortcut). So that command just makes shortcuts from the config files in /etc
to the /usr/share
install.
By the way, I figured this out after using the program opensnoop
, which shows you what files are being opened (technically, traces open()
syscalls and the pid of the process, as they happen), which you can install on Ubuntu with apt-get install perf-tools-unstable
, or you can get it here.
Most of the time you can't - depending on the host. You can contact the support team where your hosting is subscribed to, and if they confirmed that it is really not allowed, you can just set up the composer on your dev machine, and commit and push all dependencies to your live server using Git or whatever you prefer.
My solution is similar to Payam's, except I am using
//older code
//postman.setGlobalVariable("currentDate", new Date().toLocaleDateString());
pm.globals.set("currentDate", new Date().toLocaleDateString());
If you hit the "3 dots" on the folder and click "Edit"
Then set Pre-Request Scripts for the all calls, so the global variable is always available.
I encountered the same problem:
E/AndroidRuntime: FATAL EXCEPTION: Thread-4
Process: com.example.languoguang.welcomeapp, PID: 4724
java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
at android.widget.Toast$TN.<init>(Toast.java:393)
at android.widget.Toast.<init>(Toast.java:117)
at android.widget.Toast.makeText(Toast.java:280)
at android.widget.Toast.makeText(Toast.java:270)
at com.example.languoguang.welcomeapp.MainActivity$1.run(MainActivity.java:51)
at java.lang.Thread.run(Thread.java:764)
I/Process: Sending signal. PID: 4724 SIG: 9
Application terminated.
Before: onCreate function
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
}
});
thread.start();
After: onCreate function
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
}
});
it worked.
var array = ["Zero", "One", "Two"];
var s = array + [];
console.log(s); // => Zero,One,Two
>> /dev/null
redirects standard output (stdout
) to /dev/null
, which discards it.
(The >>
seems sort of superfluous, since >>
means append while >
means truncate and write, and either appending to or writing to /dev/null
has the same net effect. I usually just use >
for that reason.)
2>&1
redirects standard error (2
) to standard output (1
), which then discards it as well since standard output has already been redirected.
Here is solution.
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="**Your String Value**" />
JULI logging levels for Tomcat
SEVERE - Serious failures
WARNING - Potential problems
INFO - Informational messages
CONFIG - Static configuration messages
FINE - Trace messages
FINER - Detailed trace messages
FINEST - Highly detailed trace messages
You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html
It actually works now from bower.
bower install material-design-icons --save
It downloads 37.1 KBs. Then it extracts and installs. You will see a folder called material-design-icons in bower_components folder. The total size is around 299KBs
With Chinese text, I tried to use the Charset UTF-16 and lucklily it work.
Hope this could help!
PrintWriter out = new PrintWriter( file, "UTF-16" );
Auth::user()->products->sum('price');
The documentation is a little light for some of the Collection
methods but all the query builder aggregates are seemingly available besides avg()
that can be found at http://laravel.com/docs/queries#aggregates.
This makes me wonder, when is it advisable to use the EntityManager.getReference() method instead of the EntityManager.find() method?
EntityManager.getReference()
is really an error prone method and there is really very few cases where a client code needs to use it.
Personally, I never needed to use it.
I disagree with the accepted answer and particularly :
If i call find method, JPA provider, behind the scenes, will call
SELECT NAME, AGE FROM PERSON WHERE PERSON_ID = ? UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?
If i call getReference method, JPA provider, behind the scenes, will call
UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?
It is not the behavior that I get with Hibernate 5 and the javadoc of getReference()
doesn't say such a thing :
Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.
EntityManager.getReference()
spares a query to retrieve the entity in two cases :
1) if the entity is stored in the Persistence context, that is
the first level cache.
And this behavior is not specific to EntityManager.getReference()
,
EntityManager.find()
will also spare a query to retrieve the entity if the entity is stored in the Persistence context.
You can check the first point with any example.
You can also rely on the actual Hibernate implementation.
Indeed, EntityManager.getReference()
relies on the createProxyIfNecessary()
method of the org.hibernate.event.internal.DefaultLoadEventListener
class to load the entity.
Here is its implementation :
private Object createProxyIfNecessary(
final LoadEvent event,
final EntityPersister persister,
final EntityKey keyToLoad,
final LoadEventListener.LoadType options,
final PersistenceContext persistenceContext) {
Object existing = persistenceContext.getEntity( keyToLoad );
if ( existing != null ) {
// return existing object or initialized proxy (unless deleted)
if ( traceEnabled ) {
LOG.trace( "Entity found in session cache" );
}
if ( options.isCheckDeleted() ) {
EntityEntry entry = persistenceContext.getEntry( existing );
Status status = entry.getStatus();
if ( status == Status.DELETED || status == Status.GONE ) {
return null;
}
}
return existing;
}
if ( traceEnabled ) {
LOG.trace( "Creating new proxy for entity" );
}
// return new uninitialized proxy
Object proxy = persister.createProxy( event.getEntityId(), event.getSession() );
persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey( keyToLoad );
persistenceContext.addProxy( keyToLoad, proxy );
return proxy;
}
The interesting part is :
Object existing = persistenceContext.getEntity( keyToLoad );
2) If we don't effectively manipulate the entity, echoing to the lazily fetched of the javadoc.
Indeed, to ensure the effective loading of the entity, invoking a method on it is required.
So the gain would be related to a scenario where we want to load a entity without having the need to use it ? In the frame of applications, this need is really uncommon and in addition the getReference()
behavior is also very misleading if you read the next part.
In terms of overhead, getReference()
is not better than find()
as discussed in the previous point.
So why use the one or the other ?
Invoking getReference()
may return a lazily fetched entity.
Here, the lazy fetching doesn't refer to relationships of the entity but the entity itself.
It means that if we invoke getReference()
and then the Persistence context is closed, the entity may be never loaded and so the result is really unpredictable. For example if the proxy object is serialized, you could get a null
reference as serialized result or if a method is invoked on the proxy object, an exception such as LazyInitializationException
is thrown.
It means that the throw of EntityNotFoundException
that is the main reason to use getReference()
to handle an instance that does not exist in the database as an error situation may be never performed while the entity is not existing.
EntityManager.find()
doesn't have the ambition of throwing EntityNotFoundException
if the entity is not found. Its behavior is both simple and clear. You will never have surprise as it returns always a loaded entity or null
(if the entity is not found) but never an entity under the shape of a proxy that may not be effectively loaded.
So EntityManager.find()
should be favored in the very most of cases.
In MySQL there is a group_concat function that will return what you're asking for.
SELECT TableA.ID, TableA.Name, group_concat(TableB.SomeColumn)
as SomColumnGroup FROM TableA LEFT JOIN TableB ON
TableB.TableA_ID = TableA.ID
There's a better way of storing JSON in the HTML:
HTML
<script id="some-data" type="application/json">{"param_1": "Value 1", "param_2": "Value 2"}</script>
JavaScript
JSON.parse(document.getElementById('some-data').textContent);
For Ubuntu 14.04 and 16.04, you can apply following commands
First, check MySQL service is running or not using
sudo service mysql status
Now you can see you show a message like this: mysql stop/waiting.
Now apply command: sudo service mysql restart!
Now you can see you show a message like this: mysql start/running, process 8313.
Now go to the browser and logged in as root(username) and root(password) and you will be logged in successfully
Another method is to use netcat (or nc, dependent upon which posix) in the same format as vatine shows or you can create a text file that contains each command on it's own line.
I have found that some posix' telnets do not handle redirect correctly (which is why I suggest netcat)
the best way is:
let methods = Object.getOwnPropertyNames(yourobject);
console.log(methods)
use 'let' only in es6, use 'var' instead
Use the git add
command, followed by a list of space-separated filenames. Include paths if in other directories, e.g. directory-name/file-name
.
git add file-1 file-2 file-3
There is a simple function subtract
which moment library gives us to subtract time from some time.
Using it is also very simple.
moment(Date.now()).subtract(7, 'days'); // This will subtract 7 days from current time
moment(Date.now()).subtract(3, 'd'); // This will subtract 3 days from current time
//You can do this for days, years, months, hours, minutes, seconds
//You can also subtract multiple things simulatneously
//You can chain it like this.
moment(Date.now()).subtract(3, 'd').subtract(5. 'h'); // This will subtract 3 days and 5 hours from current time
//You can also use it as object literal
moment(Date.now()).subtract({days:3, hours:5}); // This will subtract 3 days and 5 hours from current time
Hope this helps!
To check if a specific package is installed:
conda list html5lib
which outputs something like this if installed:
# packages in environment at C:\ProgramData\Anaconda3:
#
# Name Version Build Channel
html5lib 1.0.1 py37_0
or something like this if not installed:
# packages in environment at C:\ProgramData\Anaconda3:
#
# Name Version Build Channel
you don't need to type the exact package name. Partial matches are supported:
conda list html
This outputs all installed packages containing 'html':
# packages in environment at C:\ProgramData\Anaconda3:
#
# Name Version Build Channel
html5lib 1.0.1 py37_0
sphinxcontrib-htmlhelp 1.0.2 py_0
sphinxcontrib-serializinghtml 1.1.3 py_0
I will try to explain the static thing to you. First of all static variables do not belong to any particular instance of the class. They are recognized with the name of the class. Static methods again do not belong again to any particular instance. They can access only static variables. Imagine you call MyClass.myMethod() and myMethod is a static method. If you use non-static variables inside the method, how the hell on earth would it know which variables to use? That's why you can use from static methods only static variables. I repeat again they do NOT belong to any particular instance.
You will need to configure you IIS (assuming this is the web server your are/will using) allowing access from WLAN/LAN to specific users (or anonymous). Allow IIS trought your firewall if you have one.
Your application won't need to be changed, that's just networking problems ans configuration you will have to face to allow acces only trought LAN and WLAN.
If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1
, column2
, column3
like in this code snippet
while IFS=$'\t' read -r column1 column2 column3 ; do
printf "%b\n" "column1<${column1}>"
printf "%b\n" "column2<${column2}>"
printf "%b\n" "column3<${column3}>"
done < "myfile"
to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN
is not a good idea to do so).
Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js
Just use it like this, e.g.:
document.onclick = function (event) {
if (event.shiftKey || macKeys.shiftKey) {
//do something interesting
}
}
Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.
Go option #2. If ImportError
is thrown, then the package is not installed (or not in sys.path
).
You can also use super-assignment.
Rather than "<-" type "<<-". The function will recursively and repeatedly search one functional level higher for an object of that name. If it can't find one, it will create one on the global level.
You need to either have the message be a fixed size, or you need to send the size or you need to use some separator characters.
This is the easiest case for a known size (100 bytes):
in = new DataInputStream(server.getInputStream());
byte[] message = new byte[100]; // the well known size
in.readFully(message);
In this case DataInputStream
makes sense as it offers readFully()
. If you don't use it, you need to loop yourself until the expected number of bytes is read.
You can achieve with following way
this.projectService.create(project)
.subscribe(
result => {
console.log(result);
},
error => {
console.log(error);
this.errors = error
}
);
}
if (!this.errors) {
//route to new page
}
Works for primitives and immutable classes like String
, Wrapper classes Character, Byte.
int i=0,j=2
String s1,s2
s1 = s2 = "java rocks"
For mutable classes
Reference r1 = Reference r2 = Reference r3 = new Object();`
Three references + one object are created. All references point to the same object and your program will misbehave.
I'd like to differ with marc_s on this, who wrote:
a XSD describes the DATA aspects e.g. of a webservice - the WSDL describes the FUNCTIONS of the web services (method calls). You cannot typically figure out the method calls from your data alone.
WSDL does not describe functions. WSDL defines a network interface, which itself is comprised of endpoints that get messages and then sometimes reply with messages. WSDL describes the endpoints, and the request and reply messages. It is very much message oriented.
We often think of WSDL as a set of functions, but this is because the web services tools typically generate client-side proxies that expose the WSDL operations as methods or function calls. But the WSDL does not require this. This is a side effect of the tools.
EDIT: Also, in the general case, XSD does not define data aspects of a web service. XSD defines the elements that may be present in a compliant XML document. Such a document may be exchanged as a message over a web service endpoint, but it need not be.
Getting back to the question I would answer the original question a little differently. I woudl say YES, it is possible to generate a WSDL file given a xsd file, in the same way it is possible to generate an omelette using eggs.
EDIT: My original response has been unclear. Let me try again. I do not suggest that XSD is equivalent to WSDL, nor that an XSD is sufficient to produce a WSDL. I do say that it is possible to generate a WSDL, given an XSD file, if by that phrase you mean "to generate a WSDL using an XSD file". Doing so, you will augment the information in the XSD file to generate the WSDL. You will need to define additional things - message parts, operations, port types - none of these are present in the XSD. But it is possible to "generate a WSDL, given an XSD", with some creative effort.
If the phrase "generate a WSDL given an XSD" is taken to imply "mechanically transform an XSD into a WSDL", then the answer is NO, you cannot do that. This much should be clear given my description of the WSDL above.
When generating a WSDL using an XSD file, you will typically do something like this (note the creative steps in this procedure):
Most of the WSDL is more or less boilerplate. It can look daunting, but that is mostly because of those scary and plentiful angle brackets, I've found.
Some have suggested that this is a long-winded manual process. Maybe. But this is how you can build interoperable services. You can also use tools for defining WSDL. Dynamically generating WSDL from code will lead to interop pitfalls.
Here, since onSaveInstanceState
in fragment does not call when you add fragment into backstack. The fragment lifecycle in backstack when restored start onCreateView
and end onDestroyView
while onSaveInstanceState
is called between onDestroyView
and onDestroy
. My solution is create instance variable and init in onCreate
. Sample code:
private boolean isDataLoading = true;
private ArrayList<String> listData;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
isDataLoading = false;
// init list at once when create fragment
listData = new ArrayList();
}
And check it in onActivityCreated
:
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(isDataLoading){
fetchData();
}else{
//get saved instance variable listData()
}
}
private void fetchData(){
// do fetch data into listData
}
If your team uses TFS and you want to use Git you might want to consider a "git to tfs" bridge. Essentially you work day to day using Git on your computer, then when you want to push your changes you push them to the TFS server.
There are a couple out there (on github). I used one at my last place (along with another developer) with some success. See:
For Grammarly you can use:
<textarea data-gramm="false" />
firstarray
and secondarray
are converted to a pointer to int, when passed to printarray()
.
printarray(int arg[], ...)
is equivalent to printarray(int *arg, ...)
However, this is not specific to C++. C has the same rules for passing array names to a function.
I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:
public static void main(String[] args) {
try {
throw new RuntimeException("Cannot move file");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage());
}
}
...you will see a popup that says exactly what you want.
However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method getRootCause
:
public static void main(String[] args) {
try {
throw new Exception(new RuntimeException("Cannot move file"));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,
"Error: " + getRootCause(ex).getMessage());
}
}
public static Throwable getRootCause(Throwable throwable) {
if (throwable.getCause() != null)
return getRootCause(throwable.getCause());
return throwable;
}
Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.
You cannot have spaces around the =
sign.
When you write:
STR = "foo"
bash tries to run a command named STR
with 2 arguments (the strings =
and foo
)
When you write:
STR =foo
bash tries to run a command named STR
with 1 argument (the string =foo
)
When you write:
STR= foo
bash tries to run the command foo
with STR set to the empty string in its environment.
I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:
STR "=" "foo"
,STR "=foo"
,STR="" foo
.The relevant section of the sh language spec, section 2.9.1 states:
A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.
In that context, a word
is the command that bash is going to run. Any string containing =
(in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the =
is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo"
, STR
is not a variable assignment.
sudo is a command for Linux so it cant be used in windows so you will get that error
I wrote a small class to test which has the better performance of the two and + comes ahead of format. by a factor of 5 to 6. Try it your self
import java.io.*;
import java.util.Date;
public class StringTest{
public static void main( String[] args ){
int i = 0;
long prev_time = System.currentTimeMillis();
long time;
for( i = 0; i< 100000; i++){
String s = "Blah" + i + "Blah";
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
prev_time = System.currentTimeMillis();
for( i = 0; i<100000; i++){
String s = String.format("Blah %d Blah", i);
}
time = System.currentTimeMillis() - prev_time;
System.out.println("Time after for loop " + time);
}
}
Running the above for different N shows that both behave linearly, but String.format
is 5-30 times slower.
The reason is that in the current implementation String.format
first parses the input with regular expressions and then fills in the parameters. Concatenation with plus, on the other hand, gets optimized by javac (not by the JIT) and uses StringBuilder.append
directly.
Here are the differences that I know about:
This is how you'd do it with re:
import re
p = re.compile('^hello$', re.I)
p.match('Hello')
p.match('hello')
p.match('HELLO')
The answers did help, but I think a full implementation of this will help a lot of people.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace Dom
{
class Dom
{
public static string make_Sting_From_Dom(string reportname)
{
try
{
WebClient client = new WebClient();
client.Credentials = CredentialCache.DefaultCredentials;
// Retrieve resource as a stream
Stream data = client.OpenRead(new Uri(reportname.Trim()));
// Retrieve the text
StreamReader reader = new StreamReader(data);
string htmlContent = reader.ReadToEnd();
string mtch = "TILDE";
bool b = htmlContent.Contains(mtch);
if (b)
{
int index = htmlContent.IndexOf(mtch);
if (index >= 0)
Console.WriteLine("'{0} begins at character position {1}",
mtch, index + 1);
}
// Cleanup
data.Close();
reader.Close();
return htmlContent;
}
catch (Exception)
{
throw;
}
}
static void Main(string[] args)
{
make_Sting_From_Dom("https://www.w3.org/TR/PNG/iso_8859-1.txt");
}
}
}
Add !important
rule to display: table
of your .v-center
class.
.v-center {
display:table !important;
border:2px solid gray;
height:300px;
}
Your display property is being overridden by bootstrap to display: block
.
What you have is a fairly unusual use of the ternary operator. Usually it is used as an expression, not a statement, inside of some other operation, e.g.:
var y = (x == 2 ? "yes" : "no");
So, for readability (because what you are doing is unusual), and because it avoids the "else" that you don't want, I would suggest:
if (x==2) doSomething();
A hacky way to do it without stored procedures or functions would be to create a settings table in your database, with columns Id, Param1, Param2, etc. Insert a row into that table containing the values Id=1,Param1=0,Param2=0, etc. Then you can add a join to that table in your view to create the desired effect, and update the settings table before running the view. If you have multiple users updating the settings table and running the view concurrently things could go wrong, but otherwise it should work OK. Something like:
CREATE VIEW v_emp
AS
SELECT *
FROM emp E
INNER JOIN settings S
ON S.Id = 1 AND E.emp_id = S.Param1
Try this?
encodeURIComponent('space word').replace(/%20/g,'+')
Try this
outline: none;
live demo https://codepen.io/wenpingguo/pen/KQgbXq
If you getting a blank screen, that may be because of 2 reasons:
Browser blocking the Frames from being displayed. In some browsers the frames are considered as unsafe. To overcome this you can launch the frameless version of phpPgAdmin by
http://-your-domain-name-/intro.php
You have enabled a security feature in Nginx for X-Frame-Options try disabling it.
Only one app is automatically initialized. Others have to manually initialized as follows:
Syntax:
angular.bootstrap(element, [modules]);
Example:
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<script src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8" data-require="[email protected]"></script>_x000D_
<script data-require="[email protected]" data-semver="0.2.18" src="//cdn.rawgit.com/angular-ui/ui-router/0.2.18/release/angular-ui-router.js"></script>_x000D_
<link rel="stylesheet" href="style.css" />_x000D_
<script>_x000D_
var parentApp = angular.module('parentApp', [])_x000D_
.controller('MainParentCtrl', function($scope) {_x000D_
$scope.name = 'universe';_x000D_
});_x000D_
_x000D_
_x000D_
_x000D_
var childApp = angular.module('childApp', ['parentApp'])_x000D_
.controller('MainChildCtrl', function($scope) {_x000D_
$scope.name = 'world';_x000D_
});_x000D_
_x000D_
_x000D_
angular.element(document).ready(function() {_x000D_
angular.bootstrap(document.getElementById('childApp'), ['childApp']);_x000D_
});_x000D_
_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="childApp">_x000D_
<div ng-controller="MainParentCtrl">_x000D_
Hello {{name}} !_x000D_
<div>_x000D_
<div ng-controller="MainChildCtrl">_x000D_
Hello {{name}} !_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
@Transactional
@RequestMapping(value = { "/getDatabaseTables" }, method = RequestMethod.GET)
public @ResponseBody String getDatabaseTables() throws Exception{
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
DatabaseMetaData md = con.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
HashMap<String,List<String>> databaseTables = new HashMap<String,List<String>>();
List<String> tables = new ArrayList<String>();
String db = "";
while (rs.next()) {
tables.add(rs.getString(3));
db = rs.getString(1);
}
List<String> database = new ArrayList<String>();
database.add(db);
databaseTables.put("database", database);
Collections.reverse(tables);
databaseTables.put("tables", tables);
return new ObjectMapper().writeValueAsString(databaseTables);
}
@Transactional
@RequestMapping(value = { "/getTableDetails" }, method = RequestMethod.GET)
public @ResponseBody String getTableDetails(@RequestParam(value="tablename")String tablename) throws Exception{
System.out.println("...tablename......"+tablename);
Connection con = ((SessionImpl) sessionFactory.getCurrentSession()).connection();
Statement st = con.createStatement();
String sql = "select * from "+tablename;
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
List<HashMap<String,String>> databaseColumns = new ArrayList<HashMap<String,String>>();
HashMap<String,String> columnDetails = new HashMap<String,String>();
for (int i = 0; i < rowCount; i++) {
columnDetails = new HashMap<String,String>();
Method method = com.mysql.jdbc.ResultSetMetaData.class.getDeclaredMethod("getField", int.class);
method.setAccessible(true);
com.mysql.jdbc.Field field = (com.mysql.jdbc.Field) method.invoke(metaData, i+1);
columnDetails.put("columnName", field.getName());//metaData.getColumnName(i + 1));
columnDetails.put("columnType", metaData.getColumnTypeName(i + 1));
columnDetails.put("columnSize", field.getLength()+"");//metaData.getColumnDisplaySize(i + 1)+"");
columnDetails.put("columnColl", field.getCollation());
columnDetails.put("columnNull", ((metaData.isNullable(i + 1)==0)?"NO":"YES"));
if (field.isPrimaryKey()) {
columnDetails.put("columnKEY", "PRI");
} else if(field.isMultipleKey()) {
columnDetails.put("columnKEY", "MUL");
} else if(field.isUniqueKey()) {
columnDetails.put("columnKEY", "UNI");
} else {
columnDetails.put("columnKEY", "");
}
columnDetails.put("columnAINC", (field.isAutoIncrement()?"AUTO_INC":""));
databaseColumns.add(columnDetails);
}
HashMap<String,List<HashMap<String,String>>> tableColumns = new HashMap<String,List<HashMap<String,String>>>();
Collections.reverse(databaseColumns);
tableColumns.put("columns", databaseColumns);
return new ObjectMapper().writeValueAsString(tableColumns);
}
#1 & #2 what are the purposes of using a fragment & what are the advantages and disadvantages of using fragments compared to using activities/views/layouts?
Fragments are Android's solution to creating reusable user interfaces. You can achieve some of the same things using activities and layouts (for example by using includes). However; fragments are wired in to the Android API, from HoneyComb, and up. Let me elaborate;
The ActionBar
. If you want tabs up there to navigate your app, you quickly see that ActionBar.TabListener
interface gives you a FragmentTransaction
as an input argument to the onTabSelected
method. You could probably ignore this, and do something else and clever, but you'd be working against the API, not with it.
The FragmentManager
handles «back» for you in a very clever way. Back does not mean back to the last activity, like for regular activities. It means back to the previous fragment state.
You can use the cool ViewPager
with a FragmentPagerAdapter
to create swipe interfaces. The FragmentPagerAdapter
code is much cleaner than a regular adapter, and it controls instantiations of the individual fragments.
Your life will be a lot easier if you use Fragments when you try to create applications for both phones and tablets. Since the fragments are so tied in with the Honeycomb+ APIs, you will want to use them on phones as well to reuse code. That's where the compatibility library comes in handy.
You even could and should use fragments for apps meant for phones only. If you have portability in mind. I use ActionBarSherlock
and the compatibility libraries to create "ICS looking" apps, that look the same all the way back to version 1.6. You get the latest features like the ActionBar
, with tabs, overflow, split action bar, viewpager etc.
Bonus 2
The best way to communicate between fragments are intents. When you press something in a Fragment you would typically call StartActivity()
with data on it. The intent is passed on to all fragments of the activity you launch.
J Bryan Price, a good example, but there are shortcomings
{\"response\":[123, 456, {\"name\":\"John\"}, {\"count\":3}]}
after formatting
{
"response" : [
123,
456,
{
"name" : "John"
},
{
"count" : 3
}
]
}
improper bias :(
Here is the simple API-less "readable script" version I use for pre-padding a string. (Simple, Readable, and Adjustable).
while(str.length() < desired_length)
str = '0'+str;
For this you have to use HtmlAttributes, but there is a catch: HtmlAttributes and css class .
you can define it like this:
new { Attrubute="Value", AttributeTwo = IntegerValue, @class="className" };
and here is a more realistic example:
new { style="width:50px" };
new { style="width:50px", maxsize = 50 };
new {size=30, @class="required"}
and finally in:
MVC 1
<%= Html.TextBox("test", new { style="width:50px" }) %>
MVC 2
<%= Html.TextBox("test", null, new { style="width:50px" }) %>
MVC 3
@Html.TextBox("test", null, new { style="width:50px" })
If you are working with MVVM Light you have to use the System.Windows.Interactivity Version 4.0
(the NuGet .dll wont work) that you can find under :
PathToProjectFolder\Software\packages\MvvmLightLibs.5.4.1.1\lib\net45\System.Windows.Interactivity.dll
Just add this .dll manually as Reference and it should be fine.
I achieved this via -
<p style="display:none">{{user.role="store_user"}}</p>
please go to
View > Toolbars > Customize
then select "Data" categories then click "Show data source" in command panel
"Data" menu will be seen in menu panel. click to get the website data source
You can use this line to print the contents of your desktop:
FOR %%I in (C:\windows\desktop\*.*) DO echo %%I
Once you have the %%I
variable it's easy to perform a command on it (just replace the word echo with your program)
In addition, substitution of FOR variable references has been enhanced You can now use the following optional syntax:
%~I - expands %I removing any surrounding quotes (")
%~fI - expands %I to a fully qualified path name
%~dI - expands %I to a drive letter only
%~pI - expands %I to a path only (directory with \)
%~nI - expands %I to a file name only
%~xI - expands %I to a file extension only
%~sI - expanded path contains short names only
%~aI - expands %I to file attributes of file
%~tI - expands %I to date/time of file
%~zI - expands %I to size of file
%~$PATH:I - searches the directories listed in the PATH
environment variable and expands %I to the
fully qualified name of the first one found.
If the environment variable name is not
defined or the file is not found by the
search, then this modifier expands to the
empty string
https://ss64.com/nt/syntax-args.html
In the above examples %I
and PATH can be replaced by other valid
values. The %~
syntax is terminated by a valid FOR variable name.
Picking upper case variable names like %I
makes it more readable and
avoids confusion with the modifiers, which are not case sensitive.
You can get the full documentation by typing FOR /?
change parent="android:Theme.Holo.Dark"
to parent="android:Theme.Holo"
The holo dark theme is called Holo
var arr = []
while(arr.length < 8){
var randomnumber=Math.ceil(Math.random()*100)
if(arr.indexOf(randomnumber) === -1){arr.push(randomnumber)}
}
document.write(arr);
shorter than other answers I've seen
atoi can do that for you
Example:
char string[] = "1234";
int sum = atoi( string );
printf("Sum = %d\n", sum ); // Outputs: Sum = 1234
You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest()
. A function to do this would look like the following:
def File_Checksum_Dis(dirname):
if not os.path.exists(dirname):
print(dirname+" directory is not existing");
for fname in os.listdir(dirname):
if not fname.endswith('~'):
fnaav = os.path.join(dirname, fname);
fd = open(fnaav, 'rb');
data = fd.read();
fd.close();
print("-"*70);
print("File Name is: ",fname);
print(hashlib.md5(data).hexdigest())
print("-"*70);
You can use Nexmo to send SMS as well as receive SMS.
Sending SMS with the Nexmo Java Library is fairly straightforward. After creating a new account, renting a virtual number, and getting your API key & secret you can use the library to send SMS like so:
public class SendSMS {
public static void main(String[] args) throws Exception {
AuthMethod auth = new TokenAuthMethod(API_KEY, API_SECRET);
NexmoClient client = new NexmoClient(auth);
TextMessage message = new TextMessage(FROM_NUMBER, TO_NUMBER, "Hello from Nexmo!");
//There may be more than one response if the SMS sent is more than 160 characters.
SmsSubmissionResult[] responses = client.getSmsClient().submitMessage(message);
for (SmsSubmissionResult response : responses) {
System.out.println(response);
}
}
}
To receive SMS you'll need to set up a server that consumes a webhook. That's fairly simple as well. I recommend checking out our tutorial on receiving SMS with Java.
Disclosure: I work for Nexmo
Inspired by cyptus's answer I used
_dbContext.Database.CreateIfNotExists();
on EF6 before the first database contact (before DB seeding).
Use the ToDictionary
method directly.
var result =
// as Jon Skeet pointed out, OrderBy is useless here, I just leave it
// show how to use OrderBy in a LINQ query
myClassCollection.OrderBy(mc => mc.SomePropToSortOn)
.ToDictionary(mc => mc.KeyProp.ToString(),
mc => mc.ValueProp.ToString(),
StringComparer.OrdinalIgnoreCase);
To see your log in SQL Developer
then press:
CTRL+SHIFT + L (or CTRL + CMD + L on macOS)
or
View -> Log
or by using mysql query
show errors;
.* will match any characters in regular expressions
I think the java syntax would be
"digital".matches(".*ital.*");
And for the single character match just use a single dot.
"digital".matches(".*gi.a.*");
And to match an actual dot, escape it as slash dot
\.
I've found quite straight forward solution, The idea is to copy repository and then just remove unnecessary part. This is how it works:
1) Clone a repository you'd like to split
git clone [email protected]:testrepo/test.git
2) Move to git folder
cd test/
2) Remove unnecessary folders and commit it
rm -r ABC/
git add .
enter code here
git commit -m 'Remove ABC'
3) Remove unnecessary folder(s) form history with BFG
cd ..
java -jar bfg.jar --delete-folders "{ABC}" test
cd test/
git reflog expire --expire=now --all && git gc --prune=now --aggressive
for multiply folders you can use comma
java -jar bfg.jar --delete-folders "{ABC1,ABC2}" metric.git
4) Check that history doesn't contains the files/folders you just deleted
git log --diff-filter=D --summary | grep delete
5) Now you have clean repository without ABC, so just push it into new origin
remote add origin [email protected]:username/new_repo
git push -u origin master
That's it. You can repeat the steps to get another repository,
just remove XY1,XY2 and rename XYZ -> ABC on step 3
On Linux, Unix, Git Bash, or Cygwin, try:
rm -f .git/index.lock
On Windows Command Prompt, try:
del .git\index.lock
For Windows:
From a PowerShell console opened as administrator, try
rm -Force ./.git/index.lock
If that does not work, you must kill all git.exe processes
taskkill /F /IM git.exe
SUCCESS: The process "git.exe" with PID 20448 has been terminated.
SUCCESS: The process "git.exe" with PID 11312 has been terminated.
SUCCESS: The process "git.exe" with PID 23868 has been terminated.
SUCCESS: The process "git.exe" with PID 27496 has been terminated.
SUCCESS: The process "git.exe" with PID 33480 has been terminated.
SUCCESS: The process "git.exe" with PID 28036 has been terminated. \
rm -Force ./.git/index.lock
I would use
def example(arg1, arg2, arg3):
if arg1 == 1 and arg2 == 2 and arg3 == 3:
print("Example Text")
The and
operator is identical to the logic gate with the same name; it will return 1 if and only if all of the inputs are 1. You can also use or
operator if you want that logic gate.
EDIT: Actually, the code provided in your post works fine with me. I don't see any problems with that. I think that this might be a problem with your Python, not the actual language.
You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?
Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.
Use !==
as !=
will get you into a world of nontransitive JavaScript truth table weirdness.
There is a project on CodeProject that makes it simple to convert an XML file to SQL Script. It uses XSLT. You could probably modify it to generate the DDL too.
And See this question too : Generating SQL using XML and XSLT
For anyone having trouble adjusting table / cell width using the fixed header plugin:
Datatables relies on thead tags for column width parameters. This is because its really the only native html as most of the table's inner html gets auto-generated.
However, what happens is some of your cell can be larger than the width stored inside the thead cells.
I.e. if your table has a lot of columns (wide table) and your rows have a lot of data, then calling "sWidth": to change the td cell size won't work properly because the child rows are automatically resizing td's based on overflow content and this happens after the table's been initialized and passed its init params.
The original thead "sWidth": parameters get overridden (shrunk) because datatables thinks your table still has its default width of %100--it doesn't recognize that some cells are overflowed.
To fix this I figured out the overflow width and accounted for it by resizing the table accordingly after the table has been initialized--while we're at it we can init our fixed header at the same time:
$(document).ready(function() {
$('table').css('width', '120%');
new FixedHeader(dTable, {
"offsetTop": 40,
});
});
You never created an instance.
You've defined average as an instance method, thus, in order to use average you need to create an instance first.
If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^
. Then add all files and commit again.
Try this as it worked for me...
courtesy of Last paragraph mentioned in here
With latest versions of docker, this is enough:
docker run -ti --privileged ubuntu bash
It will give access to all system resources (in /dev for instance)
You can accomplish this with:
SessionFactory sessionFactory =
entityManagerFactory.unwrap(SessionFactory.class);
where entityManagerFactory is an JPA EntityManagerFactory
.
package net.andreaskluth.hibernatesample;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SomeService {
private SessionFactory hibernateFactory;
@Autowired
public SomeService(EntityManagerFactory factory) {
if(factory.unwrap(SessionFactory.class) == null){
throw new NullPointerException("factory is not a hibernate factory");
}
this.hibernateFactory = factory.unwrap(SessionFactory.class);
}
}
The terms resource and endpoint are often used synonymously. But in fact they do not mean the same thing.
The term endpoint is focused on the URL that is used to make a request.
The term resource is focused on the data set that is returned by a request.
Now, the same resource can often be accessed by multiple different endpoints.
Also the same endpoint can return different resources, depending on a query string.
Let us see some examples:
Have a look at the following examples of different endpoints:
/api/companies/5/employees/3
/api/v2/companies/5/employees/3
/api/employees/3
They obviously could all access the very same resource in a given API.
Also an existing API could be changed completely. This could lead to new endpoints that would access the same old resources using totally new and different URLs:
/api/employees/3
/new_api/staff/3
If your endpoint returns a collection, you could implement searching/filtering/sorting using query strings. As a result the following URLs all use the same endpoint (/api/companies
), but they can return different resources (or resource collections, which by definition are resources in themselves):
/api/companies
/api/companies?sort=name_asc
/api/companies?location=germany
/api/companies?search=siemens
Since you have not mentioned what needs to be copied, I have left that section empty in the code below.
Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.
This will get you started. I have commented the code so that you will not face any problem understanding it.
First paste the below mentioned code in the outlook module.
Then
When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.
UNTESTED
Const xlUp As Long = -4162
Sub ExportToExcel(MyMail As MailItem)
Dim strID As String, olNS As Outlook.Namespace
Dim olMail As Outlook.MailItem
Dim strFileName As String
'~~> Excel Variables
Dim oXLApp As Object, oXLwb As Object, oXLws As Object
Dim lRow As Long
strID = MyMail.EntryID
Set olNS = Application.GetNamespace("MAPI")
Set olMail = olNS.GetItemFromID(strID)
'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")
'~~> If not found then create new instance
If Err.Number <> 0 Then
Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0
'~~> Show Excel
oXLApp.Visible = True
'~~> Open the relevant file
Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")
'~~> Set the relevant output sheet. Change as applicable
Set oXLws = oXLwb.Sheets("Sheet1")
lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1
'~~> Write to outlook
With oXLws
'
'~~> Code here to output data from email to Excel File
'~~> For example
'
.Range("A" & lRow).Value = olMail.Subject
.Range("B" & lRow).Value = olMail.SenderName
'
End With
'~~> Close and Clean up Excel
oXLwb.Close (True)
oXLApp.Quit
Set oXLws = Nothing
Set oXLwb = Nothing
Set oXLApp = Nothing
Set olMail = Nothing
Set olNS = Nothing
End Sub
FOLLOWUP
To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example
Dim MyAr() As String
MyAr = Split(olMail.body, vbCrLf)
For i = LBound(MyAr) To UBound(MyAr)
'~~> This will give you the contents of your email
'~~> on separate lines
Debug.Print MyAr(i)
Next i
For OpenFileDialog:
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true
}
For FolderBrowserDialog:
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description";
if (fbd.ShowDialog() == DialogResult.OK)
{
string sSelectedPath = fbd.SelectedPath;
}
To access selected folder
and selected file name
you can declare both string at class level.
namespace filereplacer
{
public partial class Form1 : Form
{
string sSelectedFile;
string sSelectedFolder;
public Form1()
{
InitializeComponent();
}
private void direc_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
//fbd.Description = "Custom Description"; //not mandatory
if (fbd.ShowDialog() == DialogResult.OK)
sSelectedFolder = fbd.SelectedPath;
else
sSelectedFolder = string.Empty;
}
private void choof_Click(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;
if (choofdlog.ShowDialog() == DialogResult.OK)
sSelectedFile = choofdlog.FileName;
else
sSelectedFile = string.Empty;
}
private void replacebtn_Click(object sender, EventArgs e)
{
if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
{
//use selected folder path and file path
}
}
....
}
NOTE:
As you have kept choofdlog.Multiselect=true;
, that means in the OpenFileDialog()
you are able to select multiple files (by pressing ctrl
key and left mouse click for selection).
In that case you could get all selected files in string[]
:
At Class Level:
string[] arrAllFiles;
Locate this line (when Multiselect=true
this line gives first file only):
sSelectedFile = choofdlog.FileName;
To get all files use this:
arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files
An ES6 approach to clearing a group of radio buttons:
Array.from( document.querySelectorAll('input[name="group-name"]:checked'), input => input.checked = false );
Copied over from comment by @sloth
Instead of YourCollection.FirstOrDefault()
, you could use YourCollection.DefaultIfEmpty(YourDefault).First()
for example.
Example:
var viewModel = new CustomerDetailsViewModel
{
MainResidenceAddressSection = (MainResidenceAddressSection)addresses.DefaultIfEmpty(new MainResidenceAddressSection()).FirstOrDefault( o => o is MainResidenceAddressSection),
RiskAddressSection = addresses.DefaultIfEmpty(new RiskAddressSection()).FirstOrDefault(o => !(o is MainResidenceAddressSection)),
};
If you want to run the same command on multiple instances you can do this :
for i in c1 dm1 dm2 ds1 ds2 gtm_m gtm_sl; do docker exec -it $i /bin/bash -c "service sshd start"; done
Listing all foreign keys in a db including description
SELECT
i1.CONSTRAINT_NAME, i1.TABLE_NAME,i1.COLUMN_NAME,
i1.REFERENCED_TABLE_SCHEMA,i1.REFERENCED_TABLE_NAME, i1.REFERENCED_COLUMN_NAME,
i2.UPDATE_RULE, i2.DELETE_RULE
FROM
information_schema.KEY_COLUMN_USAGE AS i1
INNER JOIN
information_schema.REFERENTIAL_CONSTRAINTS AS i2
ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.REFERENCED_TABLE_NAME IS NOT NULL
AND i1.TABLE_SCHEMA ='db_name';
restricting to a specific column in a table table
AND i1.table_name = 'target_tb_name' AND i1.column_name = 'target_col_name'
Try this:
x = a > b and 10 or 11
This is a sample of execution:
>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11
With the distinct
keyword with single and multiple column names, you get distinct records:
SELECT DISTINCT column 1, column 2, ...
FROM table_name;
The rules for turning on the carry flag in binary/integer math are two:
The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)
The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).
In unsigned arithmetic, watch the carry flag to detect errors.
In signed arithmetic, the carry flag tells you nothing interesting.
The rules for turning on the overflow flag in binary/integer math are two:
If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)
If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)
Otherwise the "overflow" flag is turned off
Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.
If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.
If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.
For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt
You could consider using an external tool like ffmpeg to merge the images into a movie (see answer here) or you could try to use OpenCv to combine the images into a movie like the example here.
I'm attaching below a code snipped I used to combine all png files from a folder called "images" into a video.
import cv2
import os
image_folder = 'images'
video_name = 'video.avi'
images = [img for img in os.listdir(image_folder) if img.endswith(".png")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape
video = cv2.VideoWriter(video_name, 0, 1, (width,height))
for image in images:
video.write(cv2.imread(os.path.join(image_folder, image)))
cv2.destroyAllWindows()
video.release()
If it has something to do control updates on cached pages here I have a nice method how to do this.
www.yoursite.com/page/about?getVer=1&__[date]
This method requires at least one request even when no request is needed because it already exists in the local browser cache. But the overhead is less comparing to using no cache at all (to be sure the page will show the right updated content). This requires just a few bytes for each page request instead of all content for each page.
IMPORTANT: The version info request must be implemented on your server otherwise it will return the whole page.
Example of version string returned by www.yoursite.com/page/about?getVer=1&__[date]
:
skg2pl-v8kqb
To give you an example in code, here is a part of my library (I don't think you can use it but maybe it gives you some idea how to do it):
o.gCheckDocVersion = function() // Because of the hard caching method, check document for changes with ajax
{
var sUrl = o.getQuerylessUrl(window.location.href),
sDocVer = o.gGetData( sUrl, false );
o.ajaxRequest({ url:sUrl+'?getVer=1&'+o.uniqueId(), cache:0, dataType:'text' },
function(sVer)
{
if( typeof sVer == 'string' && sVer.length )
{
var bReload = (( typeof sDocVer == 'string' ) && sDocVer != sVer );
if( bReload || !sDocVer )
{
o.gSetData( sUrl, sVer );
sDocVer = o.gGetData( sUrl, false );
if( bReload && ( typeof sDocVer != 'string' || sDocVer != sVer ))
{ bReload = false; }
}
if( bReload )
{ // Hard refresh page contents
window.location.reload(true); }
}
}, false, false );
};
If you are using version independent resources like javascript or css files, add versionnumbers (implemented with a url rewrite and not with a query because they mostly won't be cached). For example: www.yoursite.com/ver-01/about.js
For me, this method is working great, maybe it can help you too.
This is precisely the sort of scenario where analytics come to the rescue.
Given this test data:
SQL> select * from employment_history
2 order by Gc_Staff_Number
3 , start_date
4 /
GC_STAFF_NUMBER START_DAT END_DATE C
--------------- --------- --------- -
1111 16-OCT-09 Y
2222 08-MAR-08 26-MAY-09 N
2222 12-DEC-09 Y
3333 18-MAR-07 08-MAR-08 N
3333 01-JUL-09 21-MAR-09 N
3333 30-JUL-10 Y
6 rows selected.
SQL>
An inline view with an analytic LAG() function provides the right answer:
SQL> select Gc_Staff_Number
2 , start_date
3 , prev_end_date
4 from (
5 select Gc_Staff_Number
6 , start_date
7 , lag (end_date) over (partition by Gc_Staff_Number
8 order by start_date )
9 as prev_end_date
10 , current_flag
11 from employment_history
12 )
13 where current_flag = 'Y'
14 /
GC_STAFF_NUMBER START_DAT PREV_END_
--------------- --------- ---------
1111 16-OCT-09
2222 12-DEC-09 26-MAY-09
3333 30-JUL-10 21-MAR-09
SQL>
The inline view is crucial to getting the right result. Otherwise the filter on CURRENT_FLAG removes the previous rows.
I was able to get it to work by following these instructions.
Download the sample code
Unzip it to a new location
Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)
Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to)
Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs:
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
Run (hit F5)
There's no need for "else" in this case:
IF EXISTS(SELECT * FROM table1 WHERE Name='John' ) return 1
return 0
Yes, sleep is probably the function of choice here. Note that the time passed into the function is the smallest amount of time the calling thread will be inactive. So for example if you call sleep with 5 seconds, you're guaranteed your thread will be sleeping for at least 5 seconds. Could be 6, or 8 or 50, depending on what the OS is doing. (During optimal OS execution, this will be very close to 5.)
Another useful feature of the sleep function is to pass in 0. This will force a context switch from your thread.
Some additional information:
http://www.opengroup.org/onlinepubs/000095399/functions/sleep.html
If you're in Rails, .blank?
should be the method you are looking for:
a = nil
b = []
c = ""
a.blank? #=> true
b.blank? #=> true
c.blank? #=> true
d = "1"
e = ["1"]
d.blank? #=> false
e.blank? #=> false
So the answer would be:
variable = id if variable.blank?
The simplest way is to:
ssh-keygen
[enter]
[enter]
[enter]
cd ~/.ssh
ssh-copy-id -i id_rsa.pub USERNAME@SERVERTARGET
Att:
Its very very simple.
In manual of "ss-keygen" explains:
"DESCRIPTION ssh-keygen generates, manages and converts authentication keys for ssh(1). ssh-keygen can create RSA keys for use by SSH protocol version 1 and DSA, ECDSA or RSA keys for use by SSH protocol version 2. The type of key to be generated is specified with the -t option. If invoked without any arguments, ssh-keygen will generate an RSA key for use in SSH protocol 2 connections."
I suggest a custom alias on you .gitconfig
.
You have to way to do:
1) With git command:
git config --global alias.check-file <command>
2) Editing ~/.gitconfig
and add this line on alias section:
[alias]
check-file = "!f() { if [ $# -eq 0 ]; then echo 'Filename missing!'; else tracked=$(git ls-files ${1}); if [[ -z ${tracked} ]]; then echo 'File not tracked'; else echo 'File tracked'; fi; fi; }; f"
Once launched command (1) or saved file (2), on your workspace you can test it:
$ git check-file
$ Filename missing
$ git check-file README.md
$ File tracked
$ git check-file foo
$ File not tracked
Use Val(txtPrice.text)
I would also allow only number and the dot char by inserting some validation code in the key press event of the price text box.
win cmd
C:\>adb shell id
uid=2000(shell) gid=2000(shell)
C:\>adb shell 'su -c id'
/system/bin/sh: su -c id: inaccessible or not found
C:\>adb shell "su -c id"
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
C:\>adb shell su -c id
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
win msys bash
msys2@bash:~$ adb shell 'su -c id'
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
msys2@bash:~$ adb shell "su -c id"
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
msys2@bash:~$ adb shell su -c id
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
if want run am
cmd, -t
option maybe required:
C:\>adb shell su -c am stack list
cmd: Failure calling service activity: Failed transaction (2147483646)
C:\>adb shell -t su -c am stack list
Stack id=0 bounds=[0,0][1200,1920] displayId=0 userId=0
...
shell options:
shell [-e ESCAPE] [-n] [-Tt] [-x] [COMMAND...]
run remote shell command (interactive shell if no command given)
-e: choose escape character, or "none"; default '~'
-n: don't read from stdin
-T: disable pty allocation
-t: allocate a pty if on a tty (-tt: force pty allocation)
-x: disable remote exit codes and stdout/stderr separation
Android Debug Bridge version 1.0.41
Version 30.0.5-6877874
Get the data you need and combine it in the String;
getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
getHours();
getMinutes();
Check out : Working With Dates
Are you meaning?
data2 <- data1[good,]
With
data1[good]
you're selecting columns in a wrong way (using a logical vector of complete rows).
Consider that parameter pollutant
is not used; is it a column name that you want to extract? if so it should be something like
data2 <- data1[good, pollutant]
Furthermore consider that you have to rbind
the data.frame
s inside the for
loop, otherwise you get only the last data.frame (its completed.cases)
And last but not least, i'd prefer generating filenames eg with
id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")
A little modified chunk of ?sprintf
The string fmt
(in our case "%3d"
) contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through ...
. The allowed conversion specifications start with a %
and end with one of the letters in the set aAdifeEgGosxX%
. These letters denote the following types:
d
: integerEg a more general example
sprintf("I am %10d years old", 25)
[1] "I am 25 years old"
^^^^^^^^^^
| |
1 10
For Python3+ URLopener
is deprecated.
And when used you will get error as below:
url_opener = urllib.URLopener() AttributeError: module 'urllib' has no attribute 'URLopener'
So, try:
import urllib.request
urllib.request.urlretrieve(url, filename)
The CONTINUE
statement is a new feature in 11g.
Here is a related question: 'CONTINUE' keyword in Oracle 10g PL/SQL
Just use DROP TABLE IF EXISTS
:
DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );
Try searching the MySQL documentation first if you have any other problems.
above given methods are for if you have an web url ,but if you have an local html then you can have also html by this code
AssetManager mgr = mContext.getAssets();
try {
InputStream in = null;
if(condition)//you have a local html saved in assets
{
in = mgr.open(mFileName,AssetManager.ACCESS_BUFFER);
}
else if(condition)//you have an url
{
URL feedURL = new URL(sURL);
in = feedURL.openConnection().getInputStream();}
// here you will get your html
String sHTML = streamToString(in);
in.close();
//display this html in the browser or web view
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
public static String streamToString(InputStream in) throws IOException {
if(in == null) {
return "";
}
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
}
return writer.toString();
}
In my experience, don't use ffmpeg for splitting/join.
MP4Box, is faster and light than ffmpeg. Please tryit.
Eg if you want to split a 1400mb MP4 file into two parts a 700mb you can use the following cmdl:
MP4Box -splits 716800 input.mp4
eg for concatenating two files you can use:
MP4Box -cat file1.mp4 -cat file2.mp4 output.mp4
Or if you need split by time, use -splitx StartTime:EndTime
:
MP4Box -add input.mp4 -splitx 0:15 -new split.mp4
... And the answer is:
Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")
The Set
makes all the difference. Then it works like a charm.
If I read the specification correctly, no.
You can match on an element, the name of an attribute in the element, and the value of a named attribute in an element. I don't see anything for matching content within an element, though.
Get requests should not have content-type because they do not have request entity (that is, a body)
What we do, is to create two tables for each multilingual object.
E.g. the first table contains only language-neutral data (primary key, etc.) and the second table contains one record per language, containing the localized data plus the ISO code of the language.
In some cases we add a DefaultLanguage field, so that we can fall-back to that language if no localized data is available for a specified language.
Example:
Table "Product":
----------------
ID : int
<any other language-neutral fields>
Table "ProductTranslations"
---------------------------
ID : int (foreign key referencing the Product)
Language : varchar (e.g. "en-US", "de-CH")
IsDefault : bit
ProductDescription : nvarchar
<any other localized data>
With this approach, you can handle as many languages as needed (without having to add additional fields for each new language).
Update (2014-12-14): please have a look at this answer, for some additional information about the implementation used to load multilingual data into an application.
I changed google-services classpath version from 4.2.0 to 3.0.0
classpath 'com.google.gms:google-services:3.0.0'
Then rebuild the project, Then strangely it suggested me to add firebase core to the project.
Then I added firebase core on the app(module)
implementation 'com.google.firebase:firebase-messaging:16.0.8'
Then the error disappeared magically.
There are a number of good answers in here but most of them make the assumption that the user wants an "API" solution where they must write code to connect to a 3rd-party service and/or screen scrape the USPS. This is all well and good, but should be factored into the business requirements and costs associated with the implementation and then weighed against the desired benefits.
Depending upon the business requirements and the way that the data is received into the system, a real-time address processing solution may be the best bet. If a real-time solution is required, you will want to consider the license agreement and technical limitations of the Google Maps/Bing/Yahoo APIs. They typically limit the number of calls you can make each day. The USPS web tools API is the same in additional they restrict how/why you can use their system and how you are allowed to use the data thereafter.
At the same time, there are a handful of great service providers that can easily process a static list of addresses. Essentially, you give the service provider a CSV file or Excel file, they clean it up and get it back to you. It's a one-time deal with no long-term commitment or obligation—usually.
Full disclosure: I'm the founder of SmartyStreets. We do address verification for addresses within the United States. We are easily able to CASS certify a list and we also offer a address verification web service API. We have no hidden fees, contracts, or anything. You use our service until you no longer need it and you can walk away. (Unlike cell phone companies that require a contract.)
I had same problem, and have the latest ver Microsoft Visual Studio Community 2017 Version 15.7.3
I just downloaded the latest SDK 2.1 and no more targeting issue. https://www.microsoft.com/net/download/thank-you/dotnet-sdk-2.1.301-windows-x64-installer
Info: Microsoft Visual Studio Community 2017 Version 15.7.3 VisualStudio.15.Release/15.7.3+27703.2026 Microsoft .NET Framework Version 4.7.03056
Installed Version: Community
C# Tools 2.8.3-beta6-62923-07. Commit Hash: 7aafab561e449da50712e16c9e81742b8e7a2969 C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.
Common Azure Tools 1.10 Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.
NuGet Package Manager 4.6.0 NuGet Package Manager in Visual Studio. For more information about NuGet, visit http://docs.nuget.org/.
ProjectServicesPackage Extension 1.0 ProjectServicesPackage Visual Studio Extension Detailed Info
ResourcePackage Extension 1.0 ResourcePackage Visual Studio Extension Detailed Info
Visual Basic Tools 2.8.3-beta6-62923-07. Commit Hash: 7aafab561e449da50712e16c9e81742b8e7a2969 Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.
Visual Studio Code Debug Adapter Host Package 1.0 Interop layer for hosting Visual Studio Code debug adapters in Visual Studio
Visual Studio Tools for Unity 3.7.0.1 Visual Studio Tools for Unity
Just simply
var tar = (TargetFrameworkAttribute)Assembly
.LoadFrom("yoursAssembly.dll")
.GetCustomAttributes(typeof(TargetFrameworkAttribute)).First();
Add .done() to your function
var id;
var vname;
function ajaxCall(){
for(var q = 1; q<=10; q++){
$.ajax({
url: 'api.php',
data: 'id1='+q+'',
dataType: 'json',
async:false,
success: function(data)
{
id = data[0];
vname = data[1];
}
}).done(function(){
printWithAjax();
});
}//end of the for statement
}//end of ajax call function
I think the cool thing about using a dynamic language like Python is you really shouldn't have to check something like that.
I would just call the required methods on your object and catch an AttributeError
. Later on this will allow you to call your methods with other (seemingly unrelated) objects to accomplish different tasks, such as mocking an object for testing.
I've used this a lot when getting data off the web with urllib2.urlopen()
which returns a file like object. This can in turn can be passed to almost any method that reads from a file, because it implements the same read()
method as a real file.
But I'm sure there is a time and place for using isinstance()
, otherwise it probably wouldn't be there :)
does it matter? people are generally smart enough to interpret messages correctly, if they aren't you probably shouldn't let them access your repository anyway!
There are a few different limits that might come in to play in determining the number of connections an Oracle database supports. The simplest approach would be to use the SESSIONS parameter and V$SESSION, i.e.
The number of sessions the database was configured to allow
SELECT name, value
FROM v$parameter
WHERE name = 'sessions'
The number of sessions currently active
SELECT COUNT(*)
FROM v$session
As I said, though, there are other potential limits both at the database level and at the operating system level and depending on whether shared server has been configured. If shared server is ignored, you may well hit the limit of the PROCESSES parameter before you hit the limit of the SESSIONS parameter. And you may hit operating system limits because each session requires a certain amount of RAM.
This is mostly covered already, but one addition as I ran into an issue with the previous code samples.
Dim strHTML as String = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/folder/filename.html"))
There are multiple ways to remove an element from an Array. Let me point out most used options below. I'm writing this answer because I couldn't find a proper reason as to what to use from all of these options. The answer to the question is option 3 (Splice()).
1) SHIFT() - Remove First Element from Original Array and Return the First Element
See reference for Array.prototype.shift(). Use this only if you want to remove the first element, and only if you are okay with changing the original array.
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
2) SLICE() - Returns a Copy of the Array, Separated by a Begin Index and an End Index
See reference for Array.prototype.slice(). You cannot remove a specific element from this option. You can take only slice the existing array and get a continuous portion of the array. It's like cutting the array from the indexes you specify. The original array does not get affected.
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));
// expected output: Array ["camel", "duck"]
console.log(animals.slice(1, 5));
// expected output: Array ["bison", "camel", "duck", "elephant"]
3) SPLICE() - Change Contents of Array by Removing or Replacing Elements at Specific Indexes.
See reference for Array.prototype.splice(). The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Returns updated array. Original array gets updated.
const months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at index 1
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "June"]
months.splice(4, 1, 'May');
// replaces 1 element at index 4
console.log(months);
// expected output: Array ["Jan", "Feb", "March", "April", "May"]
In .NET 5, a new class has been introduced called JsonContent
, which derives from HttpContent
. See in Microsoft docs
This class has a static method called Create()
, which takes an object as a parameter.
Usage:
var myObject = new
{
foo = "Hello",
bar = "World",
};
JsonContent content = JsonContent.Create(myObject);
HttpResponseMessage response = await _httpClient.PostAsync("https://...", content);
If you want a generic solution using MutationObserver you can use this function
// MIT Licensed
// Author: jwilson8767
/**
* Waits for an element satisfying selector to exist, then resolves promise with the element.
* Useful for resolving race conditions.
*
* @param selector
* @returns {Promise}
*/
export function elementReady(selector) {
return new Promise((resolve, reject) => {
const el = document.querySelector(selector);
if (el) {resolve(el);}
new MutationObserver((mutationRecords, observer) => {
// Query for elements matching the specified selector
Array.from(document.querySelectorAll(selector)).forEach((element) => {
resolve(element);
//Once we have resolved we don't need the observer anymore.
observer.disconnect();
});
})
.observe(document.documentElement, {
childList: true,
subtree: true
});
});
}
Source: https://gist.github.com/jwilson8767/db379026efcbd932f64382db4b02853e
Example how to use it
elementReady('#someWidget').then((someWidget)=>{someWidget.remove();});
Note: MutationObserver has a great browser support; https://caniuse.com/#feat=mutationobserver
Et voilà ! :)
Solution for those working with Huawei phones - You will get this error when ADB interface is not installed. Check if you have installed Huawei HiSuite. USB driver gets installed when you install HiSuite (I suppose this is true for most of the new phones that come with a Sync Software). If the ADB interface is installed on your computer you should see 'Android Composite ADB Interface' under Android Phone in your Device Manager as shown in this picture.
I've had this same problem for a while as I generate a fair number of ad-hoc reports from SQL Server and copy/paste them into Excel. I would also welcome a proper solution but my temporary workaround was to create a default macro in Excel which converts highlighted cells to Excel's datetime format, and assigned it to a hotkey (Shift-Ctrl-D in my case). So I open Excel, copy/paste from SSMS into a new Excel worksheet, highlight the column to convert and press Shift-Ctrl-D. Job done.
In case you don't want to include a big library like jQuery for something this simple, here's an alternative solution using built-in DOM methods:
// Check checkbox by id:_x000D_
document.querySelector('#radio_1').checked = true;_x000D_
_x000D_
// Check checkbox by value:_x000D_
document.querySelector('#type > [value="1"]').checked = true;_x000D_
_x000D_
// If this is the only input with a value of 1 on the page, you can leave out the #type >_x000D_
document.querySelector('[value="1"]').checked = true;
_x000D_
<form>_x000D_
<div id='type'>_x000D_
<input type='radio' id='radio_1' name='type' value='1' />_x000D_
<input type='radio' id='radio_2' name='type' value='2' />_x000D_
<input type='radio' id='radio_3' name='type' value='3' /> _x000D_
</div>_x000D_
</form>
_x000D_
Update: Since I wrote this answer two years ago, we productized Mono to run on Android. The work included a few steps: porting Mono to Android, integrating it with Visual Studio, building plugins for MonoDevelop on Mac and Windows and exposing the Java Android APIs to .NET languages. This is now available at http://monodroid.net
Mono on Android is based on the Mono 2.10 runtime, and defaults to 4.0 profile with the C# 4.0 compiler and uses Mono's new SGen garbage collection engine, as well as our new distributed garbage collection system that performs GC across Java and Mono.
The links below reflect Mono on Android as of January of 2009, I have kept them for historical context
Mono now works on Android thanks to the work of Koushik Dutta and Marc Crichton.
You can see a video of it running here: http://www.koushikdutta.com/2009/01/mono-on-android-with-gratuitous-shaky.html
And you can get the instructions to build Mono yourself here: http://www.koushikdutta.com/2009/01/building-mono-for-android.html
You can get a benchmark comparing Mono's JIT vs Dalvik's interpreter here: http://www.koushikdutta.com/2009/01/dalvik-vs-mono.html
And of course, you can get a pre-configured image with Mono here (go to the bottom of the post for details on using that): http://www.koushikdutta.com/2009/01/building-mono-for-android.html
It's possible to get this done using seaborn.lineplot()
but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:
# imports
import seaborn as sns
import numpy as np
import pandas as pd
# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])
# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)
# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>
And we get the following plot:
In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.
But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:
{ Id: 1,
name:'john',
phones:[{title:'home',number:111111,...},
{title:'office',number:22222,...}]
}
sends
{ Id: 1,
name:'john',
phones:[object object]
phones:[object object]
}
\t
is the tab character, and is doing exactly what you're anticipating based on the action of \b
- it goes to the next tab stop, then gets decremented, and then goes to the next tab stop (which is in this case the same tab stop, because of the \b
.
I suggest that you use HTML Tidy to convert the HTML to XHTML, and then use a suitable XPath expression to extract the attributes.
I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
You need to call the AddAddress
method once for every recipient. Like so:
$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..
To make things easy, you should loop through an array to do this.
$recipients = array(
'[email protected]' => 'Person One',
'[email protected]' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddAddress($email, $name);
}
Better yet, add them as Carbon Copy recipients.
$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..
To make things easy, you should loop through an array to do this.
$recipients = array(
'[email protected]' => 'Person One',
'[email protected]' => 'Person Two',
// ..
);
foreach($recipients as $email => $name)
{
$mail->AddCC($email, $name);
}
The reject
actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject()
the exception value is undefined
, hence the "undefined" part in the error that you get.
You do not show the code that uses the promise, but I reckon it is something like this:
var promise = doSth();
promise.then(function() { doSthHere(); });
Try adding an empty failure call, like this:
promise.then(function() { doSthHere(); }, function() {});
This will prevent the error to appear.
However, I would consider calling reject
only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.
You can combine multiple selectors with a comma:
$('#Create .myClass,#Edit .myClass').plugin({options here});
Or if you're going to have a bunch of them, you could add a class to all your form elements and then search within that class. This doesn't get you the supposed speed savings of restricting the search, but I honestly wouldn't worry too much about that if I were you. Browsers do a lot of fancy things to optimize common operations behind your back -- the simple class selector might be faster.
public class SomeClass
{
public void SomeMethod()
{
StackFrame frame = new StackFrame(1);
var method = frame.GetMethod();
var type = method.DeclaringType;
var name = method.Name;
}
}
Now let's say you have another class like this:
public class Caller
{
public void Call()
{
SomeClass s = new SomeClass();
s.SomeMethod();
}
}
name will be "Call" and type will be "Caller"
UPDATE Two years later since I'm still getting upvotes on this
In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute
Going with the previous example:
public class SomeClass
{
public void SomeMethod([CallerMemberName]string memberName = "")
{
Console.WriteLine(memberName); //output will be name of calling method
}
}
First of all you missed ScriptService attribute to add in webservice.
[ScriptService]
After then try following method to call webservice via JSON.
var webAddr = "http://Domain/VBRService.asmx/callJson"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"x\":\"true\"}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; }
You can't do this with jQuery ajax, but with native XMLHttpRequest.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200){
//this.response is what you're looking for
handler(this.response);
console.log(this.response, typeof this.response);
var img = document.getElementById('img');
var url = window.URL || window.webkitURL;
img.src = url.createObjectURL(this.response);
}
}
xhr.open('GET', 'http://jsfiddle.net/img/logo.png');
xhr.responseType = 'blob';
xhr.send();
EDIT
So revisiting this topic, it seems it is indeed possible to do this with jQuery 3
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhr:function(){// Seems like the only way to get access to the xhr object_x000D_
var xhr = new XMLHttpRequest();_x000D_
xhr.responseType= 'blob'_x000D_
return xhr;_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
or
use xhrFields to set the responseType
jQuery.ajax({_x000D_
url:'https://images.unsplash.com/photo-1465101108990-e5eac17cf76d?ixlib=rb-0.3.5&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ%3D%3D&s=471ae675a6140db97fea32b55781479e',_x000D_
cache:false,_x000D_
xhrFields:{_x000D_
responseType: 'blob'_x000D_
},_x000D_
success: function(data){_x000D_
var img = document.getElementById('img');_x000D_
var url = window.URL || window.webkitURL;_x000D_
img.src = url.createObjectURL(data);_x000D_
},_x000D_
error:function(){_x000D_
_x000D_
}_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>_x000D_
<img id="img" width=100%>
_x000D_
sudo chown $USER /dev/kvm
Simply running that one command worked for me here in September 2019 running:
Description: Ubuntu 18.04.3
LTS Release: 18.04
Codename: bionic
Windows users:
Note: Note to Win32 Users In order to enable this module on a Windows environment, libeay32.dll and ssleay32.dll, or, as of OpenSSL 1.1 libcrypto-.dll and libssl-.dll, must be present in your PATH. Also libssh2.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.
https://www.php.net/manual/en/curl.installation.php
Add your C:\wamp\bin\php\php7.1.15 to your PATH
Restart all services
Let’s assume, your old app.module.ts may look similar to this :
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Now import FormsModule in your app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
http://jsconfig.com/solution-cant-bind-ngmodel-since-isnt-known-property-input/
Just use the length
property of a JavaScript
array like so:
$scope.names.length
Also, I don't see a starting <script>
tag in your code.
If you want the length inside your view, do it like so:
{{ names.length }}
Or in your SQL query wrap that field with IsNull or Coalesce (SQL Server).
Either way works, I like to put that logic in the query so the report has to do less.
Do this using rs.next()
:
while (rs.next())
{
...
}
If the result set is empty, the code inside the loop won't execute.
If you iterate over a dictionary you get the keys, so assuming your dictionary is in a variable called data
and you have some function find_definition()
which gets the definition, you can do something like the following:
for word in data:
data[word] = find_definition(word)
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
In my case, setting Copy to Output Directory
to Copy Always
and Build did not do the trick, while Rebuild did.
Hope this helps someone!
You can actually release your Excel Application object cleanly, but you do have to take care.
The advice to maintain a named reference for absolutely every COM object you access and then explicitly release it via Marshal.FinalReleaseComObject()
is correct in theory, but, unfortunately, very difficult to manage in practice. If one ever slips anywhere and uses "two dots", or iterates cells via a for each
loop, or any other similar kind of command, then you'll have unreferenced COM objects and risk a hang. In this case, there would be no way to find the cause in the code; you would have to review all your code by eye and hopefully find the cause, a task that could be nearly impossible for a large project.
The good news is that you do not actually have to maintain a named variable reference to every COM object you use. Instead, call GC.Collect()
and then GC.WaitForPendingFinalizers()
to release all the (usually minor) objects to which you do not hold a reference, and then explicitly release the objects to which you do hold a named variable reference.
You should also release your named references in reverse order of importance: range objects first, then worksheets, workbooks, and then finally your Excel Application object.
For example, assuming that you had a Range object variable named xlRng
, a Worksheet variable named xlSheet
, a Workbook variable named xlBook
and an Excel Application variable named xlApp
, then your cleanup code could look something like the following:
// Cleanup
GC.Collect();
GC.WaitForPendingFinalizers();
Marshal.FinalReleaseComObject(xlRng);
Marshal.FinalReleaseComObject(xlSheet);
xlBook.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(xlBook);
xlApp.Quit();
Marshal.FinalReleaseComObject(xlApp);
In most code examples you'll see for cleaning up COM objects from .NET, the GC.Collect()
and GC.WaitForPendingFinalizers()
calls are made TWICE as in:
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
This should not be required, however, unless you are using Visual Studio Tools for Office (VSTO), which uses finalizers that cause an entire graph of objects to be promoted in the finalization queue. Such objects would not be released until the next garbage collection. However, if you are not using VSTO, you should be able to call GC.Collect()
and GC.WaitForPendingFinalizers()
just once.
I know that explicitly calling GC.Collect()
is a no-no (and certainly doing it twice sounds very painful), but there is no way around it, to be honest. Through normal operations you will generate hidden objects to which you hold no reference that you, therefore, cannot release through any other means other than calling GC.Collect()
.
This is a complex topic, but this really is all there is to it. Once you establish this template for your cleanup procedure you can code normally, without the need for wrappers, etc. :-)
I have a tutorial on this here:
Automating Office Programs with VB.Net / COM Interop
It's written for VB.NET, but don't be put off by that, the principles are exactly the same as when using C#.
I know this thread is old, but still answering it so that no-one else should spend sleepless nights.
I was refactoring an old project, whose layout files all contained hardcoded
attributes such as android:maxLength = 500
. So I decided to register it in my
res/dimen
file as <dimen name="max_length">500</dimen>
.
Finished refactoring almost 30 layout files with my res-value. Guess what? the next time I ran my project it started throwing the same InflateException
.
As a solution, needed to redo my all changes and keep all-those values as same as before.
TLDR;
step 1: All running good.
step 2: To boost my maintenance I replaced android:maxLength = 500
with <dimen name="max_length">500</dimen>
and android:maxLength = @dimen/max_length
, that's where it all went wrong(crashing with InflateException
).
step 3: All running bad
step 4: Re-do all my work by again replacing android:maxLength = @dimen/max_length
with android:maxLength = 500
.Everything got fixed.
step 5: All running good.
Supplement to Mario Knezovic 's answer:
class IA
{
public:
virtual int getNum() const = 0;
};
class BaseA : public IA
{
public:
inline virtual int getNum() const final {return ...};
};
class ImplA : public BaseA {...};
IA* pa = ...;
...
ImplA* impla = static_cast<ImplA*>(pa);
//the following line should cause compiler to use the inlined function BaseA::getNum(),
//instead of dynamic binding (via vtable or something).
//any class/subclass of BaseA will benefit from it
int n = impla->getNum();
The above code shows the theory, but not actually tested on real compilers. Much appreciated if anyone paste a disassembled output.
You can use MySQL Workbench which provides a way to quickly migrate data and applications from Microsoft SQL Server to MySQL employing less time and effort.
This tool has a lot of cool features like:
These are several ways to apply style to an element. Try any one of the examples below:
1. document.getElementById('div_register').className = 'wide';
/* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';
The PHPUnit documentation says used to say to include/require PHPUnit/Framework.php, as follows:
require_once ('PHPUnit/Framework/TestCase.php');
UPDATE
As of PHPUnit 3.5, there is a built-in autoloader class that will handle this for you:
require_once 'PHPUnit/Autoload.php';
Thanks to Phoenix for pointing this out!
Like it's written up there, you forget to type #include <sstream>
#include <sstream>
using namespace std;
QString Stats_Manager::convertInt(int num)
{
stringstream ss;
ss << num;
return ss.str();
}
You can also use some other ways to convert int
to string
, like
char numstr[21]; // enough to hold all numbers up to 64-bits
sprintf(numstr, "%d", age);
result = name + numstr;
check this!
boost::lexical_cast works pretty well.
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
std::string foo = boost::lexical_cast<std::string>(argc);
}
You can use this:
SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_SCHEMA = 'yourdb' AND ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_NAME = "procedurename";
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
});
});</script>
</body>
</html>
The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here
If you don't give any position to parent then by default it takes static
. If you want to understand that difference refer to this example
Example 1::
#mainall
{
background-color:red;
height:150px;
overflow:scroll
}
Here parent class has no position so element is placed according to body.
Example 2::
#mainall
{
position:relative;
background-color:red;
height:150px;
overflow:scroll
}
In this example parent has relative position hence element are positioned absolute inside relative parent.
ActionResult is an abstract class that can have several subtypes.
ViewResult - Renders a specifed view to the response stream
PartialViewResult - Renders a specifed partial view to the response stream
EmptyResult - An empty response is returned
RedirectResult - Performs an HTTP redirection to a specifed URL
RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
JsonResult - Serializes a given ViewData object to JSON format
JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
ContentResult - Writes content to the response stream without requiring a view
FileContentResult - Returns a file to the client
FileStreamResult - Returns a file to the client, which is provided by a Stream
FilePathResult - Returns a file to the client
Afaik the Browser application data is NOT clearable for other apps, since it is store in private_mode
. So executing this command could probalby only work on rooted devices. Otherwise you should try another approach.
I really appreciate the suggestions here. The Impaler's and Oleg's comments helped me to piece my solution together.
Use the VBoxManage CLI. There's a modifymedium command with a --setlocation
option.
I suggest opening the VBox GUI (on VM VirtualBox Manager 6.0)
- select "Virtual Media Manager" (I used the File menu)
- select the "Information" button for the disk giving you this error
- copy the UUID
Note: I removed the controller from the "Storage" setting before the next step.
- open your command prompt and navigate to the location of the .vdi file
It's a good idea to type VBoxMange to see a list of options, but this is the command to run:
VBoxManage modifymedium
[insert medium type here] [UUID] --setlocation
[full path to .vdi file]
Finally, reattach the controller to any VM--preferably the one you'd like to fix.
SELECT TRIM(ColumnName) FROM dual;
The equivalent to the accepted answer in jQuery 1.11:
$(window).on("beforeunload", function () {
return "Please don't leave me!";
});
altCognito's answer used the unload
event, which happens too late for JavaScript to abort the navigation.
You can't use {{}}
when using angular directives for binding with ng-model
but for binding non-angular attributes you would have to use {{}}
..
Eg:
ng-show="my-model"
title = "{{my-model}}"
Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:
*** Phones:
*** Tablets:
Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.
Just noticed that quick search has been included into eclipse 4.13 as a built-in function by typing Ctrl+Alt+Shift+L (or Cmd+Alt+Shift+L on Mac)
https://www.eclipse.org/eclipse/news/4.13/platform.php#quick-text-search
On ipython or jupyter notebook, you can use all the above mentioned ways, but i go with
my_func?
or
?my_func
for quick summary of both method signature and docstring.
I avoid using
my_func??
(as commented by @rohan) for docstring and use it only to check the source code
I think this is what we like to do very much.
--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;
-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello;
-- step 3 (then authorized the user for that specific database , you have to use the master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO
If you already created a user and assigned to that database before by doing
USE [yourDB]
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo]
GO
then kindly delete it by doing below and follow the steps
USE yourDB;
GO
DROP USER newlogin;
GO
For more information please follow the links:
Hiding databases for a login on Microsoft Sql Server 2008R2 and above
I'm suprised this example is'nt here:
EDIT >> The above link is not reachable. Here is an excerpt from the POST example followed by the link to the HTTP examples.
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket);
}
BasicHttpEntityEnclosingRequest request = new
BasicHttpEntityEnclosingRequest("POST",
"/servlets-examples/servlet/RequestInfoExample");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
httpexecutor.preProcess(request, httpproc, coreContext);
HttpResponse response = httpexecutor.execute(request, conn, coreContext);
httpexecutor.postProcess(response, httpproc, coreContext);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, coreContext)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
http://hc.apache.org/httpcomponents-core-ga/httpcore/examples/org/apache/http/examples/
A realtime priority thread can never be pre-empted by timer interrupts and runs at a higher priority than any other thread in the system. As such a CPU bound realtime priority thread can totally ruin a machine.
Creating realtime priority threads requires a privilege (SeIncreaseBasePriorityPrivilege) so it can only be done by administrative users.
For Vista and beyond, one option for applications that do require that they run at realtime priorities is to use the Multimedia Class Scheduler Service (MMCSS) and let it manage your threads priority. The MMCSS will prevent your application from using too much CPU time so you don't have to worry about tanking the machine.
I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.
function changeImage() {
var img = document.getElementById("img");
img.src = images[x];
x++;
if(x >= images.length) {
x = 0;
}
fadeImg(img, 100, true);
setTimeout("changeImage()", 30000);
}
function fadeImg(el, val, fade) {
if(fade === true) {
val--;
} else {
val ++;
}
if(val > 0 && val < 100) {
el.style.opacity = val / 100;
setTimeout(function(){ fadeImg(el, val, fade); }, 10);
}
}
var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);
In the current version of TortoiseHg Workbench 4.4.1 (07.2018) you can use Repository
- Rollback/undo...
:
Assuming that your using Visual Studio 10, you can download an install that includes System.Net.Http, for Visual Studio 10 here: download MVC4 for VS10
Once you've installed it, right click on the References folder in the VS Project and then select Add Reference. Then, select the Browse tab. Navigate to the assemblies install path for the MVC4 install (usually in Program Files(x86)/Microsoft ASP.NET/ASP.NET MVC4/assemblies) and select the assembly named 'System.Net.Http.dll'. Now you can add your 'using System.Net.Http' at the top of your code and begin creating HttpClient connections.
You don't need to apply to_date()
to sysdate
. It is already there:
select 1
from dual
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');
If you are concerned about the time component on the date, then use trunc()
:
select 1
from dual
WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND
TO_DATE('20/06/2014', 'DD/MM/YYYY');
Use:
File file = new File("Z:\\results\\results.txt");
You need to double the backslashes in Windows because the backslash character itself is an escape in Java literal strings.
For POSIX system such as Linux, just use the default file path without doubling the forward slash. this is because forward slash is not a escape character in Java.
File file = new File("/home/userName/Documents/results.txt");
label1.Text = DateTime.Now.Month.ToString();
and
label2.Text = DateTime.Now.Year.ToString();
There is no such thing like a DateTime
without a year!
From what I gather your design is a bit strange:
I would recommend storing a "start" (DateTime
including year for the FIRST occurence) and a value which designates how to calculate the next event... this could be for example a TimeSpan
or some custom structure esp. since "every year" can mean that the event occurs on a specific date and would not automatically be the same as saysing that it occurs in +365 days.
After the event occurs you calculate the next and store that etc.
I'm assuming, due to the nature of this question that extensions are not excluded?
Also, I'm surprised that so far no one used goto
.
int main () {
int i = 0;
void * addr[1001] = { [0 ... 999] = &&again};
addr[1000] = &&end;
again:
printf("%d\n", i + 1);
goto *addr[++i];
end:
return 0;
}
Ok, so technically it is a loop - but it's no more a loop than all the recursive examples so far ;)
Your data
variable contains an object, not an array, and objects do not have the push
function as the error states. To do what you need you can do this:
data.country = 'IN';
Or
data['country'] = 'IN';
get_or_create
returns a tuple.
customer.source, created = Source.objects.get_or_create(name="Website")
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
A try block has just one mandatory clause: The try statement. The except, else and finally clauses are optional and based on user preference.
finally: Before Python leaves the try statement, it will run the code in the finally block under any conditions, even if it's ending the program. E.g., if Python ran into an error while running code in the except or else block, the finally block will still be executed before stopping the program.
Referring to the answers above, I am only adding this to help clarify things. It is possible to use HttpClient from .Net 4.0, and you have to install the package from here
However, the text is very confusion and contradicts itself.
This package is not supported in Visual Studio 2010, and is only required for projects targeting .NET Framework 4.5, Windows 8, or Windows Phone 8.1 when consuming a library that uses this package.
But underneath it states that these are the supported platforms.
Supported Platforms:
.NET Framework 4
Windows 8
Windows Phone 8.1
Windows Phone Silverlight 7.5
Silverlight 4
Portable Class Libraries
Ignore what it ways about targeting .Net 4.5. This is wrong. The package is all about using HttpClient in .Net 4.0. However, you may need to use VS2012 or higher. Not sure if it works in VS2010, but that may be worth testing.