You can convert your .ui files to an executable python file using the below command..
pyuic4 -x form1.ui > form1.py
Now you can straightaway execute the python file as
python3(whatever version) form1.py
You can import this file and you can use it.
According to the documentation, there needs to be a top level layout set.
A top level layout is necessary to ensure that your widgets will resize correctly when its window is resized. To check if you have set a top level layout, preview your widget and attempt to resize the window by dragging the size grip.
You can set one by clearing the selection and right clicking on the form itself and choosing one of the layouts available in the context menu.
You need to change the default layout type of top level QWidget object from Break layout type to other layout types (Vertical Layout, Horizontal Layout, Grid Layout, Form Layout). For example:
To something like this:
I believe i have found the answer, This code converts the integer to a hex string an removes the alpha.
Integer intColor = -16895234;
String hexColor = "#" + Integer.toHexString(intColor).substring(2);
Note only use this code if you are sure that removing the alpha would not affect anything.
If your simple test page is located on other protocol/domain/port than your hello world node.js example you are doing cross-domain requests and violating same origin policy therefore your jQuery ajax calls (get and load) are failing silently. To get this working cross-domain you should use JSONP based format. For example node.js code:
var http = require('http');
http.createServer(function (req, res) {
console.log('request received');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('_testcb(\'{"message": "Hello world!"}\')');
}).listen(8124);
and client side JavaScript/jQuery:
$(document).ready(function() {
$.ajax({
url: 'http://192.168.1.103:8124/',
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: false,
timeout: 5000,
success: function(data) {
$("#test").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
});
There are also other ways how to get this working, for example by setting up reverse proxy or build your web application entirely with framework like express.
It should be (-###
is similar to -v
):
echo | gcc -### -E - -march=native
To show the "real" native flags for gcc.
You can make them appear more "clearly" with a command:
gcc -### -E - -march=native 2>&1 | sed -r '/cc1/!d;s/(")|(^.* - )//g'
and you can get rid of flags with -mno-* with:
gcc -### -E - -march=native 2>&1 | sed -r '/cc1/!d;s/(")|(^.* - )|( -mno-[^\ ]+)//g'
let button: UIButton = UIButton()
button.setImage(UIImage(named:"imagename"), for: .normal)
button.addTarget(self, action:#selector(YourClassName.backAction(_sender:)), for: .touchUpInside)
button.frame = CGRect.init(x: 5, y: 100, width: 45, height: 45)
view.addSubview(button)
@objc public func backAction(_sender: UIButton) {
}
Working example is given below,
MyService.class
public class MyService extends Service implements SpeechDelegate, Speech.stopDueToDelay {
public static SpeechDelegate delegate;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
Speech.init(this);
delegate = this;
Speech.getInstance().setListener(this);
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
System.setProperty("rx.unsafe-disable", "True");
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
@Override
public void onStartOfSpeech() {
}
@Override
public void onSpeechRmsChanged(float value) {
}
@Override
public void onSpeechPartialResults(List<String> results) {
for (String partial : results) {
Log.d("Result", partial+"");
}
}
@Override
public void onSpeechResult(String result) {
Log.d("Result", result+"");
if (!TextUtils.isEmpty(result)) {
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onSpecifiedCommandPronounced(String event) {
try {
if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
((AudioManager) Objects.requireNonNull(
getSystemService(Context.AUDIO_SERVICE))).setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
} catch (Exception e) {
e.printStackTrace();
}
if (Speech.getInstance().isListening()) {
Speech.getInstance().stopListening();
} else {
RxPermissions.getInstance(this).request(permission.RECORD_AUDIO).subscribe(granted -> {
if (granted) { // Always true pre-M
try {
Speech.getInstance().stopTextToSpeech();
Speech.getInstance().startListening(null, this);
} catch (SpeechRecognitionNotAvailable exc) {
//showSpeechNotSupportedDialog();
} catch (GoogleVoiceTypingDisabledException exc) {
//showEnableGoogleVoiceTyping();
}
} else {
Toast.makeText(this, R.string.permission_required, Toast.LENGTH_LONG).show();
}
});
}
}
@Override
public void onTaskRemoved(Intent rootIntent) {
//Restarting the service if it is removed.
PendingIntent service =
PendingIntent.getService(getApplicationContext(), new Random().nextInt(),
new Intent(getApplicationContext(), MyService.class), PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
assert alarmManager != null;
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
super.onTaskRemoved(rootIntent);
}
}
For more details,
Hope this will help someone in future.
@variable
is very useful if calling stored procedures from an application written in Java , Python etc.
There are ocassions where variable values are created in the first call and needed in functions of subsequent calls.
The advantage can be seen in Oracle PL/SQL where these variables have 3 different scopes:
I have developed an architecture in which the complete code is written in PL/SQL. These are called from a middle-ware written in Java. There are two types of middle-ware. One to cater calls from a client which is also written in Java. The other other one to cater for calls from a browser. The client facility is implemented 100 percent in JavaScript. A command set is used instead of HTML and JavaScript for writing application in PL/SQL.
I have been looking for the same facility to port the codes written in PL/SQL to another database. The nearest one I have found is Postgres. But all the variables have function scope.
@
in MySQLI am happy to see that at least this @
facility is there in MySQL. I don't think Oracle will build same facility available in PL/SQL to MySQL stored procedures since it may affect the sales of Oracle database.
// Due to this Code ): Syntax problem.
$('.myClass', '.myOtherClass').removeClass('theclass');
According to jQuery documentation: https://api.jquery.com/multiple-selector/
When can select multiple classes in this way:
jQuery(“selector1, selector2, selectorN”) // double Commas. // IS valid.
jQuery('selector1, selector2, selectorN') // single Commas. // Is valid.
by enclosing all the selectors in a single '...' ' or double commas, "..."
So in your case the correct way to call multiple classes is:
$('.myClass', '.myOtherClass').removeClass('theclass'); // your Code // Invalid.
$('.myClass , .myOtherClass').removeClass('theclass'); // Correct Code // Is valid.
Never hardcode sensitive information (account credentials, passwords, etc.). Instead, create a file to store that information as environment variables (key/value pairs), and exclude that file from your source code management system. For example, in terms of Git (source code management system), exclude that file by adding it to .gitignore:
-bash> echo '/config/app_environment_variables.rb' >> .gitignore
/config/app_environment_variables.rb
ENV['HTTP_USER'] = 'devuser'
ENV['HTTP_PASS'] = 'devpass'
As well, add the following lines to /config/environment.rb
, between the require
line, and the Application.initialize
line:
# Load the app's custom environment variables here, so that they are loaded before environments/*.rb
app_environment_variables = File.join(Rails.root, 'config', 'app_environment_variables.rb')
load(app_environment_variables) if File.exists?(app_environment_variables)
That's it!
As the comment above says, by doing this you will be loading your environment variables before environments/*.rb
, which means that you will be able to refer to your variables inside those files (e.g. environments/production.rb
). This is a great advantage over putting your environment variables file inside /config/initializers/
.
Inside app_environment_variables.rb
there's no need to distinguish environments as far as development or production because you will never commit this file into your source code management system, hence it is for the development context by default. But if you need to set something special for the test environment (or for occasions when you test production mode locally), just add a conditional block below all the other variables:
if Rails.env.test?
ENV['HTTP_USER'] = 'testuser'
ENV['HTTP_PASS'] = 'testpass'
end
if Rails.env.production?
ENV['HTTP_USER'] = 'produser'
ENV['HTTP_PASS'] = 'prodpass'
end
Whenever you update app_environment_variables.rb
, restart the app server. Assuming you are using the likes of Apache/Passenger or rails server
:
-bash> touch tmp/restart.txt
In your code, refer to the environment variables as follows:
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == ENV['HTTP_USER'] && password == ENV['HTTP_PASS']
end
end
Note that inside app_environment_variables.rb
you must specify booleans and numbers as strings (e.g. ENV['SEND_MAIL'] = 'false'
not just false
, and ENV['TIMEOUT'] = '30'
not just 30
), otherwise you will get the errors can't convert false into String
and can't convert Fixnum into String
, respectively.
Storing and sharing sensitive information
The final knot to tie is: how to share this sensitive information with your clients and/or partners? For the purpose of business continuity (i.e. when you get hit by a falling star, how will your clients and/or partners resume full operations of the site?), your clients and/or partners need to know all the credentials required by your app. Emailing/Skyping these things around is insecure and leads to disarray. Storing it in shared Google Docs is not bad (if everyone uses https), but an app dedicated to storing and sharing small titbits like passwords would be ideal.
How to set environment variables on Heroku
If you have a single environment on Heroku:
-bash> heroku config:add HTTP_USER='herouser'
-bash> heroku config:add HTTP_USER='heropass'
If you have multiple environments on Heroku:
-bash> heroku config:add HTTP_USER='staguser' --remote staging
-bash> heroku config:add HTTP_PASS='stagpass' --remote staging
-bash> heroku config:add HTTP_USER='produser' --remote production
-bash> heroku config:add HTTP_PASS='prodpass' --remote production
Foreman and .env
Many developers use Foreman (installed with the Heroku Toolbelt) to run their apps locally (as opposed to using the likes of Apache/Passenger or rails server
). Foreman and Heroku use Procfile
for declaring what commands are run by your application, so the transition from local dev to Heroku is seamless in that regard. I use Foreman and Heroku in every Rails project, so this convenience is great. But here's the thing.. Foreman loads environment variables stored in /.env
via dotenv but unfortunately dotenv essentially only parses the file for key=value
pairs; those pairs don't become variables right there and then, so you can't refer to already set variables (to keep things DRY), nor can you do "Ruby" in there (as noted above with the conditionals), which you can do in /config/app_environment_variables.rb
. For instance, in terms of keeping things DRY I sometimes do stuff like this:
ENV['SUPPORT_EMAIL']='Company Support <[email protected]>'
ENV['MAILER_DEFAULT_FROM'] = ENV['SUPPORT_EMAIL']
ENV['MAILER_DEFAULT_TO'] = ENV['SUPPORT_EMAIL']
Hence, I use Foreman to run my apps locally, but I don't use its .env
file for loading environment variables; rather I use Foreman in conjunction with the /config/app_environment_variables.rb
approach described above.
If you don't mind something related to Bootstrap, an excellent (unofficial) Bootstrap Switch is available.
It uses radio types or checkboxes as switches. A type
attribute has been added since V.1.8.
Source code is available on Github.
I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.
Please consider having a look at modern Switches like those.
step 1 : create layout with name activity_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#c6cabd"
>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="17dp"
android:textColor="#ff0e13"
/>
<EditText
android:id="@+id/et"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/tv"
android:hint="Input your country"
/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get EditText Text"
android:layout_below="@id/et"
/>
</RelativeLayout>
Step 2 : Create class Main.class
public class Main extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn);
final TextView tv = (TextView) findViewById(R.id.tv);
final EditText et = (EditText) findViewById(R.id.et);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String country = et.getText().toString();
tv.setText("Your inputted country is : " + country);
}
});
}
}
Please install http://asepsis.binaryage.com/ and then reboot your mac.
ASEPSIS redirect all .DS_Store on your mac to /usr/local/.dscage
After that, You could delete recursively all .DS_Store from your mac.
find ~ -name ".DS_Store" -delete
or
find <your path> -name ".DS_Store" -delete
You should repeat procedure after each Mac major update.
If you only need the default style, make sure you have the following width/height, otherwise the numStars could get messed up:
android:layout_width="wrap_content"
android:layout_height="wrap_content"
Cloning Arrays and Objects in javascript have a different syntax. Sooner or later everyone learns the difference the hard way and end up here.
In Typescript and ES6 you can use the spread operator for array and object:
const myClonedArray = [...myArray]; // This is ok for [1,2,'test','bla']
// But wont work for [{a:1}, {b:2}].
// A bug will occur when you
// modify the clone and you expect the
// original not to be modified.
// The solution is to do a deep copy
// when you are cloning an array of objects.
To do a deep copy of an object you need an external library:
import {cloneDeep} from 'lodash';
const myClonedArray = cloneDeep(myArray); // This works for [{a:1}, {b:2}]
The spread operator works on object as well but it will only do a shallow copy (first layer of children)
const myShallowClonedObject = {...myObject}; // Will do a shallow copy
// and cause you an un expected bug.
To do a deep copy of an object you need an external library:
import {cloneDeep} from 'lodash';
const deeplyClonedObject = cloneDeep(myObject); // This works for [{a:{b:2}}]
Okay so three big things I noticed
You need to include the header file in your class file
Never, EVER place a using directive inside of a header or class, rather do something like std::cout << "say stuff";
Structs are completely defined within a header, structs are essentially classes that default to public
Hope this helps!
Note: the question was originally about compilation time, but later it turned out that the OP really meant execution time. But maybe this answer will still be useful for someone.
For Visual Studio: go to Tools / Options / Projects and Solutions / VC++ Project Settings
and set Build Timing
option to 'yes
'. After that the time of every build will be displayed in the Output window.
After some limited testing with Spring 3.2, it seems one can use a SpEL list: {..., ..., ...}
. This can also include null
values. Spring passes the list as the key to the actual cache implementation. When using Ehcache, such will at some point invoke List#hashCode(), which takes all its items into account. (I am not sure if Ehcache only relies on the hash code.)
I use this for a shared cache, in which I include the method name in the key as well, which the Spring default key generator does not include. This way I can easily wipe the (single) cache, without (too much...) risking matching keys for different methods. Like:
@Cacheable(value="bookCache",
key="{ #root.methodName, #isbn?.id, #checkWarehouse }")
public Book findBook(ISBN isbn, boolean checkWarehouse)
...
@Cacheable(value="bookCache",
key="{ #root.methodName, #asin, #checkWarehouse }")
public Book findBookByAmazonId(String asin, boolean checkWarehouse)
...
Of course, if many methods need this and you're always using all parameters for your key, then one can also define a custom key generator that includes the class and method name:
<cache:annotation-driven mode="..." key-generator="cacheKeyGenerator" />
<bean id="cacheKeyGenerator" class="net.example.cache.CacheKeyGenerator" />
...with:
public class CacheKeyGenerator
implements org.springframework.cache.interceptor.KeyGenerator {
@Override
public Object generate(final Object target, final Method method,
final Object... params) {
final List<Object> key = new ArrayList<>();
key.add(method.getDeclaringClass().getName());
key.add(method.getName());
for (final Object o : params) {
key.add(o);
}
return key;
}
}
SELECT o.OrderID
CASE WHEN o.NegotiatedPrice > o.SuggestedPrice THEN
o.NegotiatedPrice
ELSE
o.SuggestedPrice
END AS Price
I faced a similar issue. After ensuring the token field was actually rendered (see accepted answer) I checked my cookies. There were 2(!) cookies for the domain in my Chrome browser, apparently because I was running the application on the same domain as another app, but with a different port (i.e. mydomain.com set the original cookie while the buggy app was running on mydomain.com:123) Now apparently Chrome sent the wrong cookie so the CSRF protection was unable to link the token to the correct session.
Fix: clear all the cookies for the domain in question, make sure you don't run multiple applications on the same domain with differing ports.
use this code in teminal :
python -m pip install --upgrade PAKAGE_NAME #instead of PAKAGE_NAME
for example i want update pip pakage :
python -m pip install --upgrade pip
more example :
python -m pip install --upgrade selenium
python -m pip install --upgrade requests
...
JavaScript code using ng-controller:
$scope.checkkey = function (event) {
alert(event.keyCode); //this will show the ASCII value of the key pressed
}
In HTML:
<input type="text" ng-keypress="checkkey($event)" />
You can now place your checks and other conditions using the keyCode method.
Use the css property overflow . For example:
.item{
width : 100px;
overflow:hidden;
}
The overflow property can have one of many values like ( hidden , scroll , visible ) .. you can als control the overflow in one direction only using overflow-x or overflow-y.
I hope this helps.
I found a little utility function a while back and I've been using it for resetting my form elements ever since (source: http://www.learningjquery.com/2007/08/clearing-form-data):
function clearForm(form) {
// iterate over all of the inputs for the given form element
$(':input', form).each(function() {
var type = this.type;
var tag = this.tagName.toLowerCase(); // normalize case
// it's ok to reset the value attr of text inputs,
// password inputs, and textareas
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = "";
// checkboxes and radios need to have their checked state cleared
// but should *not* have their 'value' changed
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
// select elements need to have their 'selectedIndex' property set to -1
// (this works for both single and multiple select elements)
else if (tag == 'select')
this.selectedIndex = -1;
});
};
... or as a jQuery plugin...
$.fn.clearForm = function() {
return this.each(function() {
var type = this.type, tag = this.tagName.toLowerCase();
if (tag == 'form')
return $(':input',this).clearForm();
if (type == 'text' || type == 'password' || tag == 'textarea')
this.value = '';
else if (type == 'checkbox' || type == 'radio')
this.checked = false;
else if (tag == 'select')
this.selectedIndex = -1;
});
};
The ScriptIgnoreAttribute
class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.
You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.
If you have java 8 installed it might be related to the following issue: https://support.oracle.com/knowledge/Middleware/2412304_1.html
Simply removing/renaming the "C:\Program Files (x86)\Common Files\Oracle\Java\javapath" worked for me.
I had the same problem as I like using the Try-method-pattern which basically seems to be incompatible to the async-await-paradigm...
Important to me is that I can call the Try-method within a single if-clause and do not have to pre-define the out-variables before, but can do it in-line like in the following example:
if (TryReceive(out string msg))
{
// use msg
}
So I came up with the following solution:
Define a helper struct:
public struct AsyncOut<T, OUT>
{
private readonly T returnValue;
private readonly OUT result;
public AsyncOut(T returnValue, OUT result)
{
this.returnValue = returnValue;
this.result = result;
}
public T Out(out OUT result)
{
result = this.result;
return returnValue;
}
public T ReturnValue => returnValue;
public static implicit operator AsyncOut<T, OUT>((T returnValue ,OUT result) tuple) =>
new AsyncOut<T, OUT>(tuple.returnValue, tuple.result);
}
Define async Try-method like this:
public async Task<AsyncOut<bool, string>> TryReceiveAsync()
{
string message;
bool success;
// ...
return (success, message);
}
Call the async Try-method like this:
if ((await TryReceiveAsync()).Out(out string msg))
{
// use msg
}
For multiple out parameters you can define additional structs (e.g. AsyncOut<T,OUT1, OUT2>) or you can return a tuple.
You want to define min-width
on row so when it browser is re-sized it does not go below that and wrap.
Try this on your position:fixed element.
overflow-y: scroll;
max-height: 100%;
I directly used the following command from my Mac using the terminal. I got SHA1 Finger. This is the command:
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:
static void writeStringToFile(File file, String data)
which allows you to write text to a file in one method call:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
You might also want to consider specifying the encoding for the file as well.
One tested solution for Bootstrap 4 beta:
.popover {
min-width: 30em !important;
}
Together with the jQuery statement:
$('[data-toggle="popover"]').popover({
container: 'body',
trigger: 'focus',
html: true,
placement: 'top'
})
Side-note, data-container="body"
or container: "body"
in either HTML or as an option
to the popover({})
object didn't really do the trick [maybe the do work but only together with the CSS statement];
Also, remember that Bootstrap 4 beta relies on popper.js for its popover and tooltip positioning (prior to that it was tether.js)
A likely possibility is that your browser reaches your web service through a proxy, and SoapUI is not configured to use that proxy. For example, I work in a corporate environment and while my IE and FireFox can access external websites, my SoapUI can only access internal web services.
The easy solution is to just open the WSDL in a browser, save it to a .xml file, and base your SoapUI project on that. This won't work if your WSDL relies on external XSDs that it can't get to, however.
[What you have is just an object, not a "json-object". JSON is a textual notation. What you've quoted is JavaScript code using an array initializer and an object initializer (aka, "object literal syntax").]
If you can rely on having ECMAScript5 features available, you can use the Object.keys
function to get an array of the keys (property names) in an object. All modern browsers have Object.keys
(including IE9+).
Object.keys(jsonData).forEach(function(key) {
var value = jsonData[key];
// ...
});
The rest of this answer was written in 2011. In today's world, A) You don't need to polyfill this unless you need to support IE8 or earlier (!), and B) If you did, you wouldn't do it with a one-off you wrote yourself or grabbed from an SO answer (and probably shouldn't have in 2011, either). You'd use a curated polyfill, possibly from es5-shim
or via a transpiler like Babel that can be configured to include polyfills (which may come from es5-shim
).
Here's the rest of the answer from 2011:
Note that older browsers won't have it. If not, this is one of the ones you can supply yourself:
if (typeof Object.keys !== "function") {
(function() {
var hasOwn = Object.prototype.hasOwnProperty;
Object.keys = Object_keys;
function Object_keys(obj) {
var keys = [], name;
for (name in obj) {
if (hasOwn.call(obj, name)) {
keys.push(name);
}
}
return keys;
}
})();
}
That uses a for..in
loop (more info here) to loop through all of the property names the object has, and uses Object.prototype.hasOwnProperty
to check that the property is owned directly by the object rather than being inherited.
(I could have done it without the self-executing function, but I prefer my functions to have names, and to be compatible with IE you can't use named function expressions [well, not without great care]. So the self-executing function is there to avoid having the function declaration create a global symbol.)
Or you can use:
ssh -oStrictHostKeyChecking=no host
This will be insecure (man in the middle attacks) but easiest solution.
The better way to do that is to generate correct mappings between host and ip address, so ssh
will not complain:
#!/bin/bash
for domain in "github.com" "bitbucket.org"; do
sed -i "/$domain/d" ~/.ssh/known_hosts
line=$(ssh-keyscan $domain,`nslookup $domain | awk '/^Address: / { print $2 ; exit }'`)
echo $line >> ~/.ssh/known_hosts
done
Excerpt from gist.
Now in c++11 we have
#include <string>
string s = std::to_string(123);
Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string
Use the variables "$1"
, "$2"
, "$3"
and so on to access arguments. To access all of them you can use "$@"
, or to get the count of arguments $#
(might be useful to check for too few or too many arguments).
In some cases Array.some
will probably fulfil the requirements.
look at this: https://developer.mozilla.org/en-US/docs/Web/API/event.keyCode
In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g. 'a'), charCode is set to the code of that character, respecting the letter case. (i.e. charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode. keyCode is always set in the keydown and keyup events. In these cases, charCode is never set. To get the code of the key regardless of whether it was stored in keyCode or charCode, query the which property. Characters entered through an IME do not register through keyCode or charCode.
The one and probably not so good way of achieving your goal would using global variables.
You could achieve that by adding global $myArr;
to the beginning of your function.
However note that using global variables is in most cases a bad idea and probably avoidable.
The much better way would be passing your array as an argument to your function:
function someFuntion($arr){
$myVal = //some processing here to determine value of $myVal
$arr[] = $myVal;
return $arr;
}
$myArr = someFunction($myArr);
Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.
You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.
If you make the relationships bidirectional, you should thus have
class User {
@OneToMany(mappedBy = "user")
private Set<UserService> userServices = new HashSet<UserService>();
}
class UserService {
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "service_code")
private Service service;
@Column(name = "blocked")
private boolean blocked;
}
class Service {
@OneToMany(mappedBy = "service")
private Set<UserService> userServices = new HashSet<UserService>();
}
If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.
User user = new User();
Service service = new Service();
UserService userService = new UserService();
user.addUserService(userService);
userService.setUser(user);
service.addUserService(userService);
userService.setService(service);
session.save(user);
session.save(service);
session.save(userService);
Try this: http://www.webtrickss.com/javascript/jquery-slidetoggle-signup-form-and-login-form/
????????????????????????????????????????????????
I think your problem is your version numbers. Try making 8.1 --> 8.01, and so forth. That should put the points in the right order.
Alternatively, you could plot using X
, where X is the column number you want, instead of using 1:X
. That will plot those values on the y axis and integers on the x axis. Try:
plot "ls.dat" using 2 title 'Removed' with lines, \
"ls.dat" using 3 title 'Added' with lines, \
"ls.dat" using 4 title 'Modified' with lines
Python.org has an excellent section on strings here. Scroll down to where it says "slice notation".
-- Disable the constraints on a table called tableName:
ALTER TABLE tableName NOCHECK CONSTRAINT ALL
-- Re-enable the constraints on a table called tableName:
ALTER TABLE tableName WITH CHECK CHECK CONSTRAINT ALL
---------------------------------------------------------
-- Disable constraints for all tables:
EXEC sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all'
-- Re-enable constraints for all tables:
EXEC sp_msforeachtable 'ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all'
---------------------------------------------------------
If I understand well, you want to Join ScheduleRequest
with User
and apply the in
clause to the userName
property of the entity User
.
I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join
part (because it handles the Join
logic outside the Criteria Query).
List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);
In order to write more type-safe code you could also use Metamodel by replacing this line:
Expression<String> exp = scheduleRequest.get("createdBy");
with this:
Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);
If it works, then you may try to add the Join
logic into the Criteria Query
. But right now I can't test it, so I prefer to see if somebody else wants to try.
Not a perfect answer though may be code snippets might help.
public <T> List<T> findListWhereInCondition(Class<T> clazz,
String conditionColumnName, Serializable... conditionColumnValues) {
QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
addWhereInClause(queryBuilder, conditionColumnName,
conditionColumnValues);
queryBuilder.select();
return queryBuilder.getResultList();
}
private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
String conditionColumnName, Serializable... conditionColumnValues) {
Path<Object> path = queryBuilder.root.get(conditionColumnName);
In<Object> in = queryBuilder.criteriaBuilder.in(path);
for (Serializable conditionColumnValue : conditionColumnValues) {
in.value(conditionColumnValue);
}
queryBuilder.criteriaQuery.where(in);
}
That works better with this :
var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();
http://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx
Also, from ojdbc14 to ojdbc6, several types (e.g., OracleResultSet
, OracleStatement
) moved from package oracle.jdbc.driver
to oracle.jdbc
.
It is simple , remove the code that you have used and use the below code :
const url = 'mongodb://localhost:27017';
var dbConn = mongodb.MongoClient.connect(url, {useUnifiedTopology: true});
I do believe that the correct answer has already been provided by @Alex V, yet the answer does require some modernization as it is over five years old now.
There are two main issues:
Never use object
as a parameter name. It is a reservered word. With this being said, @Alex V's provided function will not work in strict mode
.
The addEvent
function provided by @Alex V does not return the event object
if the addEventListener
method is used. Another parameter should be added to the addEvent
function to allow for this.
NOTE: The new parameter to addEvent
has been made optional so that migrating to this new function version will not break any previous calls to this function. All legacy uses will be supported.
Here is the updated addEvent
function with these changes:
/*
function: addEvent
@param: obj (Object)(Required)
- The object which you wish
to attach your event to.
@param: type (String)(Required)
- The type of event you
wish to establish.
@param: callback (Function)(Required)
- The method you wish
to be called by your
event listener.
@param: eventReturn (Boolean)(Optional)
- Whether you want the
event object returned
to your callback method.
*/
var addEvent = function(obj, type, callback, eventReturn)
{
if(obj == null || typeof obj === 'undefined')
return;
if(obj.addEventListener)
obj.addEventListener(type, callback, eventReturn ? true : false);
else if(obj.attachEvent)
obj.attachEvent("on" + type, callback);
else
obj["on" + type] = callback;
};
An example call to the new addEvent
function:
var watch = function(evt)
{
/*
Older browser versions may return evt.srcElement
Newer browser versions should return evt.currentTarget
*/
var dimensions = {
height: (evt.srcElement || evt.currentTarget).innerHeight,
width: (evt.srcElement || evt.currentTarget).innerWidth
};
};
addEvent(window, 'resize', watch, true);
Ricardo's answer is correct, however: sometimes you may find yourself in a situation where the container simply doesn't resize as desired as the browser window changes size, thus not allowing highcharts to resize itself.
This always works:
chart.setSize(width, height, doAnimation =
true);
in your actual resize function to set the height and width
dynamicallyreflow: false
in the highcharts-options and of course set height
and width
explicitly on creation. As we'll be doing our own resize event handling there's no need Highcharts hooks in another one.IntegraStudio enables syntax coloring, building, debugging and finding definition and references (F12 and ALT-F12) for Java projects in Visual Studio.
Kotlin version with infix function
infix fun View.below(view: View) {
(this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}
Then you can write:
view1 below view2
Or you can call it as a normal function:
view1.below(view2)
The t
indicates text mode, meaning that \n
characters will be translated to the host OS line endings when writing to a file, and back again when reading. The flag is basically just noise, since text mode is the default.
Other than U
, those mode flags come directly from the standard C library's fopen()
function, a fact that is documented in the sixth paragraph of the python2 documentation for open()
.
As far as I know, t
is not and has never been part of the C standard, so although many implementations of the C library accept it anyway, there's no guarantee that they all will, and therefore no guarantee that it will work on every build of python. That explains why the python2 docs didn't list it, and why it generally worked anyway. The python3 docs make it official.
In my case I have a group of files which needs to be renamed before I can work with them. Each file has its own role in group and has its own pattern.
As result I have a list of rename commands like this:
f=`ls *canctn[0-9]*` ; mv $f CNLC.$f
f=`ls *acustb[0-9]*` ; mv $f CATB.$f
f=`ls *accusgtb[0-9]*` ; mv $f CATB.$f
f=`ls *acus[0-9]*` ; mv $f CAUS.$f
Try this also :
f=MyFileName; mv $f {pref1,pref2}$f{suf1,suf2}
This will produce all combinations with prefixes and suffixes:
pref1.MyFileName.suf1
...
pref2.MyFileName.suf2
Another way to solve same problem is to create mapping array and add corespondent prefix for each file type as shown below:
#!/bin/bash
unset masks
typeset -A masks
masks[ip[0-9]]=ip
masks[iaf_usg[0-9]]=ip_usg
masks[ipusg[0-9]]=ip_usg
...
for fileMask in ${!masks[*]};
do
registryEntry="${masks[$fileMask]}";
fileName=*${fileMask}*
[ -e ${fileName} ] && mv ${fileName} ${registryEntry}.${fileName}
done
Rails 2.X: @controller.action_name
Rails 3.1.X: controller.action_name
, action_name
Rails 4.X: action_name
dict(zip([1,2,3,4], [a,b,c,d]))
If the lists are big you should use itertools.izip
.
If you have more keys than values, and you want to fill in values for the extra keys, you can use itertools.izip_longest
.
Here, a
, b
, c
, and d
are variables -- it will work fine (so long as they are defined), but you probably meant ['a','b','c','d']
if you want them as strings.
zip
takes the first item from each iterable and makes a tuple, then the second item from each, etc. etc.
dict
can take an iterable of iterables, where each inner iterable has two items -- it then uses the first as the key and the second as the value for each item.
Maven is a powerful project management tool that is based on POM (project object model). It is used for projects build, dependency and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT. Maven helps to manage- Builds,Documentation,Reporing,SCMs,Releases,Distribution. - maven repository is a directory of packaged JAR file with pom.xml file. Maven searches for dependencies in the repositories.
You should use the setString()
method to set the userID
. This both ensures that the statement is formatted properly, and prevents SQL injection
:
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
There is a nice tutorial on how to use PreparedStatement
s properly in the Java Tutorials.
You can use the built-in ast.literal_eval
:
>>> import ast
>>> ast.literal_eval("{'muffin' : 'lolz', 'foo' : 'kitty'}")
{'muffin': 'lolz', 'foo': 'kitty'}
This is safer than using eval
. As its own docs say:
>>> help(ast.literal_eval) Help on function literal_eval in module ast: literal_eval(node_or_string) Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
For example:
>>> eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 208, in rmtree
onerror(os.listdir, path, sys.exc_info())
File "/opt/Python-2.6.1/lib/python2.6/shutil.py", line 206, in rmtree
names = os.listdir(path)
OSError: [Errno 2] No such file or directory: 'mongo'
>>> ast.literal_eval("shutil.rmtree('mongo')")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 68, in literal_eval
return _convert(node_or_string)
File "/opt/Python-2.6.1/lib/python2.6/ast.py", line 67, in _convert
raise ValueError('malformed string')
ValueError: malformed string
If you want it to be dynamic, so that the value of the variable at the time of the click is used, do the following:
<script language="javascript" type="text/javascript">
var scrt_var = 10;
</script>
<a href="2.html" onclick="location.href=this.href+'?key='+scrt_var;return false;">Link</a>
Of course, that's the quick and dirty solution. You should really have a script that after DOM load adds an onclick handler to all relevant <a>
elements.
import random
a=[]
n=int(input("Enter number of elements:"))
for j in range(n):
a.append(random.randint(1,20))
print('Randomised list is: ',a)
You can simply do:
Serial.println(n);
which will convert n
to an ASCII string automatically. See the documentation for Serial.println()
.
Use Come thing link this , This is Based on Bootstrap 3.0
.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active > a:hover, .navbar-default .navbar-nav > .active > a:focus {
background-color: #977EBD;
color: #FFFFFF;
}
.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
background-color: #977EBD;
color: #FFFFFF;
}
IrishChieftain didn't really address the question, so here's my take:
eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.
You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?
this.Controls.Add(dataGridView1);
By the way the code is a bit confused
String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql = "SELECT Clients FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
conn.Open();
DataSet ds = new DataSet();
DataGridView dataGridView1 = new DataGridView();
using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds;
// Of course, before addint the datagrid to the hosting form you need to
// set position, location and other useful properties.
// Why don't you create the DataGrid with the designer and use that instance instead?
this.Controls.Add(dataGridView1);
}
}
EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as
SELECT field_names_list FROM _tablename_
so the correct syntax to use for retrieving all the clients data is
string sql = "SELECT * FROM Clients";
where the *
means -> all the fields present in the table
As @racl101 has commented on an answer, this problem might be related to the folder owner. The rsync command should be done by the same user as the folder owner's one. If it's not the same, you can change it.
chown -R userCorrect /remote/path/to/foo/bar
Use this
file_get_contents($my_url,null,null);
\b
is a zero-width word boundary. Specifically:
Matches at the position between a word character (anything matched by \w) and a non-word character (anything matched by [^\w] or \W) as well as at the start and/or end of the string if the first and/or last characters in the string are word characters.
Example: .\b
matches c
in abc
\B
is a zero-width non-word boundary. Specifically:
Matches at the position between two word characters (i.e the position between \w\w) as well as at the position between two non-word characters (i.e. \W\W).
Example: \B.\B
matches b
in abc
See regular-expressions.info for more great regex info
Maybe map the share as a network drive and then do
git clone Z:\
Mostly just a guess; I always do this stuff using ssh. Following that suggstion of course will mean that you'll need to have that drive mapped every time you push/pull to/from the laptop. I'm not sure how you rig up ssh to work under windows but if you're going to be doing this a lot it might be worth investigating.
The solution is to set the proxy to "native" as below
Go to "Window-> Preferences -> General -> Network Connection" and change the Settings "Active Provider-> Native". It worked for me.
Swift 3 extension wrapper from @Nikolai Ruhe answer.
extension UIImageView {
func maskWith(color: UIColor) {
guard let tempImage = image?.withRenderingMode(.alwaysTemplate) else { return }
image = tempImage
tintColor = color
}
}
It can be use for UIButton
as well, e.g:
button.imageView?.maskWith(color: .blue)
locals
in Rails 4.2+In Rails 4.2 I had to remove the locals
part and just use size: 30
instead. Otherwise, it wouldn't pass the local variable correctly.
For example, use this:
<%= render @users, size: 30 %>
setTimeout
may help out here
$("#message_link").click(function(){
setTimeout(function() {
if (some_conditions...){
$("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\" /></div>");
}
}, 100);
});
That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.
You need to select that column:
In [41]:
df.loc[df['First Season'] > 1990, 'First Season'] = 1
df
Out[41]:
Team First Season Total Games
0 Dallas Cowboys 1960 894
1 Chicago Bears 1920 1357
2 Green Bay Packers 1921 1339
3 Miami Dolphins 1966 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 1950 1003
So the syntax here is:
df.loc[<mask>(here mask is generating the labels to index) , <optional column(s)> ]
You can check the docs and also the 10 minutes to pandas which shows the semantics
EDIT
If you want to generate a boolean indicator then you can just use the boolean condition to generate a boolean Series and cast the dtype to int
this will convert True
and False
to 1
and 0
respectively:
In [43]:
df['First Season'] = (df['First Season'] > 1990).astype(int)
df
Out[43]:
Team First Season Total Games
0 Dallas Cowboys 0 894
1 Chicago Bears 0 1357
2 Green Bay Packers 0 1339
3 Miami Dolphins 0 792
4 Baltimore Ravens 1 326
5 San Franciso 49ers 0 1003
It means that in table kontakty
you have a row referencing the row in osoby
you want to delete. You have do delete that row first or set a cascade delete on the relation between tables.
Powodzenia!
left = 37,up = 38, right = 39,down = 40
$(document).keydown(function(e) {
switch(e.which) {
case 37:
$( "#prev" ).click();
break;
case 38:
$( "#prev" ).click();
break;
case 39:
$( "#next" ).click();
break;
case 40:
$( "#next" ).click();
break;
default: return;
}
e.preventDefault();
});
To run multiple shell commands with ansible you can use the shell module with a multi-line string (note the pipe after shell:
), as shown in this example:
- name: Build nginx
shell: |
cd nginx-1.11.13
sudo ./configure
sudo make
sudo make install
Many times the bolded text is regarded in an information architecture way on another level and thus not have bolded and regular in one line, so you can split it to two labels/textViews, one regular and on bold italic. And use the editor to choose the font styles.
Type
C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --console
to start the sql server and then test the client connection.
another way to single instance an application is to check their hash sums. after messing around with mutex (didn't work as i want) i got it working this way:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool SetForegroundWindow(IntPtr hWnd);
public Main()
{
InitializeComponent();
Process current = Process.GetCurrentProcess();
string currentmd5 = md5hash(current.MainModule.FileName);
Process[] processlist = Process.GetProcesses();
foreach (Process process in processlist)
{
if (process.Id != current.Id)
{
try
{
if (currentmd5 == md5hash(process.MainModule.FileName))
{
SetForegroundWindow(process.MainWindowHandle);
Environment.Exit(0);
}
}
catch (/* your exception */) { /* your exception goes here */ }
}
}
}
private string md5hash(string file)
{
string check;
using (FileStream FileCheck = File.OpenRead(file))
{
MD5 md5 = new MD5CryptoServiceProvider();
byte[] md5Hash = md5.ComputeHash(FileCheck);
check = BitConverter.ToString(md5Hash).Replace("-", "").ToLower();
}
return check;
}
it checks only md5 sums by process id.
if an instance of this application was found, it focuses the running application and exit itself.
you can rename it or do what you want with your file. it wont open twice if the md5 hash is the same.
may someone has suggestions to it? i know it is answered, but maybe someone is looking for a mutex alternative.
There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:
MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.
Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (
.
) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs.+
and.-
are unnecessary.
I think several of the answers hit around the possible solution to your problem.
I agree the easiest (and best solution for SEO purposes) is the 301 redirect. In IIS this is fairly trivial, you'd create a site for subdomain.hostone.com, after creating the site, right-click on the site and go into properties. Click on the "Home Directory" tab of the site properties window that opens. Select the radio button "A redirection to a URL", enter the url for the new site (http://subdomain.hosttwo.com), and check the checkboxes for "The exact URL entered above", "A permanent redirection for this resource" (this second checkbox causes a 301 redirect, instead of a 302 redirect). Click OK, and you're done.
Or you could create a page on the site of http://subdomain.hostone.com, using one of the following methods (depending on what the hosting platform supports)
PHP Redirect:
<?
Header( "HTTP/1.1 301 Moved Permanently" );
Header( "Location: http://subdomain.hosttwo.com" );
?>
ASP Redirect:
<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://subdomain.hosttwo.com"
%>
ASP .NET Redirect:
<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://subdomain.hosttwo.com");
}
</script>
Now assuming your CNAME record is correctly created, then the only problem you are experiencing is that the site created for http://subdomain.hosttwo.com is using a shared IP, and host headers to determine which site should be displayed. To resolve this issue under IIS, in IIS Manager on the web server, you'd right-click on the site for subdomain.hosttwo.com, and click "Properties". On the displayed "Web Site" tab, you should see an "Advanced" button next to the IP address that you'll need to click. On the "Advanced Web Site Identification" window that appears, click "Add". Select the same IP address that is already being used by subdomain.hosttwo.com, enter 80 as the TCP port, and then enter subdomain.hosttwo.com as the Host Header value. Click OK until you are back to the main IIS Manager window, and you should be good to go. Open a browser, and browse to http://subdomain.hostone.com, and you'll see the site at http://subdomain.hosttwo.com appear, even though your URL shows http://subdomain.hostone.com
Hope that helps...
Here is the solution I was looking for. If you would like to create List2 that contains the difference of the number elements in List1.
list1 = [12, 15, 22, 54, 21, 68, 9, 73, 81, 34, 45]
list2 = []
for i in range(1, len(list1)):
change = list1[i] - list1[i-1]
list2.append(change)
Note that while len(list1)
is 11 (elements), len(list2)
will only be 10 elements because we are starting our for loop from element with index 1 in list1 not from element with index 0 in list1
You can combine ID and Class in CSS, but IDs are intended to be unique, so adding a class to a CSS selector would over-qualify it.
I had a really similar issue using HIVE in EMR. None of the extant solutions worked for me -- ie, none of the mapreduce configurations worked for me; and neither did setting yarn.nodemanager.vmem-check-enabled
to false.
However, what ended up working was setting tez.am.resource.memory.mb
, for example:
hive -hiveconf tez.am.resource.memory.mb=4096
Another setting to consider tweaking is yarn.app.mapreduce.am.resource.mb
You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.
Sub deleteCol()
On Error Resume Next
Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer
Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
End If
Next i
End Sub
With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.
EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare)
change the "1" in Cells(1, i)
to whatever row your headers are in.
EDIT 2: Changed the For
section of the code to account for completely empty columns.
.val()
does not return an array from a DOM element: $('#fruit')
is going to find the element in the document with an ID of #fruit and get its value (if it has a value).
On Visual Studio 2017, using the built-in database for development I had problems with the current given solution, I had to change the code to make it work because it threw the error that DATE() was not a built in function.
Here is my solution:
where CAST(TimeCalled AS DATE) = CAST(GETDATE() AS DATE)
Adding both android:layout_centerInParent
and android:layout_centerVertical
work for me to center ImageView
both vertical and horizontal:
<ImageView
..
android:layout_centerInParent="true"
android:layout_centerVertical="true"
/>
Here's a function that will do it, with comments that explain:
function displayNiceTime(date){
// getHours returns the hours in local time zone from 0 to 23
var hours = date.getHours()
// getMinutes returns the minutes in local time zone from 0 to 59
var minutes = date.getMinutes()
var meridiem = " AM"
// convert to 12-hour time format
if (hours > 12) {
hours = hours - 12
meridiem = ' PM'
}
else if (hours === 0){
hours = 12
}
// minutes should always be two digits long
if (minutes < 10) {
minutes = "0" + minutes.toString()
}
return hours + ':' + minutes + meridiem
}
Since, as others have noted, toLocaleTimeString() can be implemented differently in different browsers, this way gives better control.
To learn more about the Javascript Date object, this is a good resource: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Use:
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
// Create a couple of columns
model.addColumn("Col1");
model.addColumn("Col2");
// Append a row
model.addRow(new Object[]{"v1", "v2"});
I've had this problem. See The Python "Connection Reset By Peer" Problem.
You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.
You can (sometimes) correct this with a time.sleep(0.01)
placed strategically.
"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.
Sometimes I think we can overcomplicate the solution just to avoid repeating one line of code. This is the reason I landed on this question in the first place.
After thinking about it for a bit I came to the conclusion that the simplest solution is to repeat the ReadLine
before and inside the loop.
using (var stringReader = new StringReader(input))
{
var line = await stringReader.ReadLineAsync();
while (line != null)
{
// do something
line = await stringReader.ReadLineAsync();
}
}
I realize this might be considered to not follow the DRY principle, but I think it's worth considering given the simplicity.
Here is some code that will give you the general idea.
You need to create a custom ClientHttpRequestFactory
in order to trust the certificate.
It looks like this:
final ClientHttpRequestFactory clientHttpRequestFactory =
new MyCustomClientHttpRequestFactory(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER, serverInfo);
restTemplate.setRequestFactory(clientHttpRequestFactory);
This is the implementation for MyCustomClientHttpRequestFactory
:
public class MyCustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {
private final HostnameVerifier hostNameVerifier;
private final ServerInfo serverInfo;
public MyCustomClientHttpRequestFactory (final HostnameVerifier hostNameVerifier,
final ServerInfo serverInfo) {
this.hostNameVerifier = hostNameVerifier;
this.serverInfo = serverInfo;
}
@Override
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod)
throws IOException {
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setHostnameVerifier(hostNameVerifier);
((HttpsURLConnection) connection).setSSLSocketFactory(initSSLContext()
.getSocketFactory());
}
super.prepareConnection(connection, httpMethod);
}
private SSLContext initSSLContext() {
try {
System.setProperty("https.protocols", "TLSv1");
// Set ssl trust manager. Verify against our server thumbprint
final SSLContext ctx = SSLContext.getInstance("TLSv1");
final SslThumbprintVerifier verifier = new SslThumbprintVerifier(serverInfo);
final ThumbprintTrustManager thumbPrintTrustManager =
new ThumbprintTrustManager(null, verifier);
ctx.init(null, new TrustManager[] { thumbPrintTrustManager }, null);
return ctx;
} catch (final Exception ex) {
LOGGER.error(
"An exception was thrown while trying to initialize HTTP security manager.", ex);
return null;
}
}
In this case my serverInfo
object contains the thumbprint of the server.
You need to implement the TrustManager
interface to get
the SslThumbprintVerifier
or any other method you want to verify your certificate (you can also decide to also always return true
).
The value org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
allows all host names.
If you need to verify the host name,
you will need to implement it differently.
I'm not sure about the user and password and how you implemented it.
Often,
you need to add a header to the restTemplate
named Authorization
with a value that looks like this: Base: <encoded user+password>
.
The user+password
must be Base64
encoded.
for(var key in object) {
console.log(object[key]);
}
NOTE: This is true for the version mentioned in the question, 4.1.1.RELEASE.
Spring MVC handles a ResponseEntity
return value through HttpEntityMethodProcessor
.
When the ResponseEntity
value doesn't have a body set, as is the case in your snippet, HttpEntityMethodProcessor
tries to determine a content type for the response body from the parameterization of the ResponseEntity
return type in the signature of the @RequestMapping
handler method.
So for
public ResponseEntity<Void> taxonomyPackageExists( @PathVariable final String key ) {
that type will be Void
. HttpEntityMethodProcessor
will then loop through all its registered HttpMessageConverter
instances and find one that can write a body for a Void
type. Depending on your configuration, it may or may not find any.
If it does find any, it still needs to make sure that the corresponding body will be written with a Content-Type that matches the type(s) provided in the request's Accept
header, application/xml
in your case.
If after all these checks, no such HttpMessageConverter
exists, Spring MVC will decide that it cannot produce an acceptable response and therefore return a 406 Not Acceptable HTTP response.
With ResponseEntity<String>
, Spring will use String
as the response body and find StringHttpMessageConverter
as a handler. And since StringHttpMessageHandler
can produce content for any media type (provided in the Accept
header), it will be able to handle the application/xml
that your client is requesting.
Spring MVC has since been changed to only return 406 if the body in the ResponseEntity
is NOT null
. You won't see the behavior in the original question if you're using a more recent version of Spring MVC.
In iddy85's solution, which seems to suggest ResponseEntity<?>
, the type for the body will be inferred as Object
. If you have the correct libraries in your classpath, ie. Jackson (version > 2.5.0) and its XML extension, Spring MVC will have access to MappingJackson2XmlHttpMessageConverter
which it can use to produce application/xml
for the type Object
. Their solution only works under these conditions. Otherwise, it will fail for the same reason I've described above.
My requirement is to display 10 digit phone number in the jsp. So here's the setup for me.
MySQL: numeric(10)
Java Side:
@NumberFormat(pattern = "#")
private long mobileNumber;
and it worked!
>>> dict([('A', 1), ('B', 2), ('C', 3)])
{'A': 1, 'C': 3, 'B': 2}
Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode
-Version 2
or higher is active. Parenthesised arguments are used in .NET methods only.
function foo($a, $b, $c) {
"a: $a; b: $b; c: $c"
}
ps> foo 1 2 3
a: 1; b: 2; c: 3
Nobody mentioned it so far... with utf8mb4 which is 4-byte and can also store emoticons (we should never more use 3-byte utf8) and we can avoid errors like Incorrect string value: \xF0\x9F\x98\...
we should not use typical VARCHAR(255) but rather VARCHAR(191) because in case utf8mb4 and VARCHAR(255) same part of data are stored off-page and you can not create index for column VARCHAR(255) but for VARCHAR(191) you can. It is because the maximum indexed column size is 767 bytes for ROW_FORMAT=COMPACT or ROW_FORMAT=REDUNDANT.
For newer row formats ROW_FORMAT=DYNAMIC or ROW_FORMAT=COMPRESSED (which requires newer file format innodb_file_format=Barracuda not older Antelope) maximum indexed column size is 3072. It is available since MySQL >= 5.6.3 when innodb_large_prefix=1 (disabled by default for MySQL <= 5.7.6 and enabled by default for MySQL >= 5.7.7). So in this case we can use VARCHAR(768) for utf8mb4 (or VARCHAR(1024) for old utf8) for indexed column. Option innodb_large_prefix is deprecated since 5.7.7 because its behavior is built-in MySQL 8 (in this version is option removed).
As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.
As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.
try this:
In [110]: (df.groupby('Company Name')
.....: .agg({'Organisation Name':'count', 'Amount': 'sum'})
.....: .reset_index()
.....: .rename(columns={'Organisation Name':'Organisation Count'})
.....: )
Out[110]:
Company Name Amount Organisation Count
0 Vifor Pharma UK Ltd 4207.93 5
or if you don't want to reset index:
df.groupby('Company Name')['Amount'].agg(['sum','count'])
or
df.groupby('Company Name').agg({'Amount': ['sum','count']})
Demo:
In [98]: df.groupby('Company Name')['Amount'].agg(['sum','count'])
Out[98]:
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
In [99]: df.groupby('Company Name').agg({'Amount': ['sum','count']})
Out[99]:
Amount
sum count
Company Name
Vifor Pharma UK Ltd 4207.93 5
Assuming you use bash shell and installed Java with the Oracle installer, you could add the following to your .bash_profile
export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/jre/bin:$PATH
This would pick the correct JAVA_HOME
as defined by the Oracle installer and will set it first in your $PATH
making sure it is found.
Also, you don't need to change it later when updating Java.
EDIT
As per the comments:
Making it persistent after a reboot
Just add those lines in the shell configuration file. (Assuming it's bash
)
Ex: .bashrc
, .bash_profile
or .profile
(for ubuntu)
Using a custom Java installation
Set JAVA_HOME
to the root folder of the custom Java installation path without the $()
.
Ex: JAVA_HOME=/opt/java/openjdk
If you use Laravel, then you can use logging functions such as info() to log to the Laravel log file under storage/logs. So it won't appear in your terminal but in the log file.
Your submit button doesn't have a name. Add name="submit" to your submit button.
If you view source on the form in the browser, you'll see how it submits to self - the form's action attribute will contain the name of the current script - therefore when the form submits, it submits to itself. Edit for vanity sake!
You can discover those things easily by yourself:
def hello(*args, **kwargs):
print kwargs
print type(kwargs)
print dir(kwargs)
hello(what="world")
If you're using knockout.bindings.dataTables.js
then you can edit the file and replace this line
dataTable.fnAddData(unwrappedItems);
with
if (unwrappedItems.length > 0) {
dataTable.fnAddData(unwrappedItems);
}
This has help me and i hope will help you.
input[type='checkbox', name='ProductCode']
That's the CSS way and I'm almost sure it will work in jQuery.
If you use auto-layout on iOS 6 you might also need to set the preferredMaxLayoutWidth
property:
button.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
button.titleLabel.textAlignment = NSTextAlignmentCenter;
button.titleLabel.preferredMaxLayoutWidth = button.frame.size.width;
The first example nearly always wins in my book:
if(foo)
{
}
It's shorter and more concise. Why add an extra check to something when it's absolutely not needed? Just wasting cycles...
I do agree, though, that sometimes the more verbose syntax makes things more readable (which is ultimately more important as long as performance is acceptable) in situations where variables are poorly named.
It's a pointer, so instead try:
a->f();
Basically the operator .
(used to access an object's fields and methods) is used on objects and references, so:
A a;
a.f();
A& ref = a;
ref.f();
If you have a pointer type, you have to dereference it first to obtain a reference:
A* ptr = new A();
(*ptr).f();
ptr->f();
The a->b
notation is usually just a shorthand for (*a).b
.
The operator->
can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use ->
to refer to the pointed object:
auto ptr = make_unique<A>();
ptr->f();
Set the CSS position: relative;
on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:
position: absolute;
bottom: 0;
right: 0;
If you need to space the text farther away from the edge, you could change 0
to 2px
or similar.
You're adding the event handler to the <select>
element.
Therefore, $(this)
will be the dropdown itself, not the selected <option>
.
You need to find the selected <option>
, like this:
var option = $('option:selected', this).attr('mytag');
I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.
After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.
So to access the variable, I type
string fp = Variables.FilePath;
In the PreExecute() method of the Script Component.
Instructions for Eclipse Indigo:
Once installed click on Window -> Show View -> Others. A new window pops up. Click on folder Hibernate and select Hibernate Configurations to setup a DB connection. It is possible to setup a new connection using an existing Hiberbate properties file or creating a JDBC connection.
Once setup your DB connection click on Ping to test everything is correct.
Lastly, click on the Open HQL Editor button (third button on the top Hibernate Configurations menu) to run a HQL query.
Late to the party, but... why not just this.hasAttribute("name")
?
Refer This
Use bytearray
:
with open("img.png", "rb") as image:
f = image.read()
b = bytearray(f)
print b[0]
You can also have a look at struct which can do many conversions of that kind.
Both call()
and apply()
are methods which are located on Function.prototype
. Therefore they are available on every function object via the prototype chain. Both call()
and apply()
can execute a function with a specified value of the this
.
The main difference between call()
and apply()
is the way you have to pass in arguments into it. In both call()
and apply()
you pass as a first argument the object you want to be the value as this
. The other arguments differ in the following way:
call()
you have to put in the arguments normally (starting from the second argument)apply()
you have to pass in array of arguments.let obj = {_x000D_
val1: 5,_x000D_
val2: 10_x000D_
}_x000D_
_x000D_
const summation = function (val3, val4) {_x000D_
return this.val1 + this.val2 + val3 + val4;_x000D_
}_x000D_
_x000D_
console.log(summation.apply(obj, [2 ,3]));_x000D_
// first we assign we value of this in the first arg_x000D_
// with apply we have to pass in an array_x000D_
_x000D_
_x000D_
console.log(summation.call(obj, 2, 3));_x000D_
// with call we can pass in each arg individually
_x000D_
The this
value can be tricky sometimes in javascript. The value of this
determined when a function is executed not when a function is defined. If our function is dependend on a right this
binding we can use call()
and apply()
to enforce this behaviour. For example:
var name = 'unwantedGlobalName';_x000D_
_x000D_
const obj = {_x000D_
name: 'Willem',_x000D_
sayName () { console.log(this.name);}_x000D_
}_x000D_
_x000D_
_x000D_
let copiedMethod = obj.sayName;_x000D_
// we store the function in the copiedmethod variable_x000D_
_x000D_
_x000D_
_x000D_
copiedMethod();_x000D_
// this is now window, unwantedGlobalName gets logged_x000D_
_x000D_
copiedMethod.call(obj);_x000D_
// we enforce this to be obj, Willem gets logged
_x000D_
Packaging an artifact as POM means that it has a very simple lifecycle
package -> install -> deploy
http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html
This is useful if you are deploying a pom.xml file or a project that doesn't fit with the other packaging types.
We use pom packaging for many of our projects and bind extra phases and goals as appropriate.
For example some of our applications use:
prepare-package -> test -> package -> install -> deploy
When you mvn install the application it should add it to your locally .m2 repository. To publish elsewhere you will need to set up correct distribution management information. You may also need to use the maven builder helper plugin, if artifacts aren't automatically attached to by Maven.
If you want to call a function on clicking of submit button then you have
to use ajax or jquery,if you want to call your php function after submission of form
you can do that as :
<html>
<body>
<form method="post" action="display()">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
if($_SERVER['REQUEST_METHOD']=='POST')
{
display();
}
?>
</body>
</html>
I've seen some terrible observer patterns here that cause memory leaks on large applications.
I might be a little late but it's as simple as this.
The watch function watches for reference changes (primitive types) if you want to watch something like array push simply use:
someArray.push(someObj); someArray = someArray.splice(0);
This will update the reference and update the watch from anywhere. Including a services getter method. Anything that's a primitive will be updated automatically.
For reference, a non-CSS solution:
Below is some JS that re-sizes a font depending on the text length within a container.
Codepen with slightly modified code, but same idea as below:
function scaleFontSize(element) {
var container = document.getElementById(element);
// Reset font-size to 100% to begin
container.style.fontSize = "100%";
// Check if the text is wider than its container,
// if so then reduce font-size
if (container.scrollWidth > container.clientWidth) {
container.style.fontSize = "70%";
}
}
For me, I call this function when a user makes a selection in a drop-down, and then a div in my menu gets populated (this is where I have dynamic text occurring).
scaleFontSize("my_container_div");
In addition, I also use CSS ellipses ("...") to truncate yet even longer text too, like so:
#my_container_div {
width: 200px; /* width required for text-overflow to work */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
So, ultimately:
Short text: e.g. "APPLES"
Fully rendered, nice big letters.
Long text: e.g. "APPLES & ORANGES"
Gets scaled down 70%, via the above JS scaling function.
Super long text: e.g. "APPLES & ORANGES & BANAN..."
Gets scaled down 70% AND gets truncated with a "..." ellipses, via the above JS scaling function together with the CSS rule.
You could also explore playing with CSS letter-spacing to make text narrower while keeping the same font size.
Quick answer:
A child scope normally prototypically inherits from its parent scope, but not always. One exception to this rule is a directive with scope: { ... }
-- this creates an "isolate" scope that does not prototypically inherit. This construct is often used when creating a "reusable component" directive.
As for the nuances, scope inheritance is normally straightfoward... until you need 2-way data binding (i.e., form elements, ng-model) in the child scope. Ng-repeat, ng-switch, and ng-include can trip you up if you try to bind to a primitive (e.g., number, string, boolean) in the parent scope from inside the child scope. It doesn't work the way most people expect it should work. The child scope gets its own property that hides/shadows the parent property of the same name. Your workarounds are
New AngularJS developers often do not realize that ng-repeat
, ng-switch
, ng-view
, ng-include
and ng-if
all create new child scopes, so the problem often shows up when these directives are involved. (See this example for a quick illustration of the problem.)
This issue with primitives can be easily avoided by following the "best practice" of always have a '.' in your ng-models – watch 3 minutes worth. Misko demonstrates the primitive binding issue with ng-switch
.
Having a '.' in your models will ensure that prototypal inheritance is in play. So, use
<input type="text" ng-model="someObj.prop1">
<!--rather than
<input type="text" ng-model="prop1">`
-->
Also placed on the AngularJS wiki: https://github.com/angular/angular.js/wiki/Understanding-Scopes
It is important to first have a solid understanding of prototypal inheritance, especially if you are coming from a server-side background and you are more familiar with class-ical inheritance. So let's review that first.
Suppose parentScope has properties aString, aNumber, anArray, anObject, and aFunction. If childScope prototypically inherits from parentScope, we have:
(Note that to save space, I show the anArray
object as a single blue object with its three values, rather than an single blue object with three separate gray literals.)
If we try to access a property defined on the parentScope from the child scope, JavaScript will first look in the child scope, not find the property, then look in the inherited scope, and find the property. (If it didn't find the property in the parentScope, it would continue up the prototype chain... all the way up to the root scope). So, these are all true:
childScope.aString === 'parent string'
childScope.anArray[1] === 20
childScope.anObject.property1 === 'parent prop1'
childScope.aFunction() === 'parent output'
Suppose we then do this:
childScope.aString = 'child string'
The prototype chain is not consulted, and a new aString property is added to the childScope. This new property hides/shadows the parentScope property with the same name. This will become very important when we discuss ng-repeat and ng-include below.
Suppose we then do this:
childScope.anArray[1] = '22'
childScope.anObject.property1 = 'child prop1'
The prototype chain is consulted because the objects (anArray and anObject) are not found in the childScope. The objects are found in the parentScope, and the property values are updated on the original objects. No new properties are added to the childScope; no new objects are created. (Note that in JavaScript arrays and functions are also objects.)
Suppose we then do this:
childScope.anArray = [100, 555]
childScope.anObject = { name: 'Mark', country: 'USA' }
The prototype chain is not consulted, and child scope gets two new object properties that hide/shadow the parentScope object properties with the same names.
Takeaways:
One last scenario:
delete childScope.anArray
childScope.anArray[1] === 22 // true
We deleted the childScope property first, then when we try to access the property again, the prototype chain is consulted.
The contenders:
scope: true
, directive with transclude: true
.scope: { ... }
. This creates an "isolate" scope instead.Note, by default, directives do not create new scope -- i.e., the default is scope: false
.
Suppose we have in our controller:
$scope.myPrimitive = 50;
$scope.myObject = {aNumber: 11};
And in our HTML:
<script type="text/ng-template" id="/tpl1.html">
<input ng-model="myPrimitive">
</script>
<div ng-include src="'/tpl1.html'"></div>
<script type="text/ng-template" id="/tpl2.html">
<input ng-model="myObject.aNumber">
</script>
<div ng-include src="'/tpl2.html'"></div>
Each ng-include generates a new child scope, which prototypically inherits from the parent scope.
Typing (say, "77") into the first input textbox causes the child scope to get a new myPrimitive
scope property that hides/shadows the parent scope property of the same name. This is probably not what you want/expect.
Typing (say, "99") into the second input textbox does not result in a new child property. Because tpl2.html binds the model to an object property, prototypal inheritance kicks in when the ngModel looks for object myObject -- it finds it in the parent scope.
We can rewrite the first template to use $parent, if we don't want to change our model from a primitive to an object:
<input ng-model="$parent.myPrimitive">
Typing (say, "22") into this input textbox does not result in a new child property. The model is now bound to a property of the parent scope (because $parent is a child scope property that references the parent scope).
For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via scope properties $parent, $$childHead and $$childTail. I normally don't show these scope properties in the diagrams.
For scenarios where form elements are not involved, another solution is to define a function on the parent scope to modify the primitive. Then ensure the child always calls this function, which will be available to the child scope due to prototypal inheritance. E.g.,
// in the parent scope
$scope.setMyPrimitive = function(value) {
$scope.myPrimitive = value;
}
Here is a sample fiddle that uses this "parent function" approach. (The fiddle was written as part of this answer: https://stackoverflow.com/a/14104318/215945.)
See also https://stackoverflow.com/a/13782671/215945 and https://github.com/angular/angular.js/issues/1267.
ng-switch scope inheritance works just like ng-include. So if you need 2-way data binding to a primitive in the parent scope, use $parent, or change the model to be an object and then bind to a property of that object. This will avoid child scope hiding/shadowing of parent scope properties.
See also AngularJS, bind scope of a switch-case?
Ng-repeat works a little differently. Suppose we have in our controller:
$scope.myArrayOfPrimitives = [ 11, 22 ];
$scope.myArrayOfObjects = [{num: 101}, {num: 202}]
And in our HTML:
<ul><li ng-repeat="num in myArrayOfPrimitives">
<input ng-model="num">
</li>
<ul>
<ul><li ng-repeat="obj in myArrayOfObjects">
<input ng-model="obj.num">
</li>
<ul>
For each item/iteration, ng-repeat creates a new scope, which prototypically inherits from the parent scope, but it also assigns the item's value to a new property on the new child scope. (The name of the new property is the loop variable's name.) Here's what the Angular source code for ng-repeat actually is:
childScope = scope.$new(); // child scope prototypically inherits from parent scope
...
childScope[valueIdent] = value; // creates a new childScope property
If item is a primitive (as in myArrayOfPrimitives), essentially a copy of the value is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence child scope num
) does not change the array the parent scope references. So in the first ng-repeat above, each child scope gets a num
property that is independent of the myArrayOfPrimitives array:
This ng-repeat will not work (like you want/expect it to). Typing into the textboxes changes the values in the gray boxes, which are only visible in the child scopes. What we want is for the inputs to affect the myArrayOfPrimitives array, not a child scope primitive property. To accomplish this, we need to change the model to be an array of objects.
So, if item is an object, a reference to the original object (not a copy) is assigned to the new child scope property. Changing the child scope property's value (i.e., using ng-model, hence obj.num
) does change the object the parent scope references. So in the second ng-repeat above, we have:
(I colored one line gray just so that it is clear where it is going.)
This works as expected. Typing into the textboxes changes the values in the gray boxes, which are visible to both the child and parent scopes.
See also Difficulty with ng-model, ng-repeat, and inputs and https://stackoverflow.com/a/13782671/215945
Nesting controllers using ng-controller results in normal prototypal inheritance, just like ng-include and ng-switch, so the same techniques apply. However, "it is considered bad form for two controllers to share information via $scope inheritance" -- http://onehungrymind.com/angularjs-sticky-notes-pt-1-architecture/ A service should be used to share data between controllers instead.
(If you really want to share data via controllers scope inheritance, there is nothing you need to do. The child scope will have access to all of the parent scope properties. See also Controller load order differs when loading or navigating)
scope: false
) - the directive does not create a new scope, so there is no inheritance here. This is easy, but also dangerous because, e.g., a directive might think it is creating a new property on the scope, when in fact it is clobbering an existing property. This is not a good choice for writing directives that are intended as reusable components.scope: true
- the directive creates a new child scope that prototypically inherits from the parent scope. If more than one directive (on the same DOM element) requests a new scope, only one new child scope is created. Since we have "normal" prototypal inheritance, this is like ng-include and ng-switch, so be wary of 2-way data binding to parent scope primitives, and child scope hiding/shadowing of parent scope properties.scope: { ... }
- the directive creates a new isolate/isolated scope. It does not prototypically inherit. This is usually your best choice when creating reusable components, since the directive cannot accidentally read or modify the parent scope. However, such directives often need access to a few parent scope properties. The object hash is used to set up two-way binding (using '=') or one-way binding (using '@') between the parent scope and the isolate scope. There is also '&' to bind to parent scope expressions. So, these all create local scope properties that are derived from the parent scope.
Note that attributes are used to help set up the binding -- you can't just reference parent scope property names in the object hash, you have to use an attribute. E.g., this won't work if you want to bind to parent property parentProp
in the isolated scope: <div my-directive>
and scope: { localProp: '@parentProp' }
. An attribute must be used to specify each parent property that the directive wants to bind to: <div my-directive the-Parent-Prop=parentProp>
and scope: { localProp: '@theParentProp' }
.
__proto__
references Object.
Isolate scope's $parent references the parent scope, so although it is isolated and doesn't inherit prototypically from the parent scope, it is still a child scope.
<my-directive interpolated="{{parentProp1}}" twowayBinding="parentProp2">
and
scope: { interpolatedProp: '@interpolated', twowayBindingProp: '=twowayBinding' }
scope.someIsolateProp = "I'm isolated"
transclude: true
- the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. The transcluded and the isolated scope (if any) are siblings -- the $parent property of each scope references the same parent scope. When a transcluded and an isolate scope both exist, isolate scope property $$nextSibling will reference the transcluded scope. I'm not aware of any nuances with the transcluded scope.
transclude: true
This fiddle has a showScope()
function that can be used to examine an isolate and transcluded scope. See the instructions in the comments in the fiddle.
There are four types of scopes:
scope: true
scope: {...}
. This one is not prototypal, but '=', '@', and '&' provide a mechanism to access parent scope properties, via attributes.transclude: true
. This one is also normal prototypal scope inheritance, but it is also a sibling of any isolate scope.For all scopes (prototypal or not), Angular always tracks a parent-child relationship (i.e., a hierarchy), via properties $parent and $$childHead and $$childTail.
Diagrams were generated with graphviz "*.dot" files, which are on github. Tim Caswell's "Learning JavaScript with Object Graphs" was the inspiration for using GraphViz for the diagrams.
You can get the current activity with getActivity()
Toast.makeText(getActivity(),"Toast your message" ,Toast.LENGTH_SHORT).show();
You can do that using your application.properties.
logging.level.=ERROR
-> Sets the root logging level to error
...
logging.level.=DEBUG
-> Sets the root logging level to DEBUG
logging.file=${java.io.tmpdir}/myapp.log
-> Sets the absolute log file path to TMPDIR/myapp.log
A sane default set of application.properties regarding logging using profiles would be:
application.properties:
spring.application.name=<your app name here>
logging.level.=ERROR
logging.file=${java.io.tmpdir}/${spring.application.name}.log
application-dev.properties:
logging.level.=DEBUG
logging.file=
When you develop inside your favourite IDE you just add a -Dspring.profiles.active=dev
as VM argument to the run/debug configuration of your app.
This will give you error only logging in production and debug logging during development WITHOUT writing the output to a log file. This will improve the performance during development ( and save SSD drives some hours of operation ;) ).
Once you opened the mongo CLI, connected and authorized on the right database.
The following example shows how to find the document with the _id=568c28fffc4be30d44d0398e from a collection called “products”:
db.products.find({"_id": ObjectId("568c28fffc4be30d44d0398e")})
The accepted answer doesn't seem to work if you unplug the network cable. Or the server crashes. Or your router crashes. Or if you forget to pay your internet bill. Set the TCP keep-alive options for better reliability.
public static class SocketExtensions
{
public static void SetSocketKeepAliveValues(this Socket instance, int KeepAliveTime, int KeepAliveInterval)
{
//KeepAliveTime: default value is 2hr
//KeepAliveInterval: default value is 1s and Detect 5 times
//the native structure
//struct tcp_keepalive {
//ULONG onoff;
//ULONG keepalivetime;
//ULONG keepaliveinterval;
//};
int size = Marshal.SizeOf(new uint());
byte[] inOptionValues = new byte[size * 3]; // 4 * 3 = 12
bool OnOff = true;
BitConverter.GetBytes((uint)(OnOff ? 1 : 0)).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)KeepAliveTime).CopyTo(inOptionValues, size);
BitConverter.GetBytes((uint)KeepAliveInterval).CopyTo(inOptionValues, size * 2);
instance.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
}
}
// ...
Socket sock;
sock.SetSocketKeepAliveValues(2000, 1000);
The time value sets the timeout since data was last sent. Then it attempts to send and receive a keep-alive packet. If it fails it retries 10 times (number hardcoded since Vista AFAIK) in the interval specified before deciding the connection is dead.
So the above values would result in 2+10*1 = 12 second detection. After that any read / wrtie / poll operations should fail on the socket.
Lets look at some test cases - try running the following expressions in your JS console:
"a" < "b"
"aa" < "ab"
"aaa" < "aab"
All return true.
JavaScript compares strings character by character and "a" comes before "b" in the alphabet - hence less than.
In your case it works like so -
1 . "a?aaa" < "?a?b"
compares the first two "a" characters - all equal, lets move to the next character.
2 . "a?a??aa" < "a?b??"
compares the second characters "a" against "b" - whoop! "a" comes before "b". Returns true.
If CSS3 is an option (or you have a fallback) you can use transform:
.center {
right: 50%;
bottom: 50%;
transform: translate(50%,50%);
position: absolute;
}
Unlike the first approach above, you don't want to use left:50% with the negative translation because there's an overflow bug in IE9+. Utilize a positive right value and you won't see horizontal scrollbars.
<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>
That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em'
as the measurement, you may want to use other units, like 'px'
.
EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:
In your HTML page, containing the <p>
tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:
<head>
<style type="text/css">
p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>
So above, all <p>
elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:
<head>
<style type="text/css">
.container p { margin-left:5em; /* Or another measurement unit, like px */ }
</style>
</head>
<body>
<div class="container">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</div>
<p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>
In the example above, only the <p>
element inside the div, whose class name is 'container', will have the styles applied - and not the <p>
element outside the container.
In addition to the above, you can collect your styles together and remove the style element from the <head>
tag, replacing it with a <link>
tag, which points to an external CSS file. This external file is where you'd now put your <p>
tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.
You can think of a mysql database
as a schema/user in Oracle
. If you have the privileges, you can query the DBA_USERS
view to see the list of schema.
Your program has no knowledge of where your VS project is, so see get path for my .exe and go ../..
to get your project's path.
Because the view must return render
, not just call it. Change the last line to
return render(request, 'auth_lifecycle/user_profile.html',
context_instance=RequestContext(request))
My solution might not be the cleanest but it should work with no problems.
The logic is simply to create a static variable to store your data on the Service
and update your view each second on your Activity
.
Let's say that you have a String
on your Service
that you want to send it to a TextView
on your Activity
. It should look like this
Your Service:
public class TestService extends Service {
public static String myString = "";
// Do some stuff with myString
Your Activty:
public class TestActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
setContentView(tv);
update();
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
update();
}
});
}
} catch (InterruptedException ignored) {}
}
};
t.start();
startService(new Intent(this, TestService.class));
}
private void update() {
// update your interface here
tv.setText(TestService.myString);
}
}
Presenting the Cadillac of Diffs as an SP. See within for the basic template that was based on answer by @erikkallen. It supports
exec Common.usp_DiffTableRows '#t1', '#t2';
exec Common.usp_DiffTableRows
@pTable0 = 'ydb.ysh.table1',
@pTable1 = 'xdb.xsh.table2',
@pOrderByCsvOpt = null, -- Order the results
@pOnlyCsvOpt = null, -- Only compare these columns
@pIgnoreCsvOpt = null; -- Ignore these columns (ignored if @pOnlyCsvOpt is specified)
alter proc [Common].[usp_DiffTableRows]
@pTable0 varchar(300),
@pTable1 varchar(300),
@pOrderByCsvOpt nvarchar(1000) = null, -- Order the Results
@pOnlyCsvOpt nvarchar(4000) = null, -- Only compare these columns
@pIgnoreCsvOpt nvarchar(4000) = null, -- Ignore these columns (ignored if @pOnlyCsvOpt is specified)
@pDebug bit = 0
as
/*---------------------------------------------------------------------------------------------------------------------
Purpose: Compare rows between two tables.
Usage: exec Common.usp_DiffTableRows '#a', '#b';
Modified By Description
---------- ---------- -------------------------------------------------------------------------------------------
2015.10.06 crokusek Initial Version
2019.03.13 crokusek Added @pOrderByCsvOpt
2019.06.26 crokusek Support for @pIgnoreCsvOpt, @pOnlyCsvOpt.
2019.09.04 crokusek Minor debugging improvement
2020.03.12 crokusek Detect duplicate rows in either source table
---------------------------------------------------------------------------------------------------------------------*/
begin try
if (substring(@pTable0, 1, 1) = '#')
set @pTable0 = 'tempdb..' + @pTable0; -- object_id test below needs full names for temp tables
if (substring(@pTable1, 1, 1) = '#')
set @pTable1 = 'tempdb..' + @pTable1; -- object_id test below needs full names for temp tables
if (object_id(@pTable0) is null)
raiserror('Table name is not recognized: ''%s''', 16, 1, @pTable0);
if (object_id(@pTable1) is null)
raiserror('Table name is not recognized: ''%s''', 16, 1, @pTable1);
create table #ColumnGathering
(
Name nvarchar(300) not null,
Sequence int not null,
TableArg tinyint not null
);
declare
@usp varchar(100) = object_name(@@procid),
@sql nvarchar(4000),
@sqlTemplate nvarchar(4000) =
'
use $database$;
insert into #ColumnGathering
select Name, column_id as Sequence, $TableArg$ as TableArg
from sys.columns c
where object_id = object_id(''$table$'', ''U'')
';
set @sql = replace(replace(replace(@sqlTemplate,
'$TableArg$', 0),
'$database$', (select DatabaseName from Common.ufn_SplitDbIdentifier(@pTable0))),
'$table$', @pTable0);
if (@pDebug = 1)
print 'Sql #CG 0: ' + @sql;
exec sp_executesql @sql;
set @sql = replace(replace(replace(@sqlTemplate,
'$TableArg$', 1),
'$database$', (select DatabaseName from Common.ufn_SplitDbIdentifier(@pTable1))),
'$table$', @pTable1);
if (@pDebug = 1)
print 'Sql #CG 1: ' + @sql;
exec sp_executesql @sql;
if (@pDebug = 1)
select * from #ColumnGathering;
select Name,
min(Sequence) as Sequence,
convert(bit, iif(min(TableArg) = 0, 1, 0)) as InTable0,
convert(bit, iif(max(TableArg) = 1, 1, 0)) as InTable1
into #Columns
from #ColumnGathering
group by Name
having ( @pOnlyCsvOpt is not null
and Name in (select Value from Common.ufn_UsvToNVarcharKeyTable(@pOnlyCsvOpt, default)))
or
( @pOnlyCsvOpt is null
and @pIgnoreCsvOpt is not null
and Name not in (select Value from Common.ufn_UsvToNVarcharKeyTable(@pIgnoreCsvOpt, default)))
or
( @pOnlyCsvOpt is null
and @pIgnoreCsvOpt is null)
if (exists (select 1 from #Columns where InTable0 = 0 or InTable1 = 0))
begin
select 1; -- without this the debugging info doesn't stream sometimes
select * from #Columns order by Sequence;
waitfor delay '00:00:02'; -- give results chance to stream before raising exception
raiserror('Columns are not equal between tables, consider using args @pIgnoreCsvOpt, @pOnlyCsvOpt. See Result Sets for details.', 16, 1);
end
if (@pDebug = 1)
select * from #Columns order by Sequence;
declare
@columns nvarchar(4000) = --iif(@pOnlyCsvOpt is null and @pIgnoreCsvOpt is null,
-- '*',
(
select substring((select ',' + ac.name
from #Columns ac
order by Sequence
for xml path('')),2,200000) as csv
);
if (@pDebug = 1)
begin
print 'Columns: ' + @columns;
waitfor delay '00:00:02'; -- give results chance to stream before possibly raising exception
end
-- Based on https://stackoverflow.com/a/2077929/538763
-- - Added sensing for duplicate rows
-- - Added reporting of source table location
--
set @sqlTemplate = '
with
a as (select ~, Row_Number() over (partition by ~ order by (select null)) -1 as Duplicates from $a$),
b as (select ~, Row_Number() over (partition by ~ order by (select null)) -1 as Duplicates from $b$)
select 0 as SourceTable, ~
from
(
select * from a
except
select * from b
) anb
union all
select 1 as SourceTable, ~
from
(
select * from b
except
select * from a
) bna
order by $orderBy$
';
set @sql = replace(replace(replace(replace(@sqlTemplate,
'$a$', @pTable0),
'$b$', @pTable1),
'~', @columns),
'$orderBy$', coalesce(@pOrderByCsvOpt, @columns + ', SourceTable')
);
if (@pDebug = 1)
print 'Sql: ' + @sql;
exec sp_executesql @sql;
end try
begin catch
declare
@CatchingUsp varchar(100) = object_name(@@procid);
if (xact_state() = -1)
rollback;
-- Disabled for S.O. post
--exec Common.usp_Log
--@pMethod = @CatchingUsp;
--exec Common.usp_RethrowError
--@pCatchingMethod = @CatchingUsp;
throw;
end catch
go
create function Common.Trim
(
@pOriginalString nvarchar(max),
@pCharsToTrim nvarchar(50) = null -- specify null or 'default' for whitespae
)
returns table
with schemabinding
as
/*--------------------------------------------------------------------------------------------------
Purpose: Trim the specified characters from a string.
Modified By Description
---------- -------------- --------------------------------------------------------------------
2012.09.25 S.Rutszy/crok Modified from https://dba.stackexchange.com/a/133044/9415
--------------------------------------------------------------------------------------------------*/
return
with cte AS
(
select patindex(N'%[^' + EffCharsToTrim + N']%', @pOriginalString) AS [FirstChar],
patindex(N'%[^' + EffCharsToTrim + N']%', reverse(@pOriginalString)) AS [LastChar],
len(@pOriginalString + N'~') - 1 AS [ActualLength]
from
(
select EffCharsToTrim = coalesce(@pCharsToTrim, nchar(0x09) + nchar(0x20) + nchar(0x0d) + nchar(0x0a))
) c
)
select substring(@pOriginalString, [FirstChar],
((cte.[ActualLength] - [LastChar]) - [FirstChar] + 2)
) AS [TrimmedString]
--
--cte.[ActualLength],
--[FirstChar],
--((cte.[ActualLength] - [LastChar]) + 1) AS [LastChar]
from cte;
go
create function [Common].[ufn_UsvToNVarcharKeyTable] (
@pCsvList nvarchar(MAX),
@pSeparator nvarchar(1) = ',' -- can pass keyword 'default' when calling using ()'s
)
--
-- SQL Server 2012 distinguishes nvarchar keys up to maximum of 450 in length (900 bytes)
--
returns @tbl table (Value nvarchar(450) not null primary key(Value)) as
/*-------------------------------------------------------------------------------------------------
Purpose: Converts a comma separated list of strings into a sql NVarchar table. From
http://www.programmingado.net/a-398/SQL-Server-parsing-CSV-into-table.aspx
This may be called from RunSelectQuery:
GRANT SELECT ON Common.ufn_UsvToNVarcharTable TO MachCloudDynamicSql;
Modified By Description
---------- -------------- -------------------------------------------------------------------
2011.07.13 internet Initial version
2011.11.22 crokusek Support nvarchar strings and a custom separator.
2017.12.06 crokusek Trim leading and trailing whitespace from each element.
2019.01.26 crokusek Remove newlines
-------------------------------------------------------------------------------------------------*/
begin
declare
@pos int,
@textpos int,
@chunklen smallint,
@str nvarchar(4000),
@tmpstr nvarchar(4000),
@leftover nvarchar(4000),
@csvList nvarchar(max) = iif(@pSeparator not in (char(13), char(10), char(13) + char(10)),
replace(replace(@pCsvList, char(13), ''), char(10), ''),
@pCsvList); -- remove newlines
set @textpos = 1
set @leftover = ''
while @textpos <= len(@csvList)
begin
set @chunklen = 4000 - len(@leftover)
set @tmpstr = ltrim(@leftover + substring(@csvList, @textpos, @chunklen))
set @textpos = @textpos + @chunklen
set @pos = charindex(@pSeparator, @tmpstr)
while @pos > 0
begin
set @str = substring(@tmpstr, 1, @pos - 1)
set @str = (select TrimmedString from Common.Trim(@str, default));
insert @tbl (value) values(@str);
set @tmpstr = ltrim(substring(@tmpstr, @pos + 1, len(@tmpstr)))
set @pos = charindex(@pSeparator, @tmpstr)
end
set @leftover = @tmpstr
end
-- Handle @leftover
set @str = (select TrimmedString from Common.Trim(@leftover, default));
if @str <> ''
insert @tbl (value) values(@str);
return
end
GO
create function Common.ufn_SplitDbIdentifier(@pIdentifier nvarchar(300))
returns @table table
(
InstanceName nvarchar(300) not null,
DatabaseName nvarchar(300) not null,
SchemaName nvarchar(300),
BaseName nvarchar(300) not null,
FullTempDbBaseName nvarchar(300), -- non-null for tempdb (e.g. #Abc____...)
InstanceWasSpecified bit not null,
DatabaseWasSpecified bit not null,
SchemaWasSpecified bit not null,
IsCurrentInstance bit not null,
IsCurrentDatabase bit not null,
IsTempDb bit not null,
OrgIdentifier nvarchar(300) not null
) as
/*-----------------------------------------------------------------------------------------------------------
Purpose: Split a Sql Server Identifier into its parts, providing appropriate default values and
handling temp table (tempdb) references.
Example: select * from Common.ufn_SplitDbIdentifier('t')
union all
select * from Common.ufn_SplitDbIdentifier('s.t')
union all
select * from Common.ufn_SplitDbIdentifier('d.s.t')
union all
select * from Common.ufn_SplitDbIdentifier('i.d.s.t')
union all
select * from Common.ufn_SplitDbIdentifier('#d')
union all
select * from Common.ufn_SplitDbIdentifier('tempdb..#d');
-- Empty
select * from Common.ufn_SplitDbIdentifier('illegal name');
Modified By Description
---------- -------------- -----------------------------------------------------------------------------
2013.09.27 crokusek Initial version.
-----------------------------------------------------------------------------------------------------------*/
begin
declare
@name nvarchar(300) = ltrim(rtrim(@pIdentifier));
-- Return an empty table as a "throw"
--
--Removed for SO post
--if (Common.ufn_IsSpacelessLiteralIdentifier(@name) = 0)
-- return;
-- Find dots starting from the right by reversing first.
declare
@revName nvarchar(300) = reverse(@name);
declare
@firstDot int = charindex('.', @revName);
declare
@secondDot int = iif(@firstDot = 0, 0, charindex('.', @revName, @firstDot + 1));
declare
@thirdDot int = iif(@secondDot = 0, 0, charindex('.', @revName, @secondDot + 1));
declare
@fourthDot int = iif(@thirdDot = 0, 0, charindex('.', @revName, @thirdDot + 1));
--select @firstDot, @secondDot, @thirdDot, @fourthDot, len(@name);
-- Undo the reverse() (first dot is first from the right).
--
set @firstDot = iif(@firstDot = 0, 0, len(@name) - @firstDot + 1);
set @secondDot = iif(@secondDot = 0, 0, len(@name) - @secondDot + 1);
set @thirdDot = iif(@thirdDot = 0, 0, len(@name) - @thirdDot + 1);
set @fourthDot = iif(@fourthDot = 0, 0, len(@name) - @fourthDot + 1);
--select @firstDot, @secondDot, @thirdDot, @fourthDot, len(@name);
declare
@baseName nvarchar(300) = substring(@name, @firstDot + 1, len(@name) - @firstdot);
declare
@schemaName nvarchar(300) = iif(@firstDot - @secondDot - 1 <= 0,
null,
substring(@name, @secondDot + 1, @firstDot - @secondDot - 1));
declare
@dbName nvarchar(300) = iif(@secondDot - @thirdDot - 1 <= 0,
null,
substring(@name, @thirdDot + 1, @secondDot - @thirdDot - 1));
declare
@instName nvarchar(300) = iif(@thirdDot - @fourthDot - 1 <= 0,
null,
substring(@name, @fourthDot + 1, @thirdDot - @fourthDot - 1));
with input as (
select
coalesce(@instName, '[' + @@servername + ']') as InstanceName,
coalesce(@dbName, iif(left(@baseName, 1) = '#', 'tempdb', db_name())) as DatabaseName,
coalesce(@schemaName, iif(left(@baseName, 1) = '#', 'dbo', schema_name())) as SchemaName,
@baseName as BaseName,
iif(left(@baseName, 1) = '#',
(
select [name] from tempdb.sys.objects
where object_id = object_id('tempdb..' + @baseName)
),
null) as FullTempDbBaseName,
iif(@instName is null, 0, 1) InstanceWasSpecified,
iif(@dbName is null, 0, 1) DatabaseWasSpecified,
iif(@schemaName is null, 0, 1) SchemaWasSpecified
)
insert into @table
select i.InstanceName, i.DatabaseName, i.SchemaName, i.BaseName, i.FullTempDbBaseName,
i.InstanceWasSpecified, i.DatabaseWasSpecified, i.SchemaWasSpecified,
iif(i.InstanceName = '[' + @@servername + ']', 1, 0) as IsCurrentInstance,
iif(i.DatabaseName = db_name(), 1, 0) as IsCurrentDatabase,
iif(left(@baseName, 1) = '#', 1, 0) as IsTempDb,
@name as OrgIdentifier
from input i;
return;
end
GO
Like this?
public static void Test()
{
using (var image = Image.FromFile(@"c:\logo.png"))
using (var newImage = ScaleImage(image, 300, 400))
{
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
Why should I use it instead of optparse? Are their new features I should know about?
@Nicholas's answer covers this well, I think, but not the more "meta" question you start with:
Why has yet another command-line parsing module been created?
That's the dilemma number one when any useful module is added to the standard library: what do you do when a substantially better, but backwards-incompatible, way to provide the same kind of functionality emerges?
Either you stick with the old and admittedly surpassed way (typically when we're talking about complicated packages: asyncore vs twisted, tkinter vs wx or Qt, ...) or you end up with multiple incompatible ways to do the same thing (XML parsers, IMHO, are an even better example of this than command-line parsers -- but the email
package vs the myriad old ways to deal with similar issues isn't too far away either;-).
You may make threatening grumbles in the docs about the old ways being "deprecated", but (as long as you need to keep backwards compatibility) you can't really take them away without stopping large, important applications from moving to newer Python releases.
(Dilemma number two, not directly related to your question, is summarized in the old saying "the standard library is where good packages go to die"... with releases every year and a half or so, packages that aren't very, very stable, not needing releases any more often than that, can actually suffer substantially by being "frozen" in the standard library... but, that's really a different issue).
The previous answers don't seem to satisfy all four of my obsessive compulsive ticks:
My solution isn't pretty, and I don't think I can recommend using it, but here it is:
def iter_split_on_predicate(predicate: Callable[[T], bool], iterable: Iterable[T]) -> Tuple[Iterator[T], Iterator[T]]:
deque_predicate_true = deque()
deque_predicate_false = deque()
# define a generator function to consume the input iterable
# the Predicate is evaluated once per item, added to the appropriate deque, and the predicate result it yielded
def shared_generator(definitely_an_iterator):
for item in definitely_an_iterator:
print("Evaluate predicate.")
if predicate(item):
deque_predicate_true.appendleft(item)
yield True
else:
deque_predicate_false.appendleft(item)
yield False
# consume input iterable only once,
# converting to an iterator with the iter() function if necessary. Probably this conversion is unnecessary
shared_gen = shared_generator(
iterable if isinstance(iterable, collections.abc.Iterator) else iter(iterable)
)
# define a generator function for each predicate outcome and queue
def iter_for(predicate_value, hold_queue):
def consume_shared_generator_until_hold_queue_contains_something():
if not hold_queue:
try:
while next(shared_gen) != predicate_value:
pass
except:
pass
consume_shared_generator_until_hold_queue_contains_something()
while hold_queue:
print("Yield where predicate is "+str(predicate_value))
yield hold_queue.pop()
consume_shared_generator_until_hold_queue_contains_something()
# return a tuple of two generators
return iter_for(predicate_value=True, hold_queue=deque_predicate_true), iter_for(predicate_value=False, hold_queue=deque_predicate_false)
Testing with the following we get the output below from the print statements:
t,f = iter_split_on_predicate(lambda item:item>=10,[1,2,3,10,11,12,4,5,6,13,14,15])
print(list(zip(t,f)))
# Evaluate predicate.
# Evaluate predicate.
# Evaluate predicate.
# Evaluate predicate.
# Yield where predicate is True
# Yield where predicate is False
# Evaluate predicate.
# Yield where predicate is True
# Yield where predicate is False
# Evaluate predicate.
# Yield where predicate is True
# Yield where predicate is False
# Evaluate predicate.
# Evaluate predicate.
# Evaluate predicate.
# Evaluate predicate.
# Yield where predicate is True
# Yield where predicate is False
# Evaluate predicate.
# Yield where predicate is True
# Yield where predicate is False
# Evaluate predicate.
# Yield where predicate is True
# Yield where predicate is False
# [(10, 1), (11, 2), (12, 3), (13, 4), (14, 5), (15, 6)]
In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.
def change change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13 change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13 end
Remove the *
from your query and use individual column names, like this:
SELECT SOME_OTHER_COLUMN, CONCAT(FIRSTNAME, ',', LASTNAME) AS FIRSTNAME FROM `customer`;
Using *
means, in your results you want all the columns of the table. In your case *
will also include FIRSTNAME
. You are then concatenating some columns and using alias of FIRSTNAME
. This creates 2 columns with same name.
Starting with API level 18 (Jellybean MR2) you can cancel Notifications other than your own via NotificationListenerService.
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public class MyNotificationListenerService extends NotificationListenerService {...}
...
private void clearNotificationExample(StatusBarNotification sbn) {
myNotificationListenerService.cancelNotification(sbn.getPackageName(), sbn.getTag(), sbn.getId());
}
Another way is to inject applicationContext through servlet.
This is an example of how to inject dependencies when using Spring web services.
<servlet>
<servlet-name>my-soap-ws</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<init-param>
<param-name>transformWsdlLocations</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:my-applicationContext.xml</param-value>
</init-param>
<load-on-startup>5</load-on-startup>
</servlet>
Alternate way is to add application Context in your web.xml as shown below
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/classes/my-another-applicationContext.xml
classpath:my-second-context.xml
</param-value>
</context-param>
Basically you are trying to tell servlet that it should look for beans defined in these context files.
It is happening because your .bash_profile is not reflecting changes.To reflect it, just use the following command
$ source .bash_profile
You can try this:
@OneToOne(cascade = CascadeType.REFRESH)
or
@OneToMany(cascade = CascadeType.REFRESH)
How I solved this.
For Node.js applications, you need to set your **public**
folder configuration.
// Express js
app.use(express.static(__dirname + '/public'));
Otherwise, you need to do like href="public/css/style.css".
<link href="public/assets/css/custom.css">
<script src="public/assets/js/scripts.js"></script>
Note: It will work for
http://localhost:3000/public/assets/css/custom.css
. But couldn't work after build. You need to setapp.use(express.static(__dirname + '/public'));
for Express
One other way around this is to use @Mock
annotation instead.
Doesn't work in all cases, but looks much sexier :)
Here's an example:
@RunWith(MockitoJUnitRunner.class)
public class FooTests {
@Mock
public Foo<Bar> fooMock;
@Test
public void testFoo() {
when(fooMock.getValue()).thenReturn(new Bar());
}
}
The MockitoJUnitRunner
initializes the fields annotated with @Mock
.
Here is another simpler take:
df = pd.DataFrame([[0,1,3,4,np.nan,2],[3,5,6,np.nan,3,3]])
inds = np.asarray(df.isnull()).nonzero()
(array([0, 1], dtype=int64), array([4, 3], dtype=int64))
WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL '-3' DAY);
use quotes on the -3 value
Either in manifest class.
<activity android:name=".yourActivity"
....
android:screenOrientation="portrait" />
or programmatically
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
Note : you should call this before setContentView
method for your activity in onCreate()
.
Kotlin short version:
import android.os.Build.MANUFACTURER
import android.os.Build.MODEL
fun getDeviceName(): String =
(if (MODEL.startsWith(MANUFACTURER, ignoreCase = true)) {
MODEL
} else {
"$MANUFACTURER $MODEL"
}).capitalize()
The exception message says:
Books is not mapped [SELECT COUNT(*) FROM Books]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]
Books
is not mapped. That is, that there is no mapped type called Books
.
And indeed, there isn't. Your mapped type is called Book
. It's mapped to a table called Books
, but the type is called Book
. When you write HQL (or JPQL) queries, you use the names of the types, not the tables.
So, change your query to:
select count(*) from Book
Although I think it may need to be
select count(b) from Book b
If HQL doesn't support the *
notation.
Linux service init script are stored into /etc/init.d
. You can copy and customize /etc/init.d/skeleton
file, and then call
service [yourservice] start|stop|restart
see http://www.ralfebert.de/blog/java/debian_daemon/. Its for Debian (so, Ubuntu as well) but fit more distribution.
My way on Windows 8
Add a directory with ssh-keygen to the system PATH variable, usually C:\Program Files (x86)\Git\bin
Open CMD, go to C:\Users\Me\
Generate SSH key ssh-keygen -t rsa
Enter file in which to save the key (//.ssh/id_rsa): .ssh/id_rsa (change a default incorrect path to .ssh/somegoodname_rsa)
Add the key to Heroku heroku keys:add
Select a created key from a list
Go to your app directory, write some beautiful code
Init a git repo git init
git add .
git commit -m 'chore(release): v0.0.1
Create Heroku application heroku create
Deploy your app git push heroku master
Open your app heroku open
In addition, you can use it to check if the dynamic allocation was successful.
Code example:
int ** p;
p = new int * [5]; // Dynamic array (size 5) of pointers to int
for (int i = 0; i < 5; ++i) {
p[i] = new int[3]; // Each i(ptr) is now pointing to a dynamic
// array (size 3) of actual int values
}
assert (p); // Check the dynamic allocation.
Similar to:
if (p == NULL) {
cout << "dynamic allocation failed" << endl;
exit(1);
}
column pct_free format 999.99
select
used.tablespace_name,
(reserv.maxbytes - used.bytes)*100/reserv.maxbytes pct_free,
used.bytes/1024/1024/1024 used_gb,
reserv.maxbytes/1024/1024/1024 maxgb,
reserv.bytes/1024/1024/1024 gb,
(reserv.maxbytes - used.bytes)/1024/1024/1024 "max free bytes",
reserv.datafiles
from
(select tablespace_name, count(1) datafiles, sum(greatest(maxbytes,bytes)) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
(select tablespace_name, sum(bytes) bytes from dba_segments group by tablespace_name) used
where used.tablespace_name = reserv.tablespace_name
order by 2
/
Use find. For example:
find . -name "*.ext" | wc -l
Try
what's the problem with:
field like "*AA*" and field not like "*BB*"
it should be working.
Could you post some example of your data?
yes you can rename pane names, and not only window names starting with tmux >= 2.3. Just type the following in your shell:
printf '\033]2;%s\033\\' 'title goes here'
you might need to add the following to your .tmux.conf to display pane names:
# Enable names for panes
set -g pane-border-status top
you can also automatically assign a name:
set -g pane-border-format "#P: #{pane_current_command}"
i tried it worked tnx @Anastasiosyal i want to share it on this thread.
I'm not positive how the input fields did not trigger when I emptied the fields. But I managed to trigger each required field individually using:
$(".setting-p input").bind("change", function () {
//Seven.NetOps.validateSettings(Seven.NetOps.saveSettings);
/*$.validator.unobtrusive.parse($('#saveForm'));*/
$('#NodeZoomLevel').valid();
$('#ZoomLevel').valid();
$('#CenterLatitude').valid();
$('#CenterLongitude').valid();
$('#NodeIconSize').valid();
$('#SaveDashboard').valid();
$('#AutoRefresh').valid();
});
here's my view
@using (Html.BeginForm("SaveSettings", "Settings", FormMethod.Post, new {id = "saveForm"}))
{
<div id="sevenRightBody">
<div id="mapMenuitemPanel" class="setingsPanelStyle" style="display: block;">
<div class="defaultpanelTitleStyle">Map Settings</div>
Customize the map view upon initial navigation to the map view page.
<p class="setting-p">@Html.LabelFor(x => x.NodeZoomLevel)</p>
<p class="setting-p">@Html.EditorFor(x => x.NodeZoomLevel) @Html.ValidationMessageFor(x => x.NodeZoomLevel)</p>
<p class="setting-p">@Html.LabelFor(x => x.ZoomLevel)</p>
<p class="setting-p">@Html.EditorFor(x => x.ZoomLevel) @Html.ValidationMessageFor(x => x.ZoomLevel)</p>
<p class="setting-p">@Html.LabelFor(x => x.CenterLatitude)</p>
<p class="setting-p">@Html.EditorFor(x => x.CenterLatitude) @Html.ValidationMessageFor(x => x.CenterLatitude)</p>
<p class="setting-p">@Html.LabelFor(x => x.CenterLongitude)</p>
<p class="setting-p">@Html.EditorFor(x => x.CenterLongitude) @Html.ValidationMessageFor(x => x.CenterLongitude)</p>
<p class="setting-p">@Html.LabelFor(x => x.NodeIconSize)</p>
<p class="setting-p">@Html.SliderSelectFor(x => x.NodeIconSize) @Html.ValidationMessageFor(x => x.NodeIconSize)</p>
</div>
and my Entity
public class UserSetting : IEquatable<UserSetting>
{
[Required(ErrorMessage = "Missing Node Zoom Level.")]
[Range(200, 10000000, ErrorMessage = "Node Zoom Level must be between {1} and {2}.")]
[DefaultValue(100000)]
[Display(Name = "Node Zoom Level")]
public double NodeZoomLevel { get; set; }
[Required(ErrorMessage = "Missing Zoom Level.")]
[Range(200, 10000000, ErrorMessage = "Zoom Level must be between {1} and {2}.")]
[DefaultValue(1000000)]
[Display(Name = "Zoom Level")]
public double ZoomLevel { get; set; }
[Range(-90, 90, ErrorMessage = "Latitude degrees must be between {1} and {2}.")]
[Required(ErrorMessage = "Missing Latitude.")]
[DefaultValue(-200)]
[Display(Name = "Latitude")]
public double CenterLatitude { get; set; }
[Range(-180, 180, ErrorMessage = "Longitude degrees must be between {1} and {2}.")]
[Required(ErrorMessage = "Missing Longitude.")]
[DefaultValue(-200)]
[Display(Name = "Longitude")]
public double CenterLongitude { get; set; }
[Display(Name = "Save Dashboard")]
public bool SaveDashboard { get; set; }
.....
}
just do this:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
a * b
The other answers are correct as to "how" to resize them, but I would also thrown in the recommendation to just grab the resolution you are interested in, to begin with. Most Android devices offer a range of resolutions and you should pick one that gives you a file size that you're comfortable with. The biggest reason for this is that the native Android scaling algorithm (as detailed by Jin35 and Padma Kumar) produces pretty crappy results. It's not going to give you Photoshop quality resizing, even downscaling (to say nothing of upscaling, which I know you're not asking about, but that's just a non-starter).
So, you should try their solution and if you're happy with the outcome, great. But if not, I'd write a function that offers a range of width that you're happy with, and looks for that dimension (or whatever's closest) in the device's available picture size array and just set it and use it.
As it wasn't mentioned in any answers, just in case you want to align and space your text, you can use the string format features. (above python 2.5) Of course \t
is actually a TAB token whereas the described method generates spaces.
Example:
print "{0:30} {1}".format("hi", "yes")
> hi yes
Another Example, left aligned:
print("{0:<10} {1:<10} {2:<10}".format(1.0, 2.2, 4.4))
>1.0 2.2 4.4
Typical scenario,
scp -r -P port username@ip:/path-to-folder .
explained with an sample,
scp -r -P 27000 [email protected]:/tmp/hotel_dump .
where,
port = 27000
username = "abc" , remote server username
path-to-folder = tmp/hotel_dump
. = current local directory
some times the solution up doesn't work so you d have properly to remove the in class and add the css display:none manually .
$("#modal").removeClass("in");
$("#modal").css("display","none");
We can use Object.requireNonNull static method of Object class. Implementation is below
public void someMethod(SomeClass obj) {
Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}
You will never get a result, it's a simple logic error.
You're asking your database to return a row which has style_id = 24 AND style_id = 25 AND style_id = 26
. Since 24 is niether 25 nor 26, you will get no result.
You have to use OR
, then it makes some sense.
You cannot insert a class into a vector, you can insert an object (provided that it is of the proper type or convertible) of a class though.
If the type Player
has a default constructor, you can create a temporary object by doing Player()
, and that should work for your case:
vectorOfGamers.push_back(Player());
From python wiki:
>>> from operator import itemgetter, attrgetter
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
You can use System.Reflection.Assembly.Load*() methods and then grab their AssemblyInfo.
In Sender Activity Side:
Intent passIntent = new Intent(getApplicationContext(), "ActivityName".class);
passIntent.putExtra("value", integerValue);
startActivity(passIntent);
In Receiver Activity Side:
int receiveValue = getIntent().getIntExtra("value", 0);
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm()
returns false
, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Running ionic info
on your project directory give all the info you need the npm version, cli, app script and some more
To answer your first question: yes it is feasible to develop an android application in pure python, in order to achieve this I suggest you use BeeWare, which is just a suite of python tools, that work together very well and they enable you to develop platform native applications in python.
checkout this video by the creator of BeeWare that perfectly explains and demonstrates it's application
Android's preferred language of implementation is Java - so if you want to write an Android application in Python, you need to have a way to run your Python code on a Java Virtual Machine. This is what VOC does. VOC is a transpiler - it takes Python source code, compiles it to CPython Bytecode, and then transpiles that bytecode into Java-compatible bytecode. The end result is that your Python source code files are compiled directly to a Java .class file, which can be packaged into an Android application.
VOC also allows you to access native Java objects as if they were Python objects, implement Java interfaces with Python classes, and subclass Java classes with Python classes. Using this, you can write an Android application directly against the native Android APIs.
Once you've written your native Android application, you can use Briefcase to package your Python code as an Android application.
Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:
You can check This native Android Tic Tac Toe app written in Python, using the BeeWare suite. on GitHub
in addition to the BeeWare tools, you'll need to have a JDK and Android SDK installed to test run your application.
and to answer your second question: a good environment can be anything you are comfortable with be it a text editor and a command line, or an IDE, if you're looking for a good python IDE I would suggest you try Pycharm, it has a community edition which is free, and it has a similar environment as android studio, due to to the fact that were made by the same company.
I hope this has been helpful
Without actually seeing your output file for confirmation, my guess is that you've got to get rid of the FIELDS ESCAPED BY
value.
MySQL's FIELDS ESCAPED BY
is probably behaving in two ways that you were not counting on: (1) it is only meant to be one character, so in your case it is probably equal to just one quotation mark; (2) it is used to precede each character that MySQL thinks needs escaping, including the FIELDS TERMINATED BY
and LINES TERMINATED BY
values. This makes sense to most of the computing world, but it isn't the way Excel does escaping.
I think your double REPLACE
is working, and that you are successfully replacing literal newlines with spaces (two spaces in the case of Windows-style newlines). But if you have any commas in your data (literals, not field separators), these are being preceded by quotation marks, which Excel treats much differently than MySQL. If that's the case, then the erroneous newlines that are tripping up Excel are actually newlines that MySQL had intended as line terminators.
I have actually done this using a bit of sleight of hand: a single lookup table with 16 entries will suffice and all you have to do is break the binary rep into nibbles (4-bit tuples). The complexity is in fact O(1) and I wrote a C++ template which was specialized on the size of the integer you wanted (in # bits)… makes it a constant expression instead of indetermined.
fwiw you can use the fact that (i & -i) will return you the LS one-bit and simply loop, stripping off the lsbit each time, until the integer is zero — but that’s an old parity trick.
hi i got the same problem.. add 0.71 to excel cell width value and give that value to the
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
eg: A Column width = 3.71 (excel value)
give column width = 4.42
will give the output file with same cell width.
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(4.42);
hope this help
You can try this:
import os
current_dir = os.path.dirname(os.path.abspath(__file__)) # Can also use os.getcwd()
print(current_dir) # prints(say)- D:\abc\def\ghi\jkl\mno"
new_dir = os.chdir('..\\..\\..\\')
print(new_dir) # prints "D:\abc\def\ghi"
I also faced this issue. My Operating system is Ubuntu 18.04 and my PHP version is PHP 7.2.
Here's how I solved it:
Install Simplexml on your Ubuntu Server:
sudo apt-get install php7.2-simplexml
Restart Apache Server
sudo systemctl restart apache2
That's all.
I hope this helps
I have used mpdf in my project. In Codeigniter-3, putted mpdf files under application/third_party and then used in this way:
/**
* This function is used to display data in PDF file.
* function is using mpdf api to generate pdf.
* @param number $id : This is unique id of table.
*/
function generatePDF($id){
require APPPATH . '/third_party/mpdf/vendor/autoload.php';
//$mpdf=new mPDF();
$mpdf = new mPDF('utf-8', 'Letter', 0, '', 0, 0, 7, 0, 0, 0);
$checkRecords = $this->user_model->getCheckInfo($id);
foreach ($checkRecords as $key => $value) {
$data['info'] = $value;
$filename = $this->load->view(CHEQUE_VIEWS.'index',$data,TRUE);
$mpdf->WriteHTML($filename);
}
$mpdf->Output(); //output pdf document.
//$content = $mpdf->Output('', 'S'); //get pdf document content's as variable.
}
div
s shouldn't be used for tabular data. That is just as wrong as using tables for layout.
Use a <table>
. Its easy, semantically correct, and you'll be done in 5 minutes.
In my experience, SVN creates a tree conflict WHENEVER I delete a folder. There appears to be no reason.
I'm the only one working on my code -> delete a directory -> commit -> conflict!
I can't wait to switch to Git.
I should clarify - I use Subclipse. That's probably the problem! Again, I can't wait to switch...
There are multiple ways to do this.
Events - already explained well.
ui router - explained above.
*
<superhero flight speed strength> Superman is here! </superhero>
<superhero speed> Flash is here! </superhero>
*
app.directive('superhero', function(){
return {
restrict: 'E',
scope:{}, // IMPORTANT - to make the scope isolated else we will pollute it in case of a multiple components.
controller: function($scope){
$scope.abilities = [];
this.addStrength = function(){
$scope.abilities.push("strength");
}
this.addSpeed = function(){
$scope.abilities.push("speed");
}
this.addFlight = function(){
$scope.abilities.push("flight");
}
},
link: function(scope, element, attrs){
element.addClass('button');
element.on('mouseenter', function(){
console.log(scope.abilities);
})
}
}
});
app.directive('strength', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addStrength();
}
}
});
app.directive('speed', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addSpeed();
}
}
});
app.directive('flight', function(){
return{
require:'superhero',
link: function(scope, element, attrs, superHeroCtrl){
superHeroCtrl.addFlight();
}
}
});
Help -> About Eclipse Platform
For Eclipse Mars - you can check Eclipse -> About Eclipse
or Help -> Installation Details
, then you should see the version:
app.use() acts as a middleware in express apps. Unlike app.get() and app.post() or so, you actually can use app.use() without specifying the request URL. In such a case what it does is, it gets executed every time no matter what URL's been hit.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
</IfModule>
Cerating extention method like one suggested does not really solve issues with race conditions, but rather hide them.
public static void SafeInvoke(this EventHandler handler, object sender)
{
if (handler != null) handler(sender, EventArgs.Empty);
}
As stated this code is the elegant equivalent to solution with temporary variable, but...
The problem with both that it's possible that subsciber of the event could be called AFTER it has unsubscribed from the event. This is possible because unsubscription can happen after delegate instance is copied to the temp variable (or passed as parameter in the method above), but before delegate is invoked.
In general the behaviour of the client code is unpredictable in such case: component state could not allow to handle event notification already. It's possible to write client code in the way to handle it, but it would put unnecesssary responsibility to the client.
The only known way to ensure thread safity is to use lock statement for the sender of the event. This ensures that all subscriptions\unsubscriptions\invocation are serialized.
To be more accurate lock should be applied to the same sync object used in add\remove event accessor methods which is be default 'this'.
You could give the target parent an id or class (e.g. myParent) and reference is with $('#element').parents(".myParent")
this is the only one that really works:
me?fields=picture.type(*YOURTYPE*)
where YOURTYPE can be one of the following: small, normal, album, large, square
Just to say one thing, WindowsAPICodePack
can not open CommonOpenFileDialog
on Windows 7 6.1.7600.
Following is the best way to get of the issue , check following on classpath:
Make sure JAVA_HOME system variable must have till jdk e.g C:\Program Files\Java\jdk1.7.0_80
, don't append bin here.
Because MAVEN will look for jre which is under C:\Program Files\Java\jdk1.7.0_80
Set %JAVA_HOME%\bin
in classpath .
Then try Maven version .
Hope it will help .
here's another one:
Drawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
Another thing is - if your keys are very complicated sometimes you need to replace the places of the fields and it helps :
if this dosent work:
foreign key (ISBN, Title) references BookTitle (ISBN, Title)
Then this might work (not for this specific example but in general) :
foreign key (Title,ISBN) references BookTitle (Title,ISBN)
HTML code
<div ng-app>
<div ng-controller='ctrl'>
<div ng-class='whatClassIsIt(call.state[0])'>{{call.state[0]}}</div>
<div ng-class='whatClassIsIt(call.state[1])'>{{call.state[1]}}</div>
<div ng-class='whatClassIsIt(call.state[2])'>{{call.state[2]}}</div>
<div ng-class='whatClassIsIt(call.state[3])'>{{call.state[3]}}</div>
<div ng-class='whatClassIsIt(call.state[4])'>{{call.state[4]}}</div>
<div ng-class='whatClassIsIt(call.state[5])'>{{call.state[5]}}</div>
<div ng-class='whatClassIsIt(call.state[6])'>{{call.state[6]}}</div>
<div ng-class='whatClassIsIt(call.state[7])'>{{call.state[7]}}</div>
</div>
JavaScript Code
function ctrl($scope){
$scope.call={state:['second','first','nothing','Never', 'Gonna', 'Give', 'You', 'Up']}
$scope.whatClassIsIt= function(someValue){
if(someValue=="first")
return "ClassA"
else if(someValue=="second")
return "ClassB";
else
return "ClassC";
}
}
The standard way to do this sort of thing is to use external tools. Disallowing the use of external tools while writing a shell script is absurd. However, if you really don't want to use external tools, you can print line 5 with:
i=0; while read line; do test $((++i)) = 5 && echo "$line"; done < input-file
Note that this will print logical line 5. That is, if input-file
contains line continuations, they will be counted as a single line. You can change this behavior by adding -r
to the read command. (Which is probably the desired behavior.)
You can use readAllLines and the join
method to get whole file content in one line:
String str = String.join("\n",Files.readAllLines(Paths.get("e:\\text.txt")));
It uses UTF-8 encoding by default, which reads ASCII data correctly.
Also you can use readAllBytes:
String str = new String(Files.readAllBytes(Paths.get("e:\\text.txt")), StandardCharsets.UTF_8);
I think readAllBytes is faster and more precise, because it does not replace new line with \n
and also new line may be \r\n
. It is depending on your needs which one is suitable.
Just for fun, here some test:
#Added this for @Graimer's request ;) (not same computer, but one with HD little more #performant...)
measure-command { Get-Content ita\ita.txt -TotalCount 260000 | Select-Object -Last 1 }
Days : 0
Hours : 0
Minutes : 0
Seconds : 28
Milliseconds : 893
Ticks : 288932649
TotalDays : 0,000334412788194444
TotalHours : 0,00802590691666667
TotalMinutes : 0,481554415
TotalSeconds : 28,8932649
TotalMilliseconds : 28893,2649
> measure-command { (gc "c:\ps\ita\ita.txt")[260000] }
Days : 0
Hours : 0
Minutes : 0
Seconds : 9
Milliseconds : 257
Ticks : 92572893
TotalDays : 0,000107144552083333
TotalHours : 0,00257146925
TotalMinutes : 0,154288155
TotalSeconds : 9,2572893
TotalMilliseconds : 9257,2893
> measure-command { ([System.IO.File]::ReadAllLines("c:\ps\ita\ita.txt"))[260000] }
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 234
Ticks : 2348059
TotalDays : 2,71766087962963E-06
TotalHours : 6,52238611111111E-05
TotalMinutes : 0,00391343166666667
TotalSeconds : 0,2348059
TotalMilliseconds : 234,8059
> measure-command {get-content .\ita\ita.txt | select -index 260000}
Days : 0
Hours : 0
Minutes : 0
Seconds : 36
Milliseconds : 591
Ticks : 365912596
TotalDays : 0,000423509949074074
TotalHours : 0,0101642387777778
TotalMinutes : 0,609854326666667
TotalSeconds : 36,5912596
TotalMilliseconds : 36591,2596
the winner is : ([System.IO.File]::ReadAllLines( path ))[index]
A node
is the generic name for any type of object in the DOM hierarchy. A node
could be one of the built-in DOM elements such as document
or document.body
, it could be an HTML tag specified in the HTML such as <input>
or <p>
or it could be a text node that is created by the system to hold a block of text inside another element. So, in a nutshell, a node
is any DOM object.
An element
is one specific type of node
as there are many other types of nodes (text nodes, comment nodes, document nodes, etc...).
The DOM consists of a hierarchy of nodes where each node can have a parent, a list of child nodes and a nextSibling and previousSibling. That structure forms a tree-like hierarchy. The document
node has the html
node as its child.
The html
node has its list of child nodes (the head
node and the body
node). The body
node would have its list of child nodes (the top level elements in your HTML page) and so on.
So, a nodeList
is simply an array-like list of nodes
.
An element is a specific type of node, one that can be directly specified in the HTML with an HTML tag and can have properties like an id
or a class
. can have children, etc... There are other types of nodes such as comment nodes, text nodes, etc... with different characteristics. Each node has a property .nodeType
which reports what type of node it is. You can see the various types of nodes here (diagram from MDN):
You can see an ELEMENT_NODE
is one particular type of node where the nodeType
property has a value of 1
.
So document.getElementById("test")
can only return one node and it's guaranteed to be an element (a specific type of node). Because of that it just returns the element rather than a list.
Since document.getElementsByClassName("para")
can return more than one object, the designers chose to return a nodeList
because that's the data type they created for a list of more than one node. Since these can only be elements (only elements typically have a class name), it's technically a nodeList
that only has nodes of type element in it and the designers could have made a differently named collection that was an elementList
, but they chose to use just one type of collection whether it had only elements in it or not.
EDIT: HTML5 defines an HTMLCollection
which is a list of HTML Elements (not any node, only Elements). A number of properties or methods in HTML5 now return an HTMLCollection
. While it is very similar in interface to a nodeList
, a distinction is now made in that it only contains Elements, not any type of node.
The distinction between a nodeList
and an HTMLCollection
has little impact on how you use one (as far as I can tell), but the designers of HTML5 have now made that distinction.
For example, the element.children
property returns a live HTMLCollection.