Please enter domain nginx file :
nano /etc/nginx/sites-available/domain.set
Add to file this code
client_max_body_size 24000M;
If you get error use this command
nginx -t
Edit filename: core/Common.php, line number: 257
Before
return $_config[0] =& $config;
After
$_config[0] =& $config;
return $_config[0];
Added by NikiC
In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).
This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.
If you just run openssl
in your terminal it should present the openSSL shell. My first clue to knowing that I didn't have mode_ssl
was when I got the following error after adding SSLEngine on
in my virtualhost file:
Invalid command 'SSLEngine', perhaps misspelled or defined by a module not included in the server configuration
In centos I just had to install it via yum install mod_ssl
The 403 error may also be caused by an encrypted file system, e.g. a symlink to an encrypted home folder.
If your symlink points into the encrypted folder, the apache user (e.g. www-data) cannot access the contents, even if apache and file/folder permissions are set correctly. Access of the www-data user can be tested with such a call:
sudo -u www-data ls -l /var/www/html/<your symlink>/
There are workarounds/solutions to this, e.g. adding the www-data user to your private group (exposes the encrypted data to the web user) or by setting up an unencrypted rsynced folder (probably rather secure). I for myself will probably go for an rsync solution during development.
https://askubuntu.com/questions/633625/public-folder-in-an-encrypted-home-directory
A convenient tool for my purposes is lsyncd. This allows me to work directly in my encrypted home folder and being able to see changes almost instantly in the apache web page. The synchronization is triggered by changes in the file system, calling an rsync. As I'm only working on rather small web pages and scripts, the syncing is very fast. I decided to use a short delay of 1 second before the rsync is started, even though it is possible to set a delay of 0 seconds.
Installing lsyncd (in Ubuntu):
sudo apt-get install lsyncd
Starting the background service:
lsyncd -delay 1 -rsync /home/<me>/<work folder>/ /var/www/html/<web folder>/
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.
You can also use RedirectMatch directive to deny access to a folder.
To deny access to a folder, you can use the following RedirectMatch in htaccess :
RedirectMatch 403 ^/folder/?$
This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.
To deny access to everything inside the folder, You can use this :
RedirectMatch 403 ^/folder/.*$
This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.
Edit: note that this answer is 3+ years old. For newer versions of apache, please see the answer by sp00n. Leaving this answer for users of older versions of apache.
For debugging mod_rewrite issues, you'll want to use RewriteLogLevel and RewriteLog:
RewriteLogLevel 3
RewriteLog "/usr/local/var/apache/logs/rewrite.log"
If you need apache Listen port other than 80, you should add next file under ubuntu
"/etc/apache2/ports.conf"
the list of Listen ports
Listen 80
Listen 81
Listen 82
After you have to go on your Virtual hosts conf file and define next
<VirtualHost *:80>
#...v host 1
</VirtualHost>
<VirtualHost *:81>
#...host 2
</VirtualHost>
<VirtualHost *:82>
#...host 3
</VirtualHost>
I had the same problem - solved it by setting display_errors = On
in both php.ini
files.
/etc/php5/apache2/php.ini
/etc/php5/cli/php.ini
Then restarting Apache:
sudo /etc/init.d/apache2 restart
Hope this helps.
Minor thing: (Optional)
Try restarting your Apache after updating the rewrite engine status in vhosts as
Rewrite ON
.
One critical thing to notice:
In Apache vhosts file, check whether you have this script line
AllowOverride None
If yes, please remove/comment this line.
My vhosts file script: (Before)
<VirtualHost *:80>
DocumentRoot "/path/to/workspace"
ServerName ciproject
ErrorLog "/path/to/workspace/error.log"
CustomLog "/path/to/workspace/access.log" common
Directory "/path/to/workspace">
Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
My vhosts file script: (After)
<VirtualHost *:80>
DocumentRoot "/path/to/workspace"
ServerName ciproject
ErrorLog "/path/to/workspace/error.log"
CustomLog "/path/to/workspace/access.log" common
Directory "/path/to/workspace">
Options Indexes FollowSymLinks
#AllowOverride None
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
I faced the same problem, struggled for around 1 day, all were fine. Later, by trial and error method, found this thing. After removing this, my job was accomplished. The URL now does not look up for index.php :)
Beside missing Order
and Allow
directives mentioned in other answers be aware that a non-matching regular expression of a DirectoryMatch
directive may also cause this error.
If the requested path is /home/user-foo1bar/www/myproject/
the folloing matcher won't match
<DirectoryMatch "/home/user-[a-z]+/www/myproject/">
...
</DirectoryMatch>
thus, even a valid access configuration might cause this error.
Sadly, mod_evasive
won't work as expected when used in non-prefork configurations (recent apache setups are mainly MPM)
On XAMPP use
D:\xampp\apache\bin>httpd -t -D DUMP_VHOSTS
This will yield errors in your configuration of the virtual hosts
You can also type "top" and look at the list of running processes.
In Apache 2.4, the authorization configuration syntax has changed, and the Order
, Deny
or Allow
directives should no longer be used.
The new way to do this would be:
<VirtualHost *:8080>
<Location />
Require ip 192.168.1.0
</Location>
...
</VirtualHost>
Further examples using the new syntax can be found in the Apache documentation: Upgrading to 2.4 from 2.2
Yes with Virtual Host you can have as many parallel programs as you want:
Open
/etc/httpd/conf/httpd.conf
Listen 81
Listen 82
Listen 83
<VirtualHost *:81>
ServerAdmin [email protected]
DocumentRoot /var/www/site1/html
ServerName site1.com
ErrorLog logs/site1-error_log
CustomLog logs/site1-access_log common
ScriptAlias /cgi-bin/ "/var/www/site1/cgi-bin/"
</VirtualHost>
<VirtualHost *:82>
ServerAdmin [email protected]
DocumentRoot /var/www/site2/html
ServerName site2.com
ErrorLog logs/site2-error_log
CustomLog logs/site2-access_log common
ScriptAlias /cgi-bin/ "/var/www/site2/cgi-bin/"
</VirtualHost>
<VirtualHost *:83>
ServerAdmin [email protected]
DocumentRoot /var/www/site3/html
ServerName site3.com
ErrorLog logs/site3-error_log
CustomLog logs/site3-access_log common
ScriptAlias /cgi-bin/ "/var/www/site3/cgi-bin/"
</VirtualHost>
Restart apache
service httpd restart
You can now refer Site1 :
http://<ip-address>:81/
http://<ip-address>:81/cgi-bin/
Site2 :
http://<ip-address>:82/
http://<ip-address>:82/cgi-bin/
Site3 :
http://<ip-address>:83/
http://<ip-address>:83/cgi-bin/
If path is not hardcoded in any script then your websites should work seamlessly.
.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.
What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.
Me also coming the same problem. The solution is goto add or remove programes then click the turn windows features on or off. Turn off the IIS. That is turn off the 'Internet information services' and 'Internet information service removable web core'. I chosed the remaining features are on. Computer will ask to restart the system. Restart ur computer and then install the apache http server. I got it. Server succesfully working...
If you are using windows, remove comment on these lines and set them as:
Line 227 : ServerName 127.0.0.1:80
Line 235 : AllowOverride all
Line 236 : Require all granted
Worked for me!
as mentioned by Uberfuzzy [ real cause of problem ]
If you look at the PHP constant [PATH_SEPARATOR][1], you will see it being ":" for you.
If you break apart your string ".:/usr/share/pear:/usr/share/php" using that character, you will get 3 parts
Any attempts to include()/require() things, will look in these directories, in this order.
It is showing you that in the error message to let you know where it could NOT find the file you were trying to require()
That was the cause of error.
Now coming to solution
php --ini
( in my case : /etc/php5/cli/php.ini
)include_path
in vi using esc
then press /include_path
then enter
include_path = ".:/usr/share/php:/var/www/<directory>/"
sudo service apache2 restart
This is it. Hope it helps.
The user owner for me is the admin user and the group is _www and works with permissions set to 775 for dir and for files 664
openssl x509 -outform der -in your-cert.pem -out your-cert.crt
Late answer here, but if you search /etc/init.d/apache2
for 'reload', you'll find something like this:
do_reload() {
if apache_conftest; then
if ! pidofproc -p $PIDFILE "$DAEMON" > /dev/null 2>&1 ; then
APACHE2_INIT_MESSAGE="Apache2 is not running"
return 2
fi
$APACHE2CTL graceful > /dev/null 2>&1
return $?
else
APACHE2_INIT_MESSAGE="The apache2$DIR_SUFFIX configtest failed. Not doing anything."
return 2
fi
}
Basically, what the answers that suggest using init.d, systemctl, etc are invoking is a thin wrapper that says:
apachectl graceful
(swallowing the output, and forwarding the exit code)This suggests that @Aruman's answer is also correct, provided you are confident there are no errors in your configuration or have already run apachctl configtest
manually.
The apache documentation also supplies the same command for a graceful restart (apachectl -k graceful
), and some more color on the behavior thereof.
Ubuntu 10.04 comes with the Suhosin patch only, which does not give you configuration options. But you can install php5-suhosin to solve this:
apt-get update
apt-get install php5-suhosin
Now you can edit /etc/php5/conf.d/suhosin.ini and set:
suhosin.memory_limit = 1G
Then using ini_set will work in a script:
ini_set('memory_limit', '256M');
I realise that's not the case here but it might help someone.
Double-check you didn't create the conf file in /etc/apache2/sites-enabled by mistake. You get the same error.
Bootstrap 4 removed .btn-group-justified. As a replacement you can use <div class="btn-group d-flex" role="group"></div>
as a wrapper around elements with .w-100.
Try this:
<div class="btn-group d-flex" role="group>
<button type="button" class="btn btn-primary w-100">Submit</button>
<button type="button" class="btn btn-primary w-100">Cancel</button>
</div>
Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()
$.each(json, function (key, data) {
console.log(key)
$.each(data, function (index, data) {
console.log('index', data)
})
})
Demo: Fiddle
Although this is an old thread, I got this error as well and the solution that worked for me is not mentioned here.
Simply put, in my case the webcam was still in use on the background, as I saw the LED light being on. I have not yet been able to reproduce the issue, so I'm not sure a simple cv2.VideoCapture(0).release()
would have solved it. I'll edit this post if and when I have found it out.
For me a restart of my PC solved the issue, without changing anything to the code.
custom validation step by step
Html template
<form [ngFormModel]="demoForm">
<input
name="NotAllowSpecialCharacters"
type="text"
#demo="ngForm"
[ngFormControl] ="demoForm.controls['spec']"
>
<div class='error' *ngIf="demo.control.touched">
<div *ngIf="demo.control.hasError('required')"> field is required.</div>
<div *ngIf="demo.control.hasError('invalidChar')">Special Characters are not Allowed</div>
</div>
</form>
Component App.ts
import {Control, ControlGroup, FormBuilder, Validators, NgForm, NgClass} from 'angular2/common';
import {CustomValidator} from '../../yourServices/validatorService';
under class define
demoForm: ControlGroup;
constructor( @Inject(FormBuilder) private Fb: FormBuilder ) {
this.demoForm = Fb.group({
spec: new Control('', Validators.compose([Validators.required, CustomValidator.specialCharValidator])),
})
}
under {../../yourServices/validatorService.ts}
export class CustomValidator {
static specialCharValidator(control: Control): { [key: string]: any } {
if (control.value) {
if (!control.value.match(/[-!$%^&*()_+|~=`{}\[\]:";#@'<>?,.\/]/)) {
return null;
}
else {
return { 'invalidChar': true };
}
}
}
}
As a memory fragmentation solution. I was getting out of memory exceptions while writing a lot of data into a memory stream (reading from a network stream). The data was written in 8K chunks. After reaching 128M there was exception even though there was a lot of memory available (but it was fragmented). Calling GC.Collect() solved the issue. I was able to handle over 1G after the fix.
Similar to above, using filter
from dplyr
:
filter(df, fct %in% vc)
For the purpose of encoding javascript has given three inbuilt functions -
escape()
- does not encode @*/+
This method is deprecated after the ECMA 3 so it should be avoided.
encodeURI()
- does not encode ~!@#$&*()=:/,;?+'
It assumes that the URI is a complete URI, so does not encode reserved characters that have special meaning in the URI.
This method is used when the intent is to convert the complete URL instead of some special segment of URL.
Example - encodeURI('http://stackoverflow.com');
will give - http://stackoverflow.com
encodeURIComponent()
- does not encode - _ . ! ~ * ' ( )
This function encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character. This method should be used to convert a component of URL. For instance some user input needs to be appended
Example - encodeURIComponent('http://stackoverflow.com');
will give - http%3A%2F%2Fstackoverflow.com
All this encoding is performed in UTF 8 i.e the characters will be converted in UTF-8 format.
encodeURIComponent differ from encodeURI in that it encode reserved characters and Number sign # of encodeURI
For Nginx (without apache) and PHP 7.2, installing php7.2-xml wasn't enough. Had to install php7.2-simplexml package to get it to work
So the commands for debian/ubuntu, update packages and install both packages
apt update
apt install php7.2-xml php7.2-simplexml
And restart both Nginx and php
systemctl restart nginx php7.2-fpm
Here is template of sort_values according to pandas documentation.
DataFrame.sort_values(by, axis=0,
ascending=True,
inplace=False,
kind='quicksort',
na_position='last',
ignore_index=False, key=None)[source]
In this case it will be like this.
df.sort_values(by=['2'])
API Reference pandas.DataFrame.sort_values
For purposes such as this, I tend to use strtok_r() instead of strtok().
For example ...
int main (void) {
char str[128];
char *ptr;
strcpy (str, "123456 789asdf");
strtok_r (str, " ", &ptr);
printf ("'%s' '%s'\n", str, ptr);
return 0;
}
This will output ...
'123456' '789asdf'
If more delimiters are needed, then loop.
Hope this helps.
The WPF Font Cache service shares font data between WPF applications. The first WPF application you run starts this service if the service is not already running. If you are using Windows Vista, you can set the "Windows Presentation Foundation (WPF) Font Cache 3.0.0.0" service from "Manual" (the default) to "Automatic (Delayed Start)" to reduce the initial start-up time of WPF applications.
There's no harm in disabling it, but WPF apps tend to start faster and load fonts faster with it running.
It is supposed to be a performance optimization. The fact that it is not in your case makes me suspect that perhaps your font cache is corrupted. To clear it, follow these steps:
C:\Documents and Settings\LocalService\Local Settings\Application Data\
folder.In Angular you can define event listeners
like in the example below:
<!-- Here you can call public methods from parental component -->
<input (change)="method_name()">
I worked out the following script for get table schema.
'CREATE TABLE ' || 'yourschema.yourtable' || E'\n(\n' ||
array_to_string(
array_agg(
' ' || column_expr
)
, E',\n'
) || E'\n);\n'
from
(
SELECT ' ' || column_name || ' ' || data_type ||
coalesce('(' || character_maximum_length || ')', '') ||
case when is_nullable = 'YES' then ' NULL' else ' NOT NULL' end as column_expr
FROM information_schema.columns
WHERE table_schema || '.' || table_name = 'yourschema.yourtable'
ORDER BY ordinal_position
) column_list;
If, like me, you find you want essentially the same sorting code in more than one place, or just want to keep the code complexity down, you can abstract away the sorting itself to a separate function, to which you pass the function that does the actual work you want (which would be different at each call site, of course).
Given a map with key type K
and value type V
, represented as <K>
and <V>
below, the common sort function might look something like this Go-code template (which Go version 1 does not support as-is):
/* Go apparently doesn't support/allow 'interface{}' as the value (or
/* key) of a map such that any arbitrary type can be substituted at
/* run time, so several of these nearly-identical functions might be
/* needed for different key/value type combinations. */
func sortedMap<K><T>(m map[<K>]<V>, f func(k <K>, v <V>)) {
var keys []<K>
for k, _ := range m {
keys = append(keys, k)
}
sort.Strings(keys) # or sort.Ints(keys), sort.Sort(...), etc., per <K>
for _, k := range keys {
v := m[k]
f(k, v)
}
}
Then call it with the input map and a function (taking (k <K>, v <V>)
as its input arguments) that is called over the map elements in sorted-key order.
So, a version of the code in the answer posted by Mingu might look like:
package main
import (
"fmt"
"sort"
)
func sortedMapIntString(m map[int]string, f func(k int, v string)) {
var keys []int
for k, _ := range m {
keys = append(keys, k)
}
sort.Ints(keys)
for _, k := range keys {
f(k, m[k])
}
}
func main() {
// Create a map for processing
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"
sortedMapIntString(m,
func(k int, v string) { fmt.Println("Key:", k, "Value:", v) })
}
The sortedMapIntString()
function can be re-used for any map[int]string
(assuming the same sort order is desired), keeping each use to just two lines of code.
Downsides include:
Other languages have various solutions:
<K>
and <V>
(to denote types for the key and value) looks a bit familiar, that code template is not terribly unlike C++ templates.range
a first-class type such that it could be substituted with a custom ordered-range
(in place of range
in the original code), I think some other languages provide iterators that are powerful enough to accomplish the same thing.//call Facebook onclick on your customized button on click by the following
FacebookSdk.sdkInitialize(this.getApplicationContext());
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d("Success", "Login");
}
@Override
public void onCancel() {
Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_LONG).show();
}
@Override
public void onError(FacebookException exception) {
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
});
setContentView(R.layout.activity_main);
Button mycustomizeedbutton=(Button)findViewById(R.id.mycustomizeedbutton);
mycustomizeedbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "user_friends"));
}
});
}
Webview in Activity,Below code worked for me , Finish the activity the after load the Url in webview.in onbackpressed it go to the previous activity
webView = (WebView) findViewById(R.id.info_webView);
webView.loadUrl(value);
finish();
I think this is an excellent article on explaining the differences and when you should use one over the other: http://tag1consulting.com/MySQL_Engines_MyISAM_vs_InnoDB
Full description how to use resources: WPF Application Resource, Content, and Data Files
And how to reference them, read "Pack URIs in WPF".
In short, there is even means to reference resources from referenced/referencing assemblies.
This will definitely work for you...
ArrayList<String> list = new ArrayList<String>();
list.add(textview.getText().toString());
list.add("B");
list.add("C");
I got the following error when using strict mode:
Node error: "Octal literals are not allowed in strict mode."
The following solution works (source):
process.stdout.write("received: " + bytesReceived + "\x1B[0G");
If you define table type as InnoDB, you can use transactions. You will need set AUTOCOMMIT=0
, and after you can issue COMMIT
or ROLLBACK
at the end of query or session to submit or cancel a transaction.
ROLLBACK -- will undo the changes that you have made
You may have not set the output file.
As of MySQL 8.0.18 This works fine for me
mysql> SET PASSWORD FOR 'user'@'localhost' = 'userpassword';
_x000D_
After my previous answer disaster, I'm going to try something else.
List<Model> usrList =
(list.Where(n => n.application == "applicationame").ToList());
usrList.ForEach(n => n.users.RemoveAll(n => n.surname != "surname"));
Just came across this new tool in hacker news.
From their page - "Nuitka is a good replacement for the Python interpreter and compiles every construct that CPython 2.6, 2.7, 3.2 and 3.3 offer. It translates the Python into a C++ program that then uses "libpython" to execute in the same way as CPython does, in a very compatible way."
styles.xml
<style name="CircularProgress" parent="Theme.AppCompat.Light">
<item name="colorAccent">@color/yellow</item>
</style>
<ProgressBar
android:layout_width="@dimen/d_40"
android:layout_height="@dimen/d_40"
android:indeterminate="true"
style="@style/Widget.AppCompat.ProgressBar"
android:theme="@style/CircularProgress"/>
As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code a little bit later on the same thread, I use this:
new android.os.Handler(Looper.getMainLooper()).postDelayed(
new Runnable() {
public void run() {
Log.i("tag", "This'll run 300 milliseconds later");
}
},
300);
.. this is pretty much equivalent to
setTimeout(
function() {
console.log("This will run 300 milliseconds later");
},
300);
I find marking the property
as readonly
cleaner than the above answers. I believe vb14 is required.
Private _Name As String
Public ReadOnly Property Name() As String
Get
Return _Name
End Get
End Property
This can be condensed to
Public ReadOnly Property Name As String
https://msdn.microsoft.com/en-us/library/dd293589.aspx?f=255&MSPPError=-2147217396
I don't have enough reputation to comment on any answer. In one of the comments, someone has asked how to ignore the hidden folders in the list. Below is how you can do this.
dir /b /AD-H
On Ubuntu 14.04 (Trusty Tahr) with Docker 1.9.1, I just uncommented the http_proxy
line, updated the value and then restarted the Docker service.
export http_proxy="http://proxy.server.com:80"
and then
service docker restart
There is a refinement of powerset:
def powerset(seq):
"""
Returns all the subsets of this set. This is a generator.
"""
if len(seq) <= 0:
yield []
else:
for item in powerset(seq[1:]):
yield [seq[0]]+item
yield item
Here is a simple code:
ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton(bean.getClass().getCanonicalName(), bean);
You need a click listener which calls addActivityItem
if less than 2 options exist:
var activities = document.getElementById("activitySelector");
activities.addEventListener("click", function() {
var options = activities.querySelectorAll("option");
var count = options.length;
if(typeof(count) === "undefined" || count < 2)
{
addActivityItem();
}
});
activities.addEventListener("change", function() {
if(activities.value == "addNew")
{
addActivityItem();
}
});
function addActivityItem() {
// ... Code to add item here
}
A live demo is here on JSfiddle.
I guess you will get ORA-01741: illegal zero-length identifier if you use the following
SELECT "" AS Contact FROM Customers;
And if you use the following 2 statements, you will be getting the same null value populated in the column.
SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;
If it's in a class, you can use getattr:
class MyClass(object):
def install(self):
print "In install"
method_name = 'install' # set by the command line options
my_cls = MyClass()
method = None
try:
method = getattr(my_cls, method_name)
except AttributeError:
raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))
method()
or if it's a function:
def install():
print "In install"
method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise NotImplementedError("Method %s not implemented" % method_name)
method()
I had the same requirement - I just use this. User enters the number of days by which he/she wants to limit the calendar range to.
SELECT DAY, offset
FROM (SELECT to_char(SYSDATE, 'DD-MON-YYYY') AS DAY, 0 AS offset
FROM DUAL
UNION ALL
SELECT to_char(SYSDATE - rownum, 'DD-MON-YYYY'), rownum
FROM all_objects d)
where offset <= &No_of_days
I use the above result set as driving view in LEFT OUTER JOIN
with other views involving tables which have dates.
You'll probably have to be more verbose here
name = "Blue Jeans"
model = Product.where('lower(name) = ?', name.downcase).first
model ||= Product.create(:name => name)
For the record, that margin and padding resetting didn't do the trick for me, but this quote from one of the comments above turned out to be crucial and solved the issue for me: "If i put the divs on the same line it margin disappears."
If you have a fixed div
just absolute position it at 50% from the top and 50% left and negative margin top and left of half the height and width respectively. Adjust to your needs:
div {
position: absolute;
top: 50%;
left: 50%;
width: 500px;
height: 300px;
margin-left: -250px;
margin-top: -150px;
}
template<typename T>
string str(T begin, T end)
{
stringstream ss;
bool first = true;
for (; begin != end; begin++)
{
if (!first)
ss << ", ";
ss << *begin;
first = false;
}
return ss.str();
}
This is the str function that can make integers turn into a string and not into a char for what the integer represents. Also works for doubles.
It's downloaded probably because there is not Adobe Reader plug-in installed. In this case, IE (it doesn't matter which version) doesn't know how to render it, and it'll simply download the file (Chrome, for example, has its own embedded PDF renderer).
That said. <iframe>
is not best way to display a PDF (do not forget compatibility with mobile browsers, for example Safari). Some browsers will always open that file inside an external application (or in another browser window). Best and most compatible way I found is a little bit tricky but works on all browsers I tried (even pretty outdated):
Keep your <iframe>
but do not display a PDF inside it, it'll be filled with an HTML page that consists of an <object>
tag. Create an HTML wrapping page for your PDF, it should look like this:
<html>
<body>
<object data="your_url_to_pdf" type="application/pdf">
<embed src="your_url_to_pdf" type="application/pdf" />
</object>
</body>
</html>
Of course, you still need the appropriate plug-in installed in the browser. Also, look at this post if you need to support Safari on mobile devices.
1st. Why nesting <embed>
inside <object>
? You'll find the answer here on SO. Instead of a nested <embed>
tag, you may (should!) provide a custom message for your users (or a built-in viewer, see next paragraph). Nowadays, <object>
can be used without worries, and <embed>
is useless.
2nd. Why an HTML page? So you can provide a fallback if PDF viewer isn't supported. Internal viewer, plain HTML error messages/options, and so on...
It's tricky to check PDF support so that you may provide an alternate viewer for your customers, take a look at PDF.JS project; it's pretty good but rendering quality - for desktop browsers - isn't as good as a native PDF renderer (I didn't see any difference in mobile browsers because of screen size, I suppose).
Change:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
To:
<!-- ANT4X -->
<dependency>
<groupId>net.sourceforge.ant4x</groupId>
<artifactId>ant4x</artifactId>
<version>${net.sourceforge.ant4x-version}</version>
<scope>provided</scope>
</dependency>
The groupId
of net.sourceforge
was incorrect. The correct value is net.sourceforge.ant4x
.
Internet Explorer is the only browser which really suffers from this in today's world. (Versions 5, 6, and 7 were dog slow. 8 does not show the same degradation.) What's more, IE gets slower and slower the longer your string is.
If you have long strings to concatenate then definitely use an array.join technique. (Or some StringBuffer wrapper around this, for readability.) But if your strings are short don't bother.
<View
style={{
flexDirection: 'row',
padding: 10,
}}
>
<Text numberOfLines={5} style={{flex:1}}>
This is a very long text that will overflow on a small device This is a very
long text that will overflow on a small deviceThis is a very long text that
will overflow on a small deviceThis is a very long text that will overflow
on a small device
</Text>
</View>
Or you could do this:
inside_git_repo="$(git rev-parse --is-inside-work-tree 2>/dev/null)"
if [ "$inside_git_repo" ]; then
echo "inside git repo"
else
echo "not in git repo"
fi
This is a very old question - but still for reference if others are looking at it - requestAnimationFrame()
is the right way to handle animation in modern browsers:
UPDATE: The mozilla link shows how to do this - I didn't feel like repeating the text behind the link ;)
If you open your module settings (F4) you can nominate which paths contain 'source'. Intellij will then mark these directories in blue and allow you to add classes etc.
In a similar fashion you can highlight test directories for unit tests.
import os
def fs_tree_to_dict(path_):
file_token = ''
for root, dirs, files in os.walk(path_):
tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs}
tree.update({f: file_token for f in files})
return tree # note we discontinue iteration trough os.walk
If anybody is interested - that recursive function returns nested structure of dictionaries. Keys are file system
names (of directories and files), values are either:
file_token
)The strings designating files are empty in this example. They can also be e.g. given file contents or its owner info or privileges or whatever object different than a dict. Unless it's a dictionary it can be easily distinguished from a "directory type" in further operations.
Having such a tree in a filesystem:
# bash:
$ tree /tmp/ex
/tmp/ex
+-- d_a
¦ +-- d_a_a
¦ +-- d_a_b
¦ ¦ +-- f1.txt
¦ +-- d_a_c
¦ +-- fa.txt
+-- d_b
¦ +-- fb1.txt
¦ +-- fb2.txt
+-- d_c
The result will be:
# python 2 or 3:
>>> fs_tree_to_dict("/tmp/ex")
{
'd_a': {
'd_a_a': {},
'd_a_b': {
'f1.txt': ''
},
'd_a_c': {},
'fa.txt': ''
},
'd_b': {
'fb1.txt': '',
'fb2.txt': ''
},
'd_c': {}
}
If you like that, I've already created a package (python 2 & 3) with this stuff (and a nice pyfakefs
helper):
https://pypi.org/project/fsforge/
Another nice way to deal with JSON data is using the JQuery getJSON function. You can call the
public ActionResult SomeActionMethod(int id)
{
return Json(new {foo="bar", baz="Blech"});
}
Method from the jquery getJSON method by simply...
$.getJSON("../SomeActionMethod", { id: someId },
function(data) {
alert(data.foo);
alert(data.baz);
}
);
The solutions here are old and now deprecated: https://github.com/uuidjs/uuid#deep-requires-now-deprecated
Use this:
npm install uuid
//add these lines to your code
const { v4: uuidv4 } = require('uuid');
var your_uuid = uuidv4();
console.log(your_uuid);
http://localhost:80
type above line in your browser you realize IIS installed or not
Check with starting mysql in terminal. Use below command
mysql-ctl start
In my case its worked
If value is 9999.988 and Precision 4, scale 2 then it means 9999(it represents precision).99(scale is 2 so .988 is rounded to .99)
If value is 9999.9887 and precision is 4, scale is 2 then it means 9999.99
If this is just plain vanilla C, then:
strcpy(buffer, text.c_str());
Assuming that buffer is allocated and large enough to hold the contents of 'text', which is the assumption in your original code.
If encrypt() takes a 'const char *' then you can use
encrypt(text.c_str())
and you do not need to copy the string.
I am using mysql 5.5.24 and the following code works:
select * from (
SELECT `users`.`first_name`, `users`.`last_name`, `users`.`email`,
SUBSTRING(`locations`.`raw`,-6,4) AS `guaranteed_postcode`
FROM `users` LEFT OUTER JOIN `locations`
ON `users`.`id` = `locations`.`user_id`
) as a
WHERE guaranteed_postcode NOT IN --this is where the fake col is being used
(
SELECT `postcode` FROM `postcodes` WHERE `region` IN
(
'australia'
)
)
You could run your JUnit test from a main method and repeat it so many times you need:
package tests;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.Result;
public class RepeatedTest {
@Test
public void test() {
fail("Not yet implemented");
}
public static void main(String args[]) {
boolean runForever = true;
while (runForever) {
Result result = org.junit.runner.JUnitCore.runClasses(RepeatedTest.class);
if (result.getFailureCount() > 0) {
runForever = false;
//Do something with the result object
}
}
}
}
I think you should give the data types of the column as NUMERIC or DOUBLE or FLOAT or REAL
Read http://sqlite.org/datatype3.html to more info.
function array_unique(nav_array) {
nav_array = nav_array.sort(function (a, b) { return a*1 - b*1; });
var ret = [nav_array[0]];
// Start loop at 1 as element 0 can never be a duplicate
for (var i = 1; i < nav_array.length; i++) {
if (nav_array[i-1] !== nav_array[i]) {
ret.push(nav_array[i]);
}
}
return ret;
}
I have noticed that when using type="image/vnd.microsoft.icon"
, the favicon fails to appear when the browser is not connected to the internet.
But type="image/x-icon"
works whether the browser can connect to the internet, or not.
When developing, at times I am not connected to the internet.
In your Installer class, add a handler for the AfterInstall event. You can then call the ServiceController in the event handler to start the service.
using System.ServiceProcess;
public ServiceInstaller()
{
//... Installer code here
this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
}
void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
ServiceInstaller serviceInstaller = (ServiceInstaller)sender;
using (ServiceController sc = new ServiceController(serviceInstaller.ServiceName))
{
sc.Start();
}
}
Now when you run InstallUtil on your installer, it will install and then start up the service automatically.
The ssh2 functions aren't very good. Hard to use and harder yet to install, using them will guarantee that your code has zero portability. My recommendation would be to use phpseclib, a pure PHP SFTP implementation.
These are all good answers, however many forget to close the cursor and database. If you don't close the cursor or database you may run in to memory leaks.
Additionally:
You can get an error when searching by String
that contains non alpha/numeric characters. For example: "1a5f9ea3-ec4b-406b-a567-e6927640db40
". Those dashes (-
) will cause an unrecognized token
error. You can overcome this by putting the string in an array. So make it a habit to query like this:
public boolean hasObject(String id) {
SQLiteDatabase db = getWritableDatabase();
String selectString = "SELECT * FROM " + _TABLE + " WHERE " + _ID + " =?";
// Add the String you are searching by here.
// Put it in an array to avoid an unrecognized token error
Cursor cursor = db.rawQuery(selectString, new String[] {id});
boolean hasObject = false;
if(cursor.moveToFirst()){
hasObject = true;
//region if you had multiple records to check for, use this region.
int count = 0;
while(cursor.moveToNext()){
count++;
}
//here, count is records found
Log.d(TAG, String.format("%d records found", count));
//endregion
}
cursor.close(); // Dont forget to close your cursor
db.close(); //AND your Database!
return hasObject;
}
The setting was disabled in Jupyter 5.X
and higher by adding below code
pylab = Unicode('disabled', config=True,
help=_("""
DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
""")
)
@observe('pylab')
def _update_pylab(self, change):
"""when --pylab is specified, display a warning and exit"""
if change['new'] != 'warn':
backend = ' %s' % change['new']
else:
backend = ''
self.log.error(_("Support for specifying --pylab on the command line has been removed."))
self.log.error(
_("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(backend)
)
self.exit(1)
And in previous versions it has majorly been a warning. But this not a big issue because Jupyter uses concepts of kernels
and you can find kernel for your project by running below command
$ jupyter kernelspec list
Available kernels:
python3 /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3
This gives me the path to the kernel folder. Now if I open the /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json
file, I see something like below
{
"argv": [
"python",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}",
],
"display_name": "Python 3",
"language": "python"
}
So you can see what command is executed to launch the kernel. So if you run the below command
$ python -m ipykernel_launcher --help
IPython: an enhanced interactive Python shell.
Subcommands
-----------
Subcommands are launched as `ipython-kernel cmd [args]`. For information on
using subcommand 'cmd', do: `ipython-kernel cmd -h`.
install
Install the IPython kernel
Options
-------
Arguments that take values are actually convenience aliases to full
Configurables, whose aliases are listed on the help line. For more information
on full configurables, see '--help-all'.
....
--pylab=<CaselessStrEnum> (InteractiveShellApp.pylab)
Default: None
Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
Pre-load matplotlib and numpy for interactive use, selecting a particular
matplotlib backend and loop integration.
--matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
Default: None
Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
Configure matplotlib for interactive use with the default matplotlib
backend.
...
To see all available configurables, use `--help-all`
So now if we update our kernel.json
file to
{
"argv": [
"python",
"-m",
"ipykernel_launcher",
"-f",
"{connection_file}",
"--pylab",
"inline"
],
"display_name": "Python 3",
"language": "python"
}
And if I run jupyter notebook
the graphs are automatically inline
Note the below approach also still works, where you create a file on below path
~/.ipython/profile_default/ipython_kernel_config.py
c = get_config()
c.IPKernelApp.matplotlib = 'inline'
But the disadvantage of this approach is that this is a global impact on every environment using python. You can consider that as an advantage also if you want to have a common behaviour across environments with a single change.
So choose which approach you would like to use based on your requirement
git rev-list --all | (
while read revision; do
git grep -F 'password' $revision
done
)
Ok, this was asked 7 years ago, but I think the best solution here is to forego the new table entirely and just do this as a custom view. That way you're not duplicating data, there's no worry about unique data, and it doesn't touch the actual database structure. Something like this:
CREATE VIEW vw_competitions
AS
SELECT
Id int
CompetitionName nvarchar(75)
CompetitionType nvarchar(50)
OtherField1 int
OtherField2 nvarchar(64) --add the fields you want viewed from the Competition table
FROM Competitions
GO
Other items can be added here like joins on other tables, WHERE clauses, etc. This is most likely the most elegant solution to this problem, as you now can just query the view:
SELECT *
FROM vw_competitions
...and add any WHERE, IN, or EXISTS clauses to the view query.
You just have to change the structure of the if...else..endif
somewhat:
if exists(select * from Table where FieldValue='') then begin
select TableID from Table where FieldValue=''
end else begin
insert into Table (FieldValue) values ('')
select TableID from Table where TableID = scope_identity()
end
You could also do:
if not exists(select * from Table where FieldValue='') then begin
insert into Table (FieldValue) values ('')
end
select TableID from Table where FieldValue=''
Or:
if exists(select * from Table where FieldValue='') then begin
select TableID from Table where FieldValue=''
end else begin
insert into Table (FieldValue) values ('')
select scope_identity() as TableID
end
This can be done with standard java properties in combination with the maven-resource-plugin
with enabled filtering on properties.
For more info see http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html
This will work for standard maven project as for plugin projects
There are very good answers with detailed explanation to this post. I just would like to refer that there is another explanation with visual representation for the meaning of Frame, Bounds, Center, Transform, Bounds Origin in WWDC 2011 video Understanding UIKit Rendering starting from @4:22 till 20:10
I've bumped into this question because I actually wanted to define a default goal in pom.xml. You can define a default goal under build:
<build>
<defaultGoal>install</defaultGoal>
...
</build>
After that change, you can then simply run mvn
which will do exactly the same as mvn install
.
Note: I don't favor this as a default approach. My use case was to define a profile that downloaded a previous version of that project from Artifactory and wanted to tie that profile to a given phase. For convenience, I can run mvn -Pdownload-jar -Dversion=0.0.9
and don't need to specify a goal/phase there. I think it's reasonable to define a defaultGoal
in a profile which has a very specific function for a particular phase.
To follow-up on Charles Bailey's answer, here's my git setup that's using p4merge (free cross-platform 3way merge tool); tested on msys Git (Windows) install:
git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"'
or, from a windows cmd.exe shell, the second line becomes :
git config --global mergetool.p4merge.cmd "p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""
The changes (relative to Charles Bailey):
Download: http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools
EDIT (Feb 2014)
As pointed out by @Gregory Pakosz, latest msys git now "natively" supports p4merge (tested on 1.8.5.2.msysgit.0).
You can display list of supported tools by running:
git mergetool --tool-help
You should see p4merge in either available or valid list. If not, please update your git.
If p4merge was listed as available, it is in your PATH and you only have to set merge.tool:
git config --global merge.tool p4merge
If it was listed as valid, you have to define mergetool.p4merge.path in addition to merge.tool:
git config --global mergetool.p4merge.path c:/Users/my-login/AppData/Local/Perforce/p4merge.exe
~
should expand to current user's home directory (so in theory the path should be ~/AppData/Local/Perforce/p4merge.exe
), this did not work for me$LOCALAPPDATA/Perforce/p4merge.exe
), git does not seem to be expanding environment variables for paths (if you know how to get this working, please let me know or update this answer)To get the width and height of the viewport:
var viewportWidth = $(window).width();
var viewportHeight = $(window).height();
resize event of the page:
$(window).resize(function() {
});
Your syntax is wrong:
string[] arr = new string[]{};
or
string[] arr = new string[0];
You are using the same Cast object for every entry. On each iteration you just changed the same object instead creating a new one.
This code should fix it:
JSONArray jCastArr = jObj.getJSONArray("abridged_cast");
ArrayList<Cast> castList= new ArrayList<Cast>();
for (int i=0; i < jCastArr.length(); i++) {
Cast person = new Cast(); // create a new object here
JSONObject jpersonObj = jCastArr.getJSONObject(i);
person.castId = (String) jpersonObj.getString("id");
person.castFullName = (String) jpersonObj.getString("name");
castList.add(person);
}
details.castList = castList;
use ng-intl-tel-input to validate mobile numbers for all countries. you can set default country also. on npm: https://www.npmjs.com/package/ng-intl-tel-input
more details: https://techpituwa.wordpress.com/2017/03/29/angular-js-phone-number-validation-with-ng-intl-tel-input/
I found up-to-date resources here: Microsoft | SQL Docs | Python SQL Driver
There are these two options explained including all the prerequisites needed and code examples: Python SQL driver - pyodbc (tested & working) Python SQL driver - pymssql
I faced the same problem but the solution that worked for me was:
HTML:
<header class="container-fluid">
...
</header>
<nav class="row">
<div class="navbar navbar-inverse navbar-static-top">
...
</div>
</nav>
JavaScript:
document.onscroll = function() {
if( $(window).scrollTop() > $('header').height() ) {
$('nav > div.navbar').removeClass('navbar-static-top').addClass('navbar-fixed-top');
}
else {
$('nav > div.navbar').removeClass('navbar-fixed-top').addClass('navbar-static-top');
}
};
Where header
was the banner tag above my navigation bar
$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);
Note: only work for your example.
Put a z-indez
of -1
on your absolute (or relative) positioned element.
This will pull it out of the stacking context. (I think.) Read more wonderful things about "stacking contexts" here: https://philipwalton.com/articles/what-no-one-told-you-about-z-index/
Intent.FLAG_ACTIVITY_FORWARD_RESULT?
If set and this intent is being used to launch a new activity from an existing one, then the reply target of the existing activity will be transfered to the new activity.
If you know the values at compile time you can do :
float[] values = {0.1f, 0.2f, 0.3f};
There is no way to do that if values are variables in runtime.
If You are using rvm, then try the following command:
rvmsudo gem install bundler
According to another question: Could not find rails (>= 0) amongst [] (Gem::LoadError)
Hope it helped, Cheers
I think you may want to introduce some helper functions to build
your button as well as a Stateful widget along with some property to key off of.
isButtonDisabled
)onPressed
value to either null
or some function onPressed: () {}
isButtonDisabled
as part of this conditional and return either null
or some function.setState(() => isButtonDisabled = true)
to flip the conditional variable.build()
method again with the new state and the button will be rendered with a null
press handler and be disabled.Here's is some more context using the Flutter counter project.
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool _isButtonDisabled;
@override
void initState() {
_isButtonDisabled = false;
}
void _incrementCounter() {
setState(() {
_isButtonDisabled = true;
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("The App"),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
_buildCounterButton(),
],
),
),
);
}
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _isButtonDisabled ? null : _incrementCounter,
);
}
}
In this example I am using an inline ternary to conditionally set the Text
and onPressed
, but it may be more appropriate for you to extract this into a function (you can use this same method to change the text of the button as well):
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _counterButtonPress(),
);
}
Function _counterButtonPress() {
if (_isButtonDisabled) {
return null;
} else {
return () {
// do anything else you may want to here
_incrementCounter();
};
}
}
The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).
The way I would actually do it is to use jQuery's .text()
.
In my case, I had a textbox that was attached to a datepicker. The only solution that worked for me was to handle it inside the onSelect event of the datepicker.
<input type="text" id="bookdate">
$("#bookdate").datepicker({
onSelect: function (selected) {
//handle change event here
}
});
Here's the steps to achieve this:
Download the sendmail.zip through this link
Open sendmail.ini and set the configuration as follows:
smtp_server=smtp.gmail.com
hostname=localhost
Access your email account. Click the Gear Tool > Settings > Forwarding and POP/IMAP > IMAP access. Click "Enable IMAP", then save your changes.
Run your WAMP Server. Enable ssl_module under Apache Module.
Next, enable php_openssl and php_sockets under PHP.
Open php.ini and configure it as the codes below. Basically, you just have to set the sendmail_path.
[mail function] ; For Win32 only. ; http://php.net/smtp ;SMTP = ; http://php.net/smtp-port ;smtp_port = 25 ; For Win32 only. ; http://php.net/sendmail-from ;sendmail_from = [email protected] ; For Unix only. You may supply arguments as well (default: "sendmail -t -i"). ; http://php.net/sendmail-path sendmail_path = "C:\wamp\sendmail\sendmail.exe -t -i"
I hope this will work for you..
The two common approaches are to submit the form to an invisible iframe, or to use a Flash control such as YUI Uploader. You could also use Java instead of Flash, but this has a narrower install base.
(Shame about the layout table in the first example)
Between for and while: while
does not need initialization nor update statement, so it may look better, more elegant; for
can have statements missing, one two or all, so it is the most flexible and obvious if you need initialization, looping condition and "update" before looping. If you need only loop condition (tested at the beginning of the loop) then while
is more elegant.
Between for/while and do-while: in do-while
the condition is evaluated at the end of the loop. More confortable if the loop must be executed at least once.
Use Lookupstage to decide whether to insert or update. Check this link for more info - http://beingoyen.blogspot.com/2010/03/ssis-how-to-update-instead-of-insert.html
Steps to do update:
Under Custom properties select SQLCOMMAND and insert update command ex:
UPDATE table1 SET col1 = ?, col2 = ? where id = ?
map columns in exact order from source to output as in update command
I know it's been a while, but just in case someone still needs it:
The JSON object I need to pass:
0:{CommunityId: 509, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}
1:{CommunityId: 510, ListingKey: "20281", Type: 10, Name: "", District: "", Description: "",…}
The Ajax code:
data: JSON.stringify(The-data-shows-above),
type: 'POST',
datatype: 'JSON',
contentType: "application/json; charset=utf-8"
And the PHP side:
json_decode(file_get_contents("php://input"));
It works for me, hope it can help!
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/activity_register_header"
android:minHeight="50dp"
android:orientation="vertical"
android:visibility="gone" />
Try This Code
Visibility works fine in this code
What you need is a quadrangle instead of a rotated rectangle.
RotatedRect
will give you incorrect results. Also you will need a perspective projection.
Basicly what must been done is:
I implemented a class Quadrangle
which takes care of contour to quadrangle conversion and will also transform it over the right perspective.
See a working implementation here: Java OpenCV deskewing a contour
Well, as colon is kind of special symbol, but is part of method signature, it is possible to exted the NSString
with category to add this non-idiomatic style of string concatenation:
[@"This " : @"feels " : @"almost like " : @"concatenation with operators"];
You can define as many colon separated arguments as you find useful... ;-)
For a good measure, I've also added concat:
with variable arguments that takes nil
terminated list of strings.
// NSString+Concatenation.h
#import <Foundation/Foundation.h>
@interface NSString (Concatenation)
- (NSString *):(NSString *)a;
- (NSString *):(NSString *)a :(NSString *)b;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c;
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d;
- (NSString *)concat:(NSString *)strings, ...;
@end
// NSString+Concatenation.m
#import "NSString+Concatenation.h"
@implementation NSString (Concatenation)
- (NSString *):(NSString *)a { return [self stringByAppendingString:a];}
- (NSString *):(NSString *)a :(NSString *)b { return [[self:a]:b];}
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c
{ return [[[self:a]:b]:c]; }
- (NSString *):(NSString *)a :(NSString *)b :(NSString *)c :(NSString *)d
{ return [[[[self:a]:b]:c]:d];}
- (NSString *)concat:(NSString *)strings, ...
{
va_list args;
va_start(args, strings);
NSString *s;
NSString *con = [self stringByAppendingString:strings];
while((s = va_arg(args, NSString *)))
con = [con stringByAppendingString:s];
va_end(args);
return con;
}
@end
// NSString+ConcatenationTest.h
#import <SenTestingKit/SenTestingKit.h>
#import "NSString+Concatenation.h"
@interface NSString_ConcatenationTest : SenTestCase
@end
// NSString+ConcatenationTest.m
#import "NSString+ConcatenationTest.h"
@implementation NSString_ConcatenationTest
- (void)testSimpleConcatenation
{
STAssertEqualObjects([@"a":@"b"], @"ab", nil);
STAssertEqualObjects([@"a":@"b":@"c"], @"abc", nil);
STAssertEqualObjects([@"a":@"b":@"c":@"d"], @"abcd", nil);
STAssertEqualObjects([@"a":@"b":@"c":@"d":@"e"], @"abcde", nil);
STAssertEqualObjects([@"this " : @"is " : @"string " : @"concatenation"],
@"this is string concatenation", nil);
}
- (void)testVarArgConcatenation
{
NSString *concatenation = [@"a" concat:@"b", nil];
STAssertEqualObjects(concatenation, @"ab", nil);
concatenation = [concatenation concat:@"c", @"d", concatenation, nil];
STAssertEqualObjects(concatenation, @"abcdab", nil);
}
update the 'name' attribute:
UPDATE test SET data=data||'{"name":"my-other-name"}' WHERE id = 1;
and if you wanted to remove for example the 'name' and 'tags' attributes:
UPDATE test SET data=data-'{"name","tags"}'::text[] WHERE id = 1;
Although the CONVERT thing works, you actually shouldn't use it. You should ask yourself why you are parsing string values in SQL-Server. If this is a one-time job where you are manually fixing some data you won't get that data another time, this is ok, but if any application is using this, you should change something. Best way would be to use the "date" data type. If this is user input, this is even worse. Then you should first do some checking in the client. If you really want to pass string values where SQL-Server expects a date, you can always use ISO format ('YYYYMMDD') and it should convert automatically.
$r = (array)json_decode($arr);
if(!is_array($r) || count($r) < 1) return false;
There is an open issue to only print this warning if there was actually something sanitized: https://github.com/angular/angular/pull/10272
I didn't read in detail when this warning is printed when nothing was sanitized.
Assign each div a class
. Then you can perform actions on all of them:
$(".divClass").hide();
So each button can do:
$(".divClass").hide()
$("#specificDiv").show();
You can make this more generic, and use the obvious convention - the button and the div with the same number in the id are related. So:
$(".button").click(function() {
var divId = "#div" + $(this).attr("id").replace("showdiv", "");
$(".divClass").hide();
$(divId).show();
}
Is there anything wrong with Nahuel Greco's solution aside from the compilation error?
If I change one line
// Compilation error
setsockopt(fd, SO_SNDTIMEO, &timeout, sizeof(timeout));
to
// Fixed?
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
then it seems to work as advertised - socket()
returns a timeout error.
Resulting code:
struct timeval timeout;
timeout.tv_sec = 7; // after 7 seconds connect() will timeout
timeout.tv_usec = 0;
setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
connect(...)
I'm not versed enough to know the tradeoffs are between a send timeout and a non-blocking socket, but I'm curious to learn.
Using jQuery:
$('#Button').click(function(){
$(this).addClass("active");
});
This way, you don't have to pollute your HTML markup with onclick
handlers.
You can use try...catch.
try {
for(int i=0; i<10; ++i) {
for(int j=0; j<10; ++j) {
if(i*j == 42)
throw 0; // this is something like "break 2"
}
}
}
catch(int e) {} // just do nothing
// just continue with other code
If you have to break out of several loops at once, it is often an exception anyways.
For anyone interested and using a newer rails and the Devise gem: Devise's "trackable" option includes a column for current/last_sign_in_ip in the users table.
To know the format string used by Excel without having to guess it: create an excel file, write a date in cell A1 and format it as you want. Then run the following lines:
FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);
Then copy-paste the resulting string, remove the backslashes (for example d/m/yy\ h\.mm;@
becomes d/m/yy h.mm;@
) and use it in the http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells code:
CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);
You're comparing the message with the empty string using ==
.
First, your comparison is wrong because the message will be null (and not the empty string).
Second, it's wrong because Objects must be compared with equals()
and not with ==
.
Third, it's wrong because you should avoid scriptlets in JSP, and use the JSP EL, the JSTL, and other custom tags instead:
<c:id test="${!empty message}">
<c:out value="${message}"/>
</c:if>
You'll need to use a static
readonly
list instead. And if you want the list to be immutable then you might want to consider using ReadOnlyCollection<T>
rather than List<T>
.
private static readonly ReadOnlyCollection<string> _metrics =
new ReadOnlyCollection<string>(new[]
{
SourceFile.LOC,
SourceFile.MCCABE,
SourceFile.NOM,
SourceFile.NOA,
SourceFile.FANOUT,
SourceFile.FANIN,
SourceFile.NOPAR,
SourceFile.NDC,
SourceFile.CALLS
});
public static ReadOnlyCollection<string> Metrics
{
get { return _metrics; }
}
To get upper case version of a string you can use str.upper
:
s = 'sdsd'
s.upper()
#=> 'SDSD'
On the other hand string.ascii_uppercase
is a string containing all ASCII letters in upper case:
import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Another different way to achieve the renaming or change the mappings for an index is to reindex using logstash. Here is a sample of the logstash 2.1 configuration:
input {
elasticsearch {
hosts => ["es01.example.com", "es02.example.com"]
index => "old-index-name"
size => 500
scroll => "5m"
}
}
filter {
mutate {
remove_field => [ "@version" ]
}
date {
"match" => [ "custom_timestamp", "MM/dd/YYYY HH:mm:ss" ]
target => "@timestamp"
}
}
output {
elasticsearch {
hosts => ["es01.example.com", "es02.example.com" ]
manage_template => false
index => "new-index-name"
}
}
All you need is -l
and --block-size
flags
Size of all files and directories under working directory (in MBs)
ls -l --block-size=M
Size of all files and directories under working directory (in GBs)
ls -l --block-size=G
Size of a specific file or directory
ls -l --block-size=M my_file.txt
ls -l --block-size=M my_dir/
ls --help
-l
use a long listing format
--block-size=SIZE
: scale sizes bySIZE
before printing them; e.g.,'--block-size=M'
prints sizes in units of 1,048,576 bytes; seeSIZE
format below
SIZE
is an integer and optional unit (example: 10M is 10*1024*1024). Units are K, M, G, T, P, E, Z, Y (powers of 1024) or KB, MB, ... (powers of 1000).
find . -size +10000k -exec ls -sd {} +
If your version of find
won't accept the +
notation (which acts rather like xargs
does), then you might use (GNU find
and xargs
, so find
probably supports +
anyway):
find . -size +10000k -print0 | xargs -0 ls -sd
or you might replace the +
with \;
(and live with the relative inefficiency of this), or you might live with problems caused by spaces in names and use the portable:
find . -size +10000k -print | xargs ls -sd
The -d
on the ls
commands ensures that if a directory is ever found (unlikely, but...), then the directory information will be printed, not the files in the directory. And, if you're looking for files more than 1 MB (as a now-deleted comment suggested), you need to adjust the +10000k
to 1000k
or maybe +1024k
, or +2048
(for 512-byte blocks, the default unit for -size
). This will list the size and then the file name. You could avoid the need for -d
by adding -type f
to the find
command, of course.
I think this post by Rex St John is very useful for unit testing with android studio.
(source: rexstjohn.com)
Use IF().
It is a short-circuiting ternary operator.
Dim Result = IF(expression,<true return>,<false return>)
SEE ALSO:
Using this SQL, Second highest salary will get with Employee Name
Select top 1 start at 2 salary from employee group by salary order by salary desc;
You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:
Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
System.IO.File.Create(filepath).Dispose()
End If
Try using Math.abs:
variableAbs = Math.abs(variable);
For square root use:
variableSqRt = Math.sqrt(variable);
You can simply call
using (StreamWriter w = File.AppendText("log.txt"))
It will create the file if it doesn't exist and open the file for appending.
Edit:
This is sufficient:
string path = txtFilePath.Text;
using(StreamWriter sw = File.AppendText(path))
{
foreach (var line in employeeList.Items)
{
Employee e = (Employee)line; // unbox once
sw.WriteLine(e.FirstName);
sw.WriteLine(e.LastName);
sw.WriteLine(e.JobTitle);
}
}
But if you insist on checking first, you can do something like this, but I don't see the point.
string path = txtFilePath.Text;
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
Also, one thing to point out with your code is that you're doing a lot of unnecessary unboxing. If you have to use a plain (non-generic) collection like ArrayList
, then unbox the object once and use the reference.
However, I perfer to use List<>
for my collections:
public class EmployeeList : List<Employee>
You should not create an instance of the activity class. It is wrong. Activity has ui and lifecycle and activity is started by startActivity(intent)
You can use startActivityForResult
or you can pass the values from one activity to another using intents and do what is required. But it depends on what you intend to do in the method.
An alternative crontab method inspired by this answer and this blog post.
1. Create a bash script file (change bob to desired user).
vi /home/bob/node_server_init.sh
2. Copy and paste this inside the file you've just created.
#!/bin/sh
export NODE_ENV=production
export PATH=/usr/local/bin:$PATH
forever start /node/server/path/server.js > /dev/null
Make sure to edit the paths above according to your config!
3. Make sure the bash script can be executed.
chmod 700 /home/bob/node_server_init.sh
4. Test the bash script.
sh /home/bob/node_server_init.sh
5. Replace "bob" with the runtime user for node.
crontab -u bob -e
6. Copy and paste (change bob to desired user).
@reboot /bin/sh /home/bob/node_server_init.sh
Save the crontab.
You've made it to the end, your prize is a reboot (to test) :)
The answer by Tomasz Nurkiewicz appears not to tell the whole story!
NB Mockito version: 1.10.19.
I am very much a Mockito newb, so can't explain the following behaviour: if there's an expert out there who can improve this answer, please feel free.
The method in question here, getContentStringValue
, is NOT final
and NOT static
.
This line does call the original method getContentStringValue
:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), isA( ScoreDoc.class ));
This line does not call the original method getContentStringValue
:
doReturn( "dummy" ).when( im ).getContentStringValue( anyInt(), any( ScoreDoc.class ));
For reasons which I can't answer, using isA()
causes the intended (?) "do not call method" behaviour of doReturn
to fail.
Let's look at the method signatures involved here: they are both static
methods of Matchers
. Both are said by the Javadoc to return null
, which is a little difficult to get your head around in itself. Presumably the Class
object passed as the parameter is examined but the result either never calculated or discarded. Given that null
can stand for any class and that you are hoping for the mocked method not to be called, couldn't the signatures of isA( ... )
and any( ... )
just return null
rather than a generic parameter* <T>
?
Anyway:
public static <T> T isA(java.lang.Class<T> clazz)
public static <T> T any(java.lang.Class<T> clazz)
The API documentation does not give any clue about this. It also seems to say the need for such "do not call method" behaviour is "very rare". Personally I use this technique all the time: typically I find that mocking involves a few lines which "set the scene" ... followed by calling a method which then "plays out" the scene in the mock context which you have staged... and while you are setting up the scenery and the props the last thing you want is for the actors to enter stage left and start acting their hearts out...
But this is way beyond my pay grade... I invite explanations from any passing Mockito high priests...
* is "generic parameter" the right term?
About looping through a hash:
$Q = @{"ONE"="1";"TWO"="2";"THREE"="3"}
$Q.GETENUMERATOR() | % { $_.VALUE }
1
3
2
$Q.GETENUMERATOR() | % { $_.key }
ONE
THREE
TWO
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind
functions to each result callback; the order of parameters is: (success, failure)
. So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: @get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401
If you want to translate your resources, just download MAT (Multilingual App Toolkit) for Visual Studio. https://marketplace.visualstudio.com/items?itemName=MultilingualAppToolkit.MultilingualAppToolkit-18308 This is the way to go to translate your projects in Visual Studio. https://blogs.msdn.microsoft.com/matdev/
I haven't checked this lately, but I know in the past with Oracle that the JDBC driver would reserve a chunk of memory during query execution to hold the result set coming back. The size of the memory chunk is dependent on the column definitions and the fetch size. So the length of the varchar2 columns affects how much memory is reserved. This caused serious performance issues for me years ago as we always used varchar2(4000) (the max at the time) and garbage collection was much less efficient than it is today.
Item #1. Putting a break
within the foreach
loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:
$todo=$project.PropertyGroup
foreach ($thing in $todo){
if ($thing -eq 'some_condition'){
break
}
}
Item #2. PowerShell lets you modify an array within a foreach
loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.
$a=1,2,3
foreach ($value in $a){
Write-Host $value
}
Write-Host $a
I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.
Attach gdb to one of the httpd child processes and reload or continue working and wait for a crash and then look at the backtrace. Do something like this:
$ ps -ef|grep httpd
0 681 1 0 10:38pm ?? 0:00.45 /Applications/MAMP/Library/bin/httpd -k start
501 690 681 0 10:38pm ?? 0:00.02 /Applications/MAMP/Library/bin/httpd -k start
...
Now attach gdb to one of the child processes, in this case PID 690 (columns are UID, PID, PPID, ...)
$ sudo gdb
(gdb) attach 690
Attaching to process 690.
Reading symbols for shared libraries . done
Reading symbols for shared libraries ....................... done
0x9568ce29 in accept$NOCANCEL$UNIX2003 ()
(gdb) c
Continuing.
Wait for crash... then:
(gdb) backtrace
Or
(gdb) backtrace full
Should give you some clue what's going on. If you file a bug report you should include the backtrace.
If the crash is hard to reproduce it may be a good idea to configure Apache to only use one child processes for handling requests. The config is something like this:
StartServers 1
MinSpareServers 1
MaxSpareServers 1
I solved it through googling:
var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception,
// the 'param' must consist of more than 12 characters.
User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]},
function(err,docs){
if(!err) res.send(docs);
});
Well your jsonString is wrong.
String jsonString = "{\"stat\":{\"sdr\": \"aa:bb:cc:dd:ee:ff\",\"rcv\": \"aa:bb:cc:dd:ee:ff\",\"time\": \"UTC in millis\",\"type\": 1,\"subt\": 1,\"argv\": [{\"1\":2},{\"2\":3}]}}";
use this jsonString
and if you use the same JSONParser
and ContainerFactory
in the example you will see that it will be encoded/decoded.
Additionally if you want to print your string after stat
here it goes:
try{
Map json = (Map)parser.parse(jsonString, containerFactory);
Iterator iter = json.entrySet().iterator();
System.out.println("==iterate result==");
Object entry = json.get("stat");
System.out.println(entry);
}
And about the json libraries, there are a lot of them. Better you check this.
According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).
FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional
v_aux VARCHAR2(32000);
v_has_double_quotes BOOLEAN;
v_has_comma BOOLEAN;
v_has_newline BOOLEAN;
BEGIN
v_has_double_quotes := instr(str, '"') > 0;
v_has_comma := instr(str,',') > 0;
v_has_newline := instr(str, C_NEWLINE) > 0;
IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
IF v_has_double_quotes THEN
v_aux := replace(str,'"','""');
ELSE
v_aux := str;
END IF;
return '"'||v_aux||'"';
ELSE
return str;
END IF;
END;
Looking in the headers sent...
res.send uses content-type:text/html
res.json uses content-type:application/json
edit: send actually changes what is sent based on what it's given, so strings are sent as text/html, but it you pass it an object it emits application/json.
The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.
Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.
You can set values from html like this. I don't think there is a direct solution from angular yet.
<div style="visibility: hidden;">{{activeTitle='home'}}</div>
When you bind the .submit()
event to the form, and you do the things you want to do before returning (true), these things happen prior to the actual submission.
For example:
$('form').submit(function(){
alert('I do something before the actual submission');
return true;
});
Another example on jquery.com: http://api.jquery.com/submit/#entry-examples
in my case (RHEL7 and MariaDB) this works.
sudo systemctl restart mariadb
The problem is that the second part of your substring argument is including the first index. You need to subtract the first index from your second index to make this work.
SELECT SUBSTRING(@Text, CHARINDEX('the dog', @Text)
, CHARINDEX('immediately',@text) - CHARINDEX('the dog', @Text) + Len('immediately'))
Use:
docker inspect $CID | grep IPAddress | grep -v null| cut -d '"' -f 4 | head -1
//first find out the removed ones
List removedList = new ArrayList();
for(Object a: list){
if(a.getXXX().equalsIgnoreCase("AAA")){
logger.info("this is AAA........should be removed from the list ");
removedList.add(a);
}
}
list.removeAll(removedList);
Follow below steps to install pyodbc in any redhat version
yum install unixODBC unixODBC-devel
yum install gcc-c++
yum install python-devel
pip install pyodbc
There is a sample from google, which lists the existing google accounts and generates an access token upon selection , you can send that access token to server to retrieve the related details from it to identify the user.
You can also get the email id from access token , for that you need to modify the SCOPE
Please go through My Post
The plus operator converts operands to int first and then does the addition. So the result is the int. You need to cast it back to short explicitly because conversions from a "longer" type to "shorter" type a made explicit, so that you don't loose data accidentally with an implicit cast.
As to why int16 is cast to int, the answer is, because this is what is defined in C# spec. And C# is this way is because it was designed to closely match to the way how CLR works, and CLR has only 32/64 bit arithmetic and not 16 bit. Other languages on top of CLR may choose to expose this differently.
You can call this method using the resultSet and the column name having Number type. It will either return the Integer value, or null. There will be no zeros returned for empty value in the database
private Integer getIntWithNullCheck(ResultSet rset, String columnName) {
try {
Integer value = rset.getInt(columnName);
return rset.wasNull() ? null : value;
} catch (Exception e) {
return null;
}
}
You could use a print stylesheet, but this will affect all print functions.
You could try having a print stylesheet externalally, and it is included via JavaScript when a button is pressed, and then call window.print()
, then after that remove it.
The middle letter of an odd-length word is irrelevant in determining whether the word is a palindrome. Just ignore it.
Hint: all you need is a slight tweak to the following line to make this work for all word lengths:
secondHalf = word[finalWordLength + 1:]
P.S. If you insist on handling the two cases separately, if len(word) % 2: ...
would tell you that the word has an odd number of characters.
What you can do, is open up a WebSocket connection when the page loads, optionally send data through the WebSocket identifying the current user, and check when that connection is closed on the server.
FYI I did a little research as well and if the name of the font-family you want to apply contains spaces (as an example I take Gill Alt One MT Light), you should write it this way :
strbody= "<BODY style=" & Chr(34) & "font-family:Gill Alt One MT Light" & Chr(34) & ">" & YOUR_TEXT & "</BODY>"
From the bash manpage:
When bash is invoked as an interactive login shell, or as a non-interactive shell with the
--login
option, it first reads and executes commands from the file/etc/profile
, if that file exists. After reading that file, it looks for~/.bash_profile
,~/.bash_login
, and~/.profile
, in that order, and reads and executes commands from the first one that exists and is readable. The--noprofile
option may be used when the shell is started to inhibit this behavior.When a login shell exits, bash reads and executes commands from the file
~/.bash_logout
, if it exists.When an interactive shell that is not a login shell is started, bash reads and executes commands from
~/.bashrc
, if that file exists. This may be inhibited by using the--norc
option. The--rcfile
file option will force bash to read and execute commands from file instead of~/.bashrc
.
Thus, if you want to get the same behavior for both login shells and interactive non-login shells, you should put all of your commands in either .bashrc
or .bash_profile
, and then have the other file source the first one.
I found using while IFS='=' read -r
to be a bit slow (I don't know why, maybe someone could briefly explain in a comment or point to a SO answer?). I also found @Nicolai answer very neat as a one-liner, but very inefficient as it will scan the entire properties file over and over again for every single call of prop
.
I found a solution that answers the question, performs well and it is a one-liner (bit verbose line though).
The solution does sourcing but massages the contents before sourcing:
#!/usr/bin/env bash
source <(grep -v '^ *#' ./app.properties | grep '[^ ] *=' | awk '{split($0,a,"="); print gensub(/\./, "_", "g", a[1]) "=" a[2]}')
echo $db_uat_user
Explanation:
grep -v '^ *#'
: discard comment lines
grep '[^ ] *='
: discards lines without =
split($0,a,"=")
: splits line at =
and stores into array a
, i.e. a[1] is the key, a[2] is the value
gensub(/\./, "_", "g", a[1])
: replaces .
with _
print gensub... "=" a[2]}
concatenates the result of gensub
above with =
and value.
Edit: As others pointed out, there are some incompatibilities issues (awk) and also it does not validate the contents to see if every line of the property file is actually a kv pair. But the goal here is to show the general idea for a solution that is both fast and clean. Sourcing seems to be the way to go as it loads the properties once that can be used multiple times.
First we must ensure that the desired attribute is loaded, and then output it. Use this:
$product = Mage::getModel('catalog/product')->load('<product_id>', array('<attribute_code>'));
$attributeValue = $product->getResource()->getAttribute('<attribute_code>')->getFrontend()->getValue($product);
You can use this option provided by dataTable itself using buttons.
dom: 'Bfrtip',
buttons: [
'selectAll',
'selectNone'
]'
Here is a sample code
var tableFaculty = $('#tableFaculty').DataTable({
"columns": [
{
data: function (row, type, set) {
return '';
}
},
{data: "NAME"}
],
"columnDefs": [
{
orderable: false,
className: 'select-checkbox',
targets: 0
}
],
select: {
style: 'multi',
selector: 'td:first-child'
},
dom: 'Bfrtip',
buttons: [
'selectAll',
'selectNone'
],
"order": [[0, 'desc']]
});
I had a similar problem. I have fixed it by turning "Windows PowerShell 2.0" feature on in "Turn Windows features on or off". Note that this feature is turned on by default, I manually turned it off few days ago.
I'm working on Windows 10 Pro 64bit and same problem was with Visual Studio 2015 and 2017 (32bit and 64bit app)
from http://ora-12154.ora-code.com
ORA-12154: TNS:could not resolve the connect identifier specified
Cause: A connection to a database or other service was requested using a connect identifier, and the connect identifier specified could not be resolved into a connect descriptor using one of the naming methods configured. For example, if the type of connect identifier used was a net service name then the net service name could not be found in a naming method repository, or the repository could not be located or reached.
Action:
If you are using local naming (TNSNAMES.ORA file):
Make sure that "TNSNAMES" is listed as one of the values of the NAMES.DIRECTORY_PATH parameter in the Oracle Net profile (SQLNET.ORA)
Verify that a TNSNAMES.ORA file exists and is in the proper directory and is accessible.
Check that the net service name used as the connect identifier exists in the TNSNAMES.ORA file.
Make sure there are no syntax errors anywhere in the TNSNAMES.ORA file. Look for unmatched parentheses or stray characters. Errors in a TNSNAMES.ORA file may make it unusable.
If you are using directory naming:
Verify that "LDAP" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).
Verify that the LDAP directory server is up and that it is accessible.
Verify that the net service name or database name used as the connect identifier is configured in the directory.
Verify that the default context being used is correct by specifying a fully qualified net service name or a full LDAP DN as the connect identifier
If you are using easy connect naming:
Verify that "EZCONNECT" is listed as one of the values of the NAMES.DIRETORY_PATH parameter in the Oracle Net profile (SQLNET.ORA).
Make sure the host, port and service name specified are correct.
Try enclosing the connect identifier in quote marks. See the Oracle Net Services Administrators Guide or the Oracle operating system specific guide for more information on naming.
Before using real image size you should load source image. If you use JQuery framework you can get real image size in simple way.
$("ImageID").load(function(){
console.log($(this).width() + "x" + $(this).height())
})
In the same line (I think this was not highlighted by any answer) it's good to mention that sometimes (specially in software where the performance matters—like in the Linux kernel) you can find some if statements like the following:
if (likely( everything_is_ok ))
{
/* Do something */
}
or similarly:
if (unlikely(very_improbable_condition))
{
/* Do something */
}
Both likely()
and unlikely()
are in fact macros that are defined by using something like the GCC's __builtin_expect
to help the compiler insert prediction code to favour the condition taking into account the information provided by the user. GCC supports other builtins that could change the behavior of the running program or emit low level instructions like clearing the cache, etc. See this documentation that goes through the available GCC's builtins.
Normally this kind of optimizations are mainly found in hard-real time applications or embedded systems where execution time matters and it's critical. For example, if you are checking for some error condition that only happens 1/10000000 times, then why not inform the compiler about this? This way, by default, the branch prediction would assume that the condition is false.
Well, as suggested by Hellfire you can use td
width or you could place an element in the td and adjust its width. We could not use
CSS property Padding
as in Microsoft Outlook
padding does not work.
So what I had to do is,
<table>
<tr>
<td><span style="display: inline-block; width: 40px;"></span><span>Content<span></td>
<td>Content</td>
</tr>
</table>
With this you can adjust right and left spacing. For top and bottom spacing you could use td's height property. Like,
<table>
<tr>
<td style="vertical-align: top; height: 100px;">Content</td>
<td>Content</td>
</tr>
</table>
This will increase bottom space.
Hope it will work for you guys. :)
Make sure you have a block element, a maximum size and set overflow to hidden. (Tested in IE9 and FF 7)
div {
border: solid 2px blue;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
width: 50px;
}
WebSockets is definitely the future.
Long polling is a dirty workaround to prevent creating connections for each request like AJAX does -- but long polling was created when WebSockets didn't exist. Now due to WebSockets, long polling is going away.
WebRTC allows for peer-to-peer communication.
I recommend learning WebSockets.
of different communication techniques on the web
AJAX - request
→ response
. Creates a connection to the server, sends request headers with optional data, gets a response from the server, and closes the connection.
Supported in all major browsers.
Long poll - request
→ wait
→ response
. Creates a connection to the server like AJAX does, but maintains a keep-alive connection open for some time (not long though). During connection, the open client can receive data from the server. The client has to reconnect periodically after the connection is closed, due to timeouts or data eof. On server side it is still treated like an HTTP request, same as AJAX, except the answer on request will happen now or some time in the future, defined by the application logic.
support chart (full) | wikipedia
WebSockets - client
↔ server
. Create a TCP connection to the server, and keep it open as long as needed. The server or client can easily close the connection. The client goes through an HTTP compatible handshake process. If it succeeds, then the server and client can exchange data in both directions at any time. It is efficient if the application requires frequent data exchange in both ways. WebSockets do have data framing that includes masking for each message sent from client to server, so data is simply encrypted.
support chart (very good) | wikipedia
WebRTC - peer
↔ peer
. Transport to establish communication between clients and is transport-agnostic, so it can use UDP, TCP or even more abstract layers. This is generally used for high volume data transfer, such as video/audio streaming, where reliability is secondary and a few frames or reduction in quality progression can be sacrificed in favour of response time and, at least, some data transfer. Both sides (peers) can push data to each other independently. While it can be used totally independent from any centralised servers, it still requires some way of exchanging endPoints data, where in most cases developers still use centralised servers to "link" peers. This is required only to exchange essential data for establishing a connection, after which a centralised server is not required.
support chart (medium) | wikipedia
Server-Sent Events - client
← server
. Client establishes persistent and long-term connection to server. Only the server can send data to a client. If the client wants to send data to the server, it would require the use of another technology/protocol to do so. This protocol is HTTP compatible and simple to implement in most server-side platforms. This is a preferable protocol to be used instead of Long Polling. support chart (good, except IE) | wikipedia
The main advantage of WebSockets server-side, is that it is not an HTTP request (after handshake), but a proper message based communication protocol. This enables you to achieve huge performance and architecture advantages. For example, in node.js, you can share the same memory for different socket connections, so they can each access shared variables. Therefore, you don't need to use a database as an exchange point in the middle (like with AJAX or Long Polling with a language like PHP). You can store data in RAM, or even republish between sockets straight away.
People are often concerned about the security of WebSockets. The reality is that it makes little difference or even puts WebSockets as better option. First of all, with AJAX, there is a higher chance of MITM, as each request is a new TCP connection that is traversing through internet infrastructure. With WebSockets, once it's connected it is far more challenging to intercept in between, with additionally enforced frame masking when data is streamed from client to server as well as additional compression, which requires more effort to probe data. All modern protocols support both: HTTP and HTTPS (encrypted).
Remember that WebSockets generally have a very different approach of logic for networking, more like real-time games had all this time, and not like http.
I think the right way to find the internal Java used by the Android Studio is to
This will not require memorising the folder or searching for java and also these steps wil take of any future changes to the java location by the Android Studio team changes I suppose
To get callback on LocationChange
Define an interface
public interface LocationCallback {
public void locationChanged(Location location);
}
Callback in your Activity
public static LocationCallback callback;
public void getUserLocation() {
callback = new LocationCallback() {
@Override
public void locationChanged(Location location) {
Toast.makeText(getApplicationContext(), location.getLatitude() + "," + location.getLongitude(), Toast.LENGTH_SHORT).show();
}
};
Intent service_intent = new Intent(this, GPSService.class);
startService(service_intent);
}
Change onLocationChange Method to
@Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
MapsActivity.callback.locationChanged(location);
mLastLocation.set(location);
}
I had the same issues as Tyler Sheaffer.
I implemented his solution in Swift and it solved my problems.
Swift 3.0:
final class UITableViewWithReloadCompletion: UITableView {
private var reloadDataCompletionBlock: (() -> Void)?
override func layoutSubviews() {
super.layoutSubviews()
reloadDataCompletionBlock?()
reloadDataCompletionBlock = nil
}
func reloadDataWithCompletion(completion: @escaping () -> Void) {
reloadDataCompletionBlock = completion
self.reloadData()
}
}
Swift 2:
class UITableViewWithReloadCompletion: UITableView {
var reloadDataCompletionBlock: (() -> Void)?
override func layoutSubviews() {
super.layoutSubviews()
self.reloadDataCompletionBlock?()
self.reloadDataCompletionBlock = nil
}
func reloadDataWithCompletion(completion:() -> Void) {
reloadDataCompletionBlock = completion
self.reloadData()
}
}
Example Usage:
tableView.reloadDataWithCompletion() {
// reloadData is guaranteed to have completed
}
Stop the MySQL process.
Start the MySQL process with the --skip-grant-tables option.
Start the MySQL console client with the -u root option.
List all the users;
SELECT * FROM mysql.user;
Reset password;
UPDATE mysql.user SET Password=PASSWORD('[password]') WHERE User='[username]';
But DO NOT FORGET to
Stop the MySQL process
Start the MySQL Process normally (i.e. without the --skip-grant-tables option)
when you are finished. Otherwise, your database's security could be compromised.
Another quicker option to call things (like DialogBoxes and MessageBoxes and creating separate threads for not-thread safe methods) would be to use the Lamba Expression
new Thread(() -> {
"code here"
}).start();
The source
command is built into some shells. If you have a script, it should specify what shell to use on the first line, such as:
#!/bin/bash
You can catch key event :
function checkEventObj ( _event_ ){
// --- IE explorer
if ( window.event )
return window.event;
// --- Netscape and other explorers
else
return _event_;
}
document.keydown = function(_event) {
var e = checkEventObject(_event);
if( e.ctrlKey && (e.keyCode == 86) )
window.clipboardData.clearData();
}
Not tested but, could help.
Source from comentcamarche and Zakaria
select
email
from loginuser where
patindex ('%[ &'',":;!+=\/()<>]*%', email) > 0 -- Invalid characters
or patindex ('[@.-_]%', email) > 0 -- Valid but cannot be starting character
or patindex ('%[@.-_]', email) > 0 -- Valid but cannot be ending character
or email not like '%@%.%' -- Must contain at least one @ and one .
or email like '%..%' -- Cannot have two periods in a row
or email like '%@%@%' -- Cannot have two @ anywhere
or email like '%.@%' or email like '%@.%' -- Cant have @ and . next to each other
or email like '%.cm' or email like '%.co' -- Unlikely. Probably typos
or email like '%.or' or email like '%.ne' -- Missing last letter
This worked for me. Had to apply rtrim and ltrim to avoid false positives.
Source: http://sevenwires.blogspot.com/2008/09/sql-how-to-find-invalid-email-in-sql.html
Postgres version:
select user_guid, user_guid email_address, creation_date, email_verified, active
from user_data where
length(substring (email_address from '%[ &'',":;!+=\/()<>]%')) > 0 -- Invalid characters
or length(substring (email_address from '[@.-_]%')) > 0 -- Valid but cannot be starting character
or length(substring (email_address from '%[@.-_]')) > 0 -- Valid but cannot be ending character
or email_address not like '%@%.%' -- Must contain at least one @ and one .
or email_address like '%..%' -- Cannot have two periods in a row
or email_address like '%@%@%' -- Cannot have two @ anywhere
or email_address like '%.@%' or email_address like '%@.%' -- Cant have @ and . next to each other
or email_address like '%.cm' or email_address like '%.co' -- Unlikely. Probably typos
or email_address like '%.or' or email_address like '%.ne' -- Missing last letter
;
Adding class using element's classList property:
element.classList.add('my-class-name');
Removing:
element.classList.remove('my-class-name');
This is an old question, but everybody fails to mention that Enums are actually Serializable
and therefore can perfectly be added to an Intent as an extra. Like this:
public enum AwesomeEnum {
SOMETHING, OTHER;
}
intent.putExtra("AwesomeEnum", AwesomeEnum.SOMETHING);
AwesomeEnum result = (AwesomeEnum) intent.getSerializableExtra("AwesomeEnum");
The suggestion to use static or application-wide variables is a really bad idea. This really couples your activities to a state managing system, and it is hard to maintain, debug and problem bound.
ALTERNATIVES:
A good point was noted by tedzyc about the fact that the solution provided by Oderik gives you an error. However, the alternative offered is a bit cumbersome to use (even using generics).
If you are really worried about the performance of adding the enum to an Intent I propose these alternatives instead:
OPTION 1:
public enum AwesomeEnum {
SOMETHING, OTHER;
private static final String name = AwesomeEnum.class.getName();
public void attachTo(Intent intent) {
intent.putExtra(name, ordinal());
}
public static AwesomeEnum detachFrom(Intent intent) {
if(!intent.hasExtra(name)) throw new IllegalStateException();
return values()[intent.getIntExtra(name, -1)];
}
}
Usage:
// Sender usage
AwesomeEnum.SOMETHING.attachTo(intent);
// Receiver usage
AwesomeEnum result = AwesomeEnum.detachFrom(intent);
OPTION 2: (generic, reusable and decoupled from the enum)
public final class EnumUtil {
public static class Serializer<T extends Enum<T>> extends Deserializer<T> {
private T victim;
@SuppressWarnings("unchecked")
public Serializer(T victim) {
super((Class<T>) victim.getClass());
this.victim = victim;
}
public void to(Intent intent) {
intent.putExtra(name, victim.ordinal());
}
}
public static class Deserializer<T extends Enum<T>> {
protected Class<T> victimType;
protected String name;
public Deserializer(Class<T> victimType) {
this.victimType = victimType;
this.name = victimType.getName();
}
public T from(Intent intent) {
if (!intent.hasExtra(name)) throw new IllegalStateException();
return victimType.getEnumConstants()[intent.getIntExtra(name, -1)];
}
}
public static <T extends Enum<T>> Deserializer<T> deserialize(Class<T> victim) {
return new Deserializer<T>(victim);
}
public static <T extends Enum<T>> Serializer<T> serialize(T victim) {
return new Serializer<T>(victim);
}
}
Usage:
// Sender usage
EnumUtil.serialize(AwesomeEnum.Something).to(intent);
// Receiver usage
AwesomeEnum result =
EnumUtil.deserialize(AwesomeEnum.class).from(intent);
OPTION 3 (with Kotlin):
It's been a while, but since now we have Kotlin, I thought I would add another option for the new paradigm. Here we can make use of extension functions and reified types (which retains the type when compiling).
inline fun <reified T : Enum<T>> Intent.putExtra(victim: T): Intent =
putExtra(T::class.java.name, victim.ordinal)
inline fun <reified T: Enum<T>> Intent.getEnumExtra(): T? =
getIntExtra(T::class.java.name, -1)
.takeUnless { it == -1 }
?.let { T::class.java.enumConstants[it] }
There are a few benefits of doing it this way.
inline
which will replace the calls with the code inside the function.One of the downsides is that, if we change the order of the Emums, then any old reference will not work. This can be an issue with things like Intents inside pending intents as they may survive updates. However, for the rest of the time, it should be ok.
It's important to note that other solutions, like using the name instead of the position, will also fail if we rename any of the values. Although, in those cases, we get an exception instead of the incorrect Enum value.
Usage:
// Sender usage
intent.putExtra(AwesomeEnum.SOMETHING)
// Receiver usage
val result = intent.getEnumExtra<AwesomeEnum>()
ALTER TABLE [dbo].[TableName]
DROP CONSTRAINT FK_TableName_TableName2
Looks like Windows might just let you do this...
Unfortunately I don't think you're going to get around starting a separate process unless you go to a third party component.
I use:
let dictionary = ["method":"login_user",
"cel":mobile.text!
"password":password.text!] as Dictionary<String,String>
for (key, value) in dictionary {
data=data+"&"+key+"="+value
}
request.HTTPBody = data.dataUsingEncoding(NSUTF8StringEncoding);
Note: this only answers part of the question.
If you just want to know the maximum number of sessions allowed, then you can execute in sqlplus, as sysdba:
SQL> show parameter sessions
This gives you an output like:
NAME TYPE VALUE
------------------------------------ ----------- ------------------------------
java_max_sessionspace_size integer 0
java_soft_sessionspace_limit integer 0
license_max_sessions integer 0
license_sessions_warning integer 0
sessions integer 248
shared_server_sessions integer
The sessions parameter is the one what you want.
Your code was very close to working.
Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.
Here's some code that writes each key/value pair on a separate row:
import csv
somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerows(somedict.items())
If instead you want all the keys on one row and all the values on the next, that is also easy:
with open('mycsvfile.csv','wb') as f:
w = csv.writer(f)
w.writerow(somedict.keys())
w.writerow(somedict.values())
Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr)
so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f)
.
To make it short, it means that you lacked some "dependencies" for the libraries you wanted to use. Before trying to use any kind of library, first it is suggested to look up whether it needs another library in python "family". What do I mean?
Downloading "dlls" is something that I avoid. I had the same problem with another library "kivy". The problem occurred when I wanted to use Python 3.4v instead of 3.5 Everything was working correctly in 3.5 but I just wanted to use the stable version for kivy which is 3.4 as they officially "advise". So, I switched to 3.4 but then I had the very same "dll" error saying lots of things are missing. So I checked the website and learned that I needed to install extra "dependencies" from the official website of kivy, then the problem got solved.
I had similar issues when migrating to androidx. this issue comes due to the Old Butter Knife library dependency.
if you are using butter knife then you should use at least butter knife version 9.0.0-SNAPSHOT or above.
implementation 'com.jakewharton:butterknife:9.0.0-SNAPSHOT'
annotationProcessor 'com.jakewharton:butterknife-compiler:9.0.0-SNAPSHOT'
I don't know if the answer will be late, but I have used this form.
JS:
function getPDF() {
html2canvas(document.getElementById("toPDF"),{
onrendered:function(canvas){
var img=canvas.toDataURL("image/png");
var doc = new jsPDF('l', 'cm');
doc.addImage(img,'PNG',2,2);
doc.save('reporte.pdf');
}
});
}
HTML:
<div id="toPDF">
#your content...
</div>
<button id="getPDF" type="button" class="btn btn-info" onclick="getPDF()">
Download PDF
</button>
For me, it came down to the proxy_pass
location setting. I needed to change over to using the HTTPS protocol, and have a valid SSL certificate set up on the node server side of things. That way when I introduce an external node server, I only have to change the IP and everything else remains the same config.
I hope this helps someone along the way... I was staring at the problem the whole time... sigh...
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream nodeserver {
server 127.0.0.1:8080;
}
server {
listen 443 default_server ssl http2;
listen [::]:443 default_server ssl http2 ipv6only=on;
server_name mysite.com;
ssl_certificate ssl/site.crt;
ssl_certificate_key ssl/site.key;
location /websocket { #replace /websocket with the path required by your application
proxy_pass https://nodeserver;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_intercept_errors on;
proxy_redirect off;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-NginX-Proxy true;
proxy_ssl_session_reuse off;
}
}
NOTE: This is mentioned in the question but restarting Visual Studio fixes the issue in most cases.
Updating Visual Studio to 'Update 2' got it working again.
Tools -> Extensions and Updates ->Visual Studio Update 2
As mentioned in the question and the link i posted therein, I'd already updated NuGet Package Manager to 3.4.4 prior to this and restarted to no avail, so I don't know if the combination of both these actions worked.
In Microservices world (having a common shared codebase), each Microservice would have a Dockerfile
whereas at the root level (generally outside of all Microservices and where your parent POM resides) you would define a docker-compose.yml
to group all Microservices into a full-blown app.
In your case "Docker Compose" is preferred over "Dockerfile". Think "App" Think "Compose".
I found this which covers most sample links, including subdirectory parts.
Regex is:
(?:(?:https?|ftp):\/\/|\b(?:[a-z\d]+\.))(?:(?:[^\s()<>]+|\((?:[^\s()<>]+|(?:\([^\s()<>]+\)))?\))+(?:\((?:[^\s()<>]+|(?:\(?:[^\s()<>]+\)))?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))?
By the answer of rudivonstaden
txtBlock.Text = await response.Content.ReadAsStringAsync();
but if you don't want to make the method async you can use
txtBlock.Text = response.Content.ReadAsStringAsync();
txtBlock.Text.Wait();
Wait() it's important, bec?use we are doing async operations and we must wait for the task to complete before going ahead.
You don't have to use the message passing to obtain or modify DOM. I used chrome.tabs.executeScript
instead. In my example I am using only activeTab permission, therefore the script is executed only on the active tab.
part of manifest.json
"browser_action": {
"default_title": "Test",
"default_popup": "index.html"
},
"permissions": [
"activeTab",
"<all_urls>"
]
index.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="test">TEST!</button>
<script src="test.js"></script>
</body>
</html>
test.js
document.getElementById("test").addEventListener('click', () => {
console.log("Popup DOM fully loaded and parsed");
function modifyDOM() {
//You can play with your DOM here or check URL against your regex
console.log('Tab script:');
console.log(document.body);
return document.body.innerHTML;
}
//We have permission to access the activeTab, so we can call chrome.tabs.executeScript:
chrome.tabs.executeScript({
code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code
}, (results) => {
//Here we have just the innerHTML and not DOM structure
console.log('Popup script:')
console.log(results[0]);
});
});
You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
Sql server unlike oracle does not need commits unless you are using transactions.
Immediatly after your update statement the table will be commited, don't use the commit command in this scenario.
Moment.js provides such functionality:
It's well documented and nice library.
It should go along the lines "Duration" and "Humanize of API http://momentjs.com/docs/#/displaying/from/
var d1, d2; // Timepoints
var differenceInPlainText = moment(a).from(moment(b), true); // Add true for suffixless text
I can not see where do you declare context
. For the purpose of the intent creation you can use MainActivity.this
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(MainActivity.this, SendMessage.class);
String message = "abc";
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
To retrieve the object upon you have clicked you can use the AdapterView
:
ListEntry entry = (ListEntry) parent.getItemAtPosition(position);
write a cloud function to and update the node count.
// below function to get the given node count.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.userscount = functions.database.ref('/users/')
.onWrite(event => {
console.log('users number : ', event.data.numChildren());
return event.data.ref.parent.child('count/users').set(event.data.numChildren());
});
Refer :https://firebase.google.com/docs/functions/database-events
root--|
|-users ( this node contains all users list)
|
|-count
|-userscount :
(this node added dynamically by cloud function with the user count)
Update your build.gradle(Module:app) add compileOptions
block and add JavaVersion.VERSION_1_8
apply plugin: 'com.android.application'
android {
.................
.........................
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
I tried changing value="true"
to ng-value="true"
, and it seems to work.
<input type="radio" name="response2" data-ng-model="choice.isUserAnswer" ng-value="true" />
Also, to get both inputs to work in your example, you'd have to give different name to each input -- e.g. response
should become response1
and response2
.
bash your_script.sh 1>file.log 2>&1
1>file.log
instructs the shell to send STDOUT to the file file.log
, and 2>&1
tells it to redirect STDERR (file descriptor 2) to STDOUT (file descriptor 1).
Note: The order matters as liw.fi pointed out, 2>&1 1>file.log
doesn't work.
//$sql - sql statement
//$em - entity manager
$em->getConnection()->exec( $sql );
If your object is myObject
, and you want to test to see if it is an NSString
, the code would be:
[myObject isKindOfClass:[NSString class]]
Likewise, if you wanted to test myObject
for a UIImageView
:
[myObject isKindOfClass:[UIImageView class]]
Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
Configure webpack
module: {
loaders: [
{
test: /\.css$/,
loader: 'style-loader'
}, {
test: /\.css$/,
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
}
]
}
To summarize:
Step1
Project Properties
-> Configuration Properties
-> Linker (General)
-> Enable Incremental Linking -> "No (/INCREMENTAL:NO)"
if step1 not work, do Step2
Project Properties
-> Configuration Properties
-> Manifest Tool (Input and Output)
-> Enable Incremental Linking -> "No"
if step2 not work, do Step3 Copy file one of:
C:\Program Files (x86)\Microsoft Visual Studio 13.0\VC\bin\cvtres.exe
Then, replace to C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\cvtres.exe With me, do 3 step it work
Anyone who is just starting with Haskell and trying to print an Int, use:
module Lib
( someFunc
) where
someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)
You can use .net application https://github.com/abhiyx/RedisSizeCalculator to calculate the size of redis key,
Please feel free to give your feedback for the same
Don't forget to take into consideration the global flag in your regexp :
var reg = /abc/g;
!!'abcdefghi'.match(reg); // => true
!!'abcdefghi'.match(reg); // => true
reg.test('abcdefghi'); // => true
reg.test('abcdefghi'); // => false <=
This is because Regexp keeps track of the lastIndex when a new match is found.
This answer attempts a pragmatic summary of the many great answers on this page:
jeb's great answer deserves special mention, because it really goes in-depth and covers many edge cases.
Notably, he points out that a misconstructed variable/parameter reference such as %~
can break any of the solutions below - including REM
lines.
REM
(or case variations thereof) is the only official comment construct, and is the safest choice - see Joey's helpful answer.
::
is a (widely used) hack, which has pros and cons:
Pros:
Cons:
(...)
blocks, ::
can break the command, and the rules for safe use are restrictive and not easy to remember - see below.If you do want to use ::
, you have these choices:
(...)
blocks and use REM
there, or do not place comments inside (...)
altogether.::
inside (...)
, which are summarized in the following snippet:@echo off
for %%i in ("dummy loop") do (
:: This works: ONE comment line only, followed by a DIFFERENT, NONBLANK line.
date /t
REM If you followed a :: line directly with another one, the *2nd* one
REM would generate a spurious "The system cannot find the drive specified."
REM error message and potentially execute commands inside the comment.
REM In the following - commented-out - example, file "out.txt" would be
REM created (as an empty file), and the ECHO command would execute.
REM :: 1st line
REM :: 2nd line > out.txt & echo HERE
REM NOTE: If :: were used in the 2 cases explained below, the FOR statement
REM would *break altogether*, reporting:
REM 1st case: "The syntax of the command is incorrect."
REM 2nd case: ") was unexpected at this time."
REM Because the next line is *blank*, :: would NOT work here.
REM Because this is the *last line* in the block, :: would NOT work here.
)
Note that none of these styles are directly supported by the batch language, but can be emulated.
Inline comments:
* The code snippets below use ver
as a stand-in for an arbitrary command, so as to facilitate experimentation.
* To make SET
commands work correctly with inline comments, double-quote the name=value
part; e.g., SET "foo=bar"
.[1]
In this context we can distinguish two subtypes:
EOL comments ([to-the-]end-of-line), which can be placed after a command, and invariably extend to the end of the line (again, courtesy of jeb's answer):
ver & REM <comment>
takes advantage of the fact that REM
is a valid command and &
can be used to place an additional command after an existing one.ver & :: <comment>
works too, but is really only usable outside of (...)
blocks, because its safe use there is even more limited than using ::
standalone.Intra-line comments, which be placed between multiple commands on a line or ideally even inside of a given command.
Intra-line comments are the most flexible (single-line) form and can by definition also be used as EOL comments.
ver & REM^. ^<comment^> & ver
allows inserting a comment between commands (again, courtesy of jeb's answer), but note how <
and >
needed to be ^
-escaped, because the following chars. cannot be used as-is: < > |
(whereas unescaped &
or &&
or ||
start the next command).
%= <comment> =%
, as detailed in dbenham's great answer, is the most flexible form, because it can be placed inside a command (among the arguments).
It takes advantage of variable-expansion syntax in a way that ensures that the expression always expands to the empty string - as long as the comment text contains neither %
nor :
Like REM
, %= <comment> =%
works well both outside and inside (...)
blocks, but it is more visually distinctive; the only down-sides are that it is harder to type, easier to get wrong syntactically, and not widely known, which can hinder understanding of source code that uses the technique.
Multi-line (whole-line block) comments:
James K's answer shows how to use a goto
statement and a label to delimit a multi-line comment of arbitrary length and content (which in his case he uses to store usage information).
Zee's answer shows how to use a "null label" to create a multi-line comment, although care must be taken to terminate all interior lines with ^
.
Rob van der Woude's blog post mentions another somewhat obscure option that allows you to end a file with an arbitrary number of comment lines: An opening (
only causes everything that comes after to be ignored, as long as it doesn't contain a ( non-^
-escaped) )
, i.e., as long as the block is not closed.
[1] Using SET "foo=bar"
to define variables - i.e., putting double quotes around the name and =
and the value combined - is necessary in commands such as SET "foo=bar" & REM Set foo to bar.
, so as to ensure that what follows the intended variable value (up to the next command, in this case a single space) doesn't accidentally become part of it.
(As an aside: SET foo="bar"
would not only not avoid the problem, it would make the double quotes part of the value).
Note that this problem is inherent to SET
and even applies to accidental trailing whitespace following the value, so it is advisable to always use the SET "foo=bar"
approach.
I had the same problem.....the issu is in the version PHP SDK 5.6.2 and the fix was editing the following file:
facebook\src\Facebook\Helpers\FacebookRedirectLoginHelper.php
change this line
$redirectUrl = FacebookUrlManipulator::removeParamsFromUrl($redirectUrl,['state','code']);
to
$redirectUrl = FacebookUrlManipulator::removeParamsFromUrl($redirectUrl,['state','code','enforce_https']);
I would try the program screen.
GoalSeek will throw an "Invalid Reference" error if the GoalSeek cell contains a value rather than a formula or if the ChangingCell contains a formula instead of a value or nothing.
The GoalSeek cell must contain a formula that refers directly or indirectly to the ChangingCell; if the formula doesn't refer to the ChangingCell in some way, GoalSeek either may not converge to an answer or may produce a nonsensical answer.
I tested your code with a different GoalSeek formula than yours (I wasn't quite clear whether some of the terms referred to cells or values).
For the test, I set:
the GoalSeek cell H18 = (G18^3)+(3*G18^2)+6
the Goal cell H32 = 11
the ChangingCell G18 = 0
The code was:
Sub GSeek()
With Worksheets("Sheet1")
.Range("H18").GoalSeek _
Goal:=.Range("H32").Value, _
ChangingCell:=.Range("G18")
End With
End Sub
And the code produced the (correct) answer of 1.1038, the value of G18 at which the formula in H18 produces the value of 11, the goal I was seeking.
To build uri with get parameters, Uri.Builder provides a more effective way.
Uri uri = new Uri.Builder()
.scheme("http")
.authority("foo.com")
.path("someservlet")
.appendQueryParameter("param1", foo)
.appendQueryParameter("param2", bar)
.build();