"Segmentation fault (core dumped)"
is the string that Linux prints when a program exits with a SIGSEGV
signal and you have core creation enabled. This means some program has crashed.
If you're actually getting this error from running Python, this means the Python interpreter has crashed. There are only a few reasons this can happen:
You're using a third-party extension module written in C, and that extension module has crashed.
You're (directly or indirectly) using the built-in module ctypes
, and calling external code that crashes.
There's something wrong with your Python installation.
You've discovered a bug in Python that you should report.
The first is by far the most common. If your q
is an instance of some object from some third-party extension module, you may want to look at the documentation.
Often, when C modules crash, it's because you're doing something which is invalid, or at least uncommon and untested. But whether it's your "fault" in that sense or not - that doesn't matter. The module should raise a Python exception that you can debug, instead of crashing. So, you should probably report a bug to whoever wrote the extension. But meanwhile, rather than waiting 6 months for the bug to be fixed and a new version to come out, you need to figure out what you did that triggered the crash, and whether there's some different way to do what you want. Or switch to a different library.
On the other hand, since you're reading and printing out data from somewhere else, it's possible that your Python interpreter just read the line "Segmentation fault (core dumped)"
and faithfully printed what it read. In that case, some other program upstream presumably crashed. (It's even possible that nobody crashed—if you fetched this page from the web and printed it out, you'd get that same line, right?) In your case, based on your comment, it's probably the Java program that crashed.
If you're not sure which case it is (and don't want to learn how to do process management, core-file inspection, or C-level debugging today), there's an easy way to test: After print line
add a line saying print "And I'm OK"
. If you see that after the Segmentation fault
line, then Python didn't crash, someone else did. If you don't see it, then it's probably Python that's crashed.
Here's the markup that should work, both locally and remotely - copied from html-5-tutorial.com:
<div id="google_translate_element"></div>
<script>
function googleTranslateElementInit() {
new google.translate.TranslateElement(
{pageLanguage: 'en'},
'google_translate_element'
);
}
</script>
<script src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
Use nm -a your.dylib
It will print all the symbols including globals
Some counterpoints from the author:
You are stuck if you need to make the class not single in the future Not at all - I was in this situation with a single database connection singleton that I wanted to turn into a connection pool. Remember that every singleton is accessed through a standard method:
MyClass.instance
This is similar to the signature of a factory method. All I did was update the instance method to return the next connection from the pool - no other changes required. That would have been far harder if we had NOT been using a singleton.
Singletons are just fancy globals Can't argue with that but so are all static fields and methods - anything that is accessed from the class rather than an instance is essentially global and I dont see so much pushback on the use of static fields?
Not saying that Singletons are good, just pushing back at some of the 'conventional wisdom' here.
Another solution is to do the division within a python command. For example:
$ numerator=90
$ denominator=7
$ python -c "print (round(${numerator}.0 / ${denominator}.0))"
Seems less archaic to me than using awk.
If above solutions dont work, try this and it works for me:
componentWillUnmount() {
// fix Warning: Can't perform a React state update on an unmounted component
this.setState = (state,callback)=>{
return;
};
}
It looks like that function isn't implemented in IE. If you're using jQuery, you could use $.trim()
instead (http://api.jquery.com/jQuery.trim/).
This question is the top Google result for "Java String Right".
Surprisingly, no-one has yet mentioned Apache Commons StringUtils.right():
String numbers = org.apache.commons.lang.StringUtils.right( text, 7 );
This also handles the case where text
is null, where many of the other answers would throw a NullPointerException.
Whatever is assigned to the files
variable is incorrect. Use the following code.
import glob
import os
list_of_files = glob.glob('/path/to/folder/*') # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)
You can change the send line to this:
c.send(b'Thank you for connecting')
The b
makes it bytes instead.
Using Google Guava:
CharMatcher.DIGIT.retainFrom("123-456-789");
CharMatcher is plug-able and quite interesting to use, for instance you can do the following:
String input = "My phone number is 123-456-789!";
String output = CharMatcher.is('-').or(CharMatcher.DIGIT).retainFrom(input);
output == 123-456-789
Addition for:
++ A mistake that’s often made when approaching REST is to think of it as “web services with URLs”—to think of REST as another remote procedure call (RPC) mechanism, like SOAP, but invoked through plain HTTP URLs and without SOAP’s hefty XML namespaces.
++ On the contrary, REST has little to do with RPC. Whereas RPC is service oriented and focused on actions and verbs, REST is resource oriented, emphasizing the things and nouns that comprise an application.
Hope this helps like it did for me.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_URI} !^public
RewriteRule ^(.*)$ public/$1 [L]
</IfModule>
Using jQuery:
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function doWork()
{
if (window.isActive) { /* do CPU-intensive stuff */}
}
For checking a variable content and have a default text, you can use:
<span>{{myVar || 'Text'}}</span>
This example shows how to use the method GetInvocationList() to retrieve delegates to all the handlers that have been added. If you are looking to see if a specific handler (function) has been added then you can use array.
public class MyClass
{
event Action MyEvent;
}
...
MyClass myClass = new MyClass();
myClass.MyEvent += SomeFunction;
...
Action[] handlers = myClass.MyEvent.GetInvocationList(); //this will be an array of 1 in this example
Console.WriteLine(handlers[0].Method.Name);//prints the name of the method
You can examine various properties on the Method property of the delegate to see if a specific function has been added.
If you are looking to see if there is just one attached, you can just test for null.
Use getChildCount()
and getChildAt(int index)
.
Example:
LinearLayout ll = …
final int childCount = ll.getChildCount();
for (int i = 0; i < childCount; i++) {
View v = ll.getChildAt(i);
// Do something with v.
// …
}
Windows uses .cer extension for an X.509 certificate. These can be in "binary" (ASN.1 DER), or it can be encoded with Base-64 and have a header and footer applied (PEM); Windows will recognize either. To verify the integrity of a certificate, you have to check its signature using the issuer's public key... which is, in turn, another certificate.
Windows uses .pfx for a PKCS #12 file. This file can contain a variety of cryptographic information, including certificates, certificate chains, root authority certificates, and private keys. Its contents can be cryptographically protected (with passwords) to keep private keys private and preserve the integrity of root certificates.
Windows uses .pvk for a private key file. I'm not sure what standard (if any) Windows follows for these. Hopefully they are PKCS #8 encoded keys. Emmanuel Bourg reports that these are a proprietary format. Some documentation is available.
You should never disclose your private key. These are contained in .pfx and .pvk files.
Generally, you only exchange your certificate (.cer) and the certificates of any intermediate issuers (i.e., the certificates of all of your CAs, except the root CA) with other parties.
One could use the Buffer
s that are provided as part of the java.nio
package to perform the conversion.
Here, the source byte[]
array has a of length 8, which is the size that corresponds with a long
value.
First, the byte[]
array is wrapped in a ByteBuffer
, and then the ByteBuffer.getLong
method is called to obtain the long
value:
ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();
System.out.println(l);
Result
4
I'd like to thank dfa for pointing out the ByteBuffer.getLong
method in the comments.
Although it may not be applicable in this situation, the beauty of the Buffer
s come with looking at an array with multiple values.
For example, if we had a 8 byte array, and we wanted to view it as two int
values, we could wrap the byte[]
array in an ByteBuffer
, which is viewed as a IntBuffer
and obtain the values by IntBuffer.get
:
ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 1, 0, 0, 0, 4});
IntBuffer ib = bb.asIntBuffer();
int i0 = ib.get(0);
int i1 = ib.get(1);
System.out.println(i0);
System.out.println(i1);
Result:
1
4
String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];
This should do it. Everything nicely stored in res
.
Did you try df.groupby('id').head(2)
Ouput generated:
>>> df.groupby('id').head(2)
id value
id
1 0 1 1
1 1 2
2 3 2 1
4 2 2
3 7 3 1
4 8 4 1
(Keep in mind that you might need to order/sort before, depending on your data)
EDIT: As mentioned by the questioner, use df.groupby('id').head(2).reset_index(drop=True)
to remove the multindex and flatten the results.
>>> df.groupby('id').head(2).reset_index(drop=True)
id value
0 1 1
1 1 2
2 2 1
3 2 2
4 3 1
5 4 1
I wrote this tool for retrieving Instagram IDs by username: Instagram User ID Lookup.
It utilizes the python-instagram library to access the API and includes a link to the source code (written on Django), which illustrates various implementations of the Instagram API.
Update: Added source code for port to Ruby on Rails.
A Date
object has no format, it is a representation. The date can be presented by a String
with the format you like.
E.g. "yyyy-MM-dd
", "yy-MMM-dd
", "dd-MMM-yy
" and etc.
To acheive this you can get the use of the SimpleDateFormat
Try this,
String inputString = "19/05/2009"; // i.e. (dd/MM/yyyy) format
SimpleDateFormat fromUser = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd");
try {
Date dateFromUser = fromUser.parse(inputString); // Parse it to the exisitng date pattern and return Date type
String dateMyFormat = myFormat.format(dateFromUser); // format it to the date pattern you prefer
System.out.println(dateMyFormat); // outputs : 2009-05-19
} catch (ParseException e) {
e.printStackTrace();
}
This outputs : 2009-05-19
If you go the brew route, the best way to install would be:
brew install macvim --with-override-system-vim
That will provide mvim, vim, vi, view, etc. in /usr/local/bin (all symlinked to the copy in the Cellar). This also removes the need to create any aliases and also changes your vi, vim, etc. to all use the same Vim distribution as your MacVim.
A different approach that I found ugly compared to the classic dict+append, but that works:
df = df.T
df[0] = ['1/1/2013', 'Smith','test',123]
df = df.T
df
Out[6]:
Date Name Action ID
0 1/1/2013 Smith test 123
Declare a SecondActivity variable in FirstActivity
Like this
public class FirstActivity extends Activity {
SecondActivity secactivity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
}
public void method() {
// some code
secactivity.call_method();// 'Method' is Name of the any one method in SecondActivity
}
}
Using this format you can call any method from one activity to another.
if is bootstrap 3 you can use:
$("#mimodal").on('hidden.bs.modal', function () {
$(this).data('bs.modal', null);
});
$('document').ready(function () {
$("#imgload").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imgshow').attr('src', e.target.result);
}
reader.readAsDataURL(this.files[0]);
}
});
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="imgload" >
<img src="#" id="imgshow" align="left">
_x000D_
That works for me in jQuery.
Even if that's a 7 years old question, people new to R should consider using the data.table, package.
A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.
vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]
In Python 3.3, added new method timestamp
:
import datetime
seconds_since_epoch = datetime.datetime.now().timestamp()
Your question stated that you needed milliseconds, which you can get like this:
milliseconds_since_epoch = datetime.datetime.now().timestamp() * 1000
If you use timestamp
on a naive datetime object, then it assumed that it is in the local timezone. Use timezone-aware datetime objects if this is not what you intend to happen.
USE MyUrlEncode.URLencoding(String url , String enc) to handle the problem
public class MyUrlEncode {
static BitSet dontNeedEncoding = null;
static final int caseDiff = ('a' - 'A');
static {
dontNeedEncoding = new BitSet(256);
int i;
for (i = 'a'; i <= 'z'; i++) {
dontNeedEncoding.set(i);
}
for (i = 'A'; i <= 'Z'; i++) {
dontNeedEncoding.set(i);
}
for (i = '0'; i <= '9'; i++) {
dontNeedEncoding.set(i);
}
dontNeedEncoding.set('-');
dontNeedEncoding.set('_');
dontNeedEncoding.set('.');
dontNeedEncoding.set('*');
dontNeedEncoding.set('&');
dontNeedEncoding.set('=');
}
public static String char2Unicode(char c) {
if(dontNeedEncoding.get(c)) {
return String.valueOf(c);
}
StringBuffer resultBuffer = new StringBuffer();
resultBuffer.append("%");
char ch = Character.forDigit((c >> 4) & 0xF, 16);
if (Character.isLetter(ch)) {
ch -= caseDiff;
}
resultBuffer.append(ch);
ch = Character.forDigit(c & 0xF, 16);
if (Character.isLetter(ch)) {
ch -= caseDiff;
}
resultBuffer.append(ch);
return resultBuffer.toString();
}
private static String URLEncoding(String url,String enc) throws UnsupportedEncodingException {
StringBuffer stringBuffer = new StringBuffer();
if(!dontNeedEncoding.get('/')) {
dontNeedEncoding.set('/');
}
if(!dontNeedEncoding.get(':')) {
dontNeedEncoding.set(':');
}
byte [] buff = url.getBytes(enc);
for (int i = 0; i < buff.length; i++) {
stringBuffer.append(char2Unicode((char)buff[i]));
}
return stringBuffer.toString();
}
private static String URIEncoding(String uri , String enc) throws UnsupportedEncodingException { //?????????
StringBuffer stringBuffer = new StringBuffer();
if(dontNeedEncoding.get('/')) {
dontNeedEncoding.clear('/');
}
if(dontNeedEncoding.get(':')) {
dontNeedEncoding.clear(':');
}
byte [] buff = uri.getBytes(enc);
for (int i = 0; i < buff.length; i++) {
stringBuffer.append(char2Unicode((char)buff[i]));
}
return stringBuffer.toString();
}
public static String URLencoding(String url , String enc) throws UnsupportedEncodingException {
int index = url.indexOf('?');
StringBuffer result = new StringBuffer();
if(index == -1) {
result.append(URLEncoding(url, enc));
}else {
result.append(URLEncoding(url.substring(0 , index),enc));
result.append("?");
result.append(URIEncoding(url.substring(index+1),enc));
}
return result.toString();
}
}
I made this codepen to help you out!
const navbar = document.querySelector('#nav')
window.addEventListener('scroll', function(e) {
const lastPosition = window.scrollY
if (lastPosition > 50 ) {
navbar.classList.add('active')
} else if (navbar.classList.contains('active')) {
navbar.classList.remove('active')
} else {
navbar.classList.remove('active')
}
})
If you had your array like this: #!/bin/bash
Unix[0]='Debian'
Unix[1]="Red Hat"
Unix[2]='Ubuntu'
Unix[3]='Suse'
for i in $(echo ${Unix[@]});
do echo $i;
done
You would get:
Debian
Red
Hat
Ubuntu
Suse
I don't know why but the loop breaks down the spaces and puts them as an individual item, even you surround it with quotes.
To get around this, instead of calling the elements in the array, you call the indexes, which takes the full string thats wrapped in quotes. It must be wrapped in quotes!
#!/bin/bash
Unix[0]='Debian'
Unix[1]='Red Hat'
Unix[2]='Ubuntu'
Unix[3]='Suse'
for i in $(echo ${!Unix[@]});
do echo ${Unix[$i]};
done
Then you'll get:
Debian
Red Hat
Ubuntu
Suse
I've got an example working.
Here's how my doc looks:
<html>
<head>
<link rel="stylesheet" href="css/main.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular-resource.min.js"></script>
<script src="js/app.js"></script>
<script src="controllers/ctrls.js"></script>
</head>
<body ng-app="app">
<div id="contnr">
<ng-view></ng-view>
</div>
</body>
</html>
Here's what my partial looks like:
<div id="welcome" ng-controller="Index">
<b>Welcome! Please Login!</b>
<form ng-submit="auth()">
<input class="input login username" type="text" placeholder="username" /><br>
<input class="input login password" type="password" placeholder="password" /><br>
<input class="input login submit" type="submit" placeholder="login!" />
</form>
</div>
Here's what my Ctrl looks like:
app.controller('Index', function($scope, $routeParams, $location){
$scope.auth = function(){
$location.url('/map');
};
});
app is my module:
var app = angular.module('app', ['ngResource']).config(function($routeProvider)...
Hope this is helpful!
renamed some_project.workspace file to some_project.workspace.backup and ran $pod install. It created a new workspace file and the error went away.
SELECT
sc.name +'.'+ ta.name TableName, SUM(pa.rows) RowCnt
FROM
sys.tables ta
INNER JOIN sys.partitions pa
ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC
Read SVNBook | Client Credentials.
With modern SVN you can just run svn auth
to display the list of cached credentials. Don't forget to make sure that you run up-to-date SVN client version because svn auth
was introduced in version 1.9. The last line will specify the path to credential store which by default is %APPDATA%\Subversion\auth
on Windows and ~/.subversion/auth/
on Unix-like systems.
PS C:\Users\MyUser> svn auth
------------------------------------------------------------------------
Credential kind: svn.simple
Authentication realm: <https://svn.example.local:443> VisualSVN Server
Password cache: wincrypt
Password: [not shown]
Username: user
Credentials cache in 'C:\Users\MyUser\AppData\Roaming\Subversion' contains 5 credentials
I would use "du" instead.
$ cat files.txt | xargs du -c | tail -1
4480 total
If you just want the number:
cat files.txt | xargs du -c | tail -1 | awk '{print $1}'
In a decorator method, you can list arguments of the original method in this way:
import inspect, itertools
def my_decorator():
def decorator(f):
def wrapper(*args, **kwargs):
# if you want arguments names as a list:
args_name = inspect.getargspec(f)[0]
print(args_name)
# if you want names and values as a dictionary:
args_dict = dict(itertools.izip(args_name, args))
print(args_dict)
# if you want values as a list:
args_values = args_dict.values()
print(args_values)
If the **kwargs
are important for you, then it will be a bit complicated:
def wrapper(*args, **kwargs):
args_name = list(OrderedDict.fromkeys(inspect.getargspec(f)[0] + kwargs.keys()))
args_dict = OrderedDict(list(itertools.izip(args_name, args)) + list(kwargs.iteritems()))
args_values = args_dict.values()
Example:
@my_decorator()
def my_function(x, y, z=3):
pass
my_function(1, y=2, z=3, w=0)
# prints:
# ['x', 'y', 'z', 'w']
# {'y': 2, 'x': 1, 'z': 3, 'w': 0}
# [1, 2, 3, 0]
The old fashion emacs bindings can still work in iterm2 and os x terminal:
Preferences -> Profiles -> Keys (sub tab in profiles)
Left/Right option <kbd>?</kbd> key acts as +Esc
(similar in os x terminal)This should enable alt-f and alt-b for moving words by words. (Still ctrl-a and ctrl-e always work as usual)
If set as meta
those old bindings will work while some iterm2 bindings unavailable.
There might be a fix to <input type="button">
- but if there is, I don't know it.
Otherwise, a good option seems to be to replace it with a carefully styled a
element.
Example: http://jsfiddle.net/Uka5v/
.button {
background-color: #E3E1B8;
padding: 2px 4px;
font: 13px sans-serif;
text-decoration: none;
border: 1px solid #000;
border-color: #aaa #444 #444 #aaa;
color: #000
}
Upsides include that the a
element will style consistently between different (older) versions of Internet Explorer without any extra work, and I think my link looks nicer than that button :)
Create a reverse dictionary using the calendar
module (which, like any module, you will need to import):
{month: index for index, month in enumerate(calendar.month_abbr) if month}
In Python versions before 2.7, due to dict comprehension syntax not being supported in the language, you would have to do
dict((month, index) for index, month in enumerate(calendar.month_abbr) if month)
Unfortunately, AFAIK you cannot run multiple SQL statements under one named query in Access in the traditional sense.
You can make several queries, then string them together with VBA (DoCmd.OpenQuery
if memory serves).
You can also string a bunch of things together with UNION if you wish.
From http://www.dba-oracle.com/t_isnumeric.htm
LENGTH(TRIM(TRANSLATE(, ' +-.0123456789', ' '))) is null
If there is anything left in the string after the TRIM it must be non-numeric characters.
I had the same problem with fb and twitter caching old meta data, this threw me for a curve as I continued to edit the code but no change. I finally discovered they had caching my first request. Adding a query string to the url worked for twitter but not fb(for me).
you can use preg_grep()
:
$a= array(
'one',
'two',
'three',
'four'
);
print_r( preg_grep( "/ONe/i" , $a ) );
The modern solution is an input field of type "search"!
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search https://www.w3schools.com/tags/tag_datalist.asp
Somewhere in your HTML you define a datalist for later reference:
<datalist id="mylist">
<option value="Option 1">
<option value="Option 2">
<option value="Option 3">
</datalist>
Then you can define your search input like this:
<input type="search" list="mylist">
Voilà. Very nice and easy.
To preselect an option when the form is initialized, the value of the select element must be set to an element attribute of the array you are iterating over and setting the value of option to. Which is the key attribute in this case.
From your example.
<select [id]="question.key" [formControlName]="question.key">
<option *ngFor="let opt of question.options" [value]="opt.key"</option>
</select>
You are iterating over 'options' to create the select options. So the value of select must be set to the key attribute of an item in options(the one you want to display on initialization). This will display the default of select as the option whose value matches the value you set for select.
You can achieve this by setting the value of the select element in the onInit method like so.
ngOnInit(): void{
myForm : new FormGroup({
...
question.key : new FormControl(null)
})
// Get desired initial value to display on <select>
desiredValue = question.options.find(opt => opt === initialValue)
this.myForm.get(question.key).setValue(desiredValue.key)
}
If you (or other searchers of this question) were actually interested in creating a contiguous array to fill with integers, consider bytearray and memoryivew:
# cast() is available starting Python 3.3
size = 10**6
ints = memoryview(bytearray(size)).cast('i')
ints.contiguous, ints.itemsize, ints.shape
# (True, 4, (250000,))
ints[0]
# 0
ints[0] = 16
ints[0]
# 16
As far as I understand, it's impossible to have it (because it would conflict with the default constructor - am I right?)
You are wrong. It doesn't conflict in any way. You just can't call it ever.
If your page does not modify any session variables, you can opt out of most of this lock.
<% @Page EnableSessionState="ReadOnly" %>
If your page does not read any session variables, you can opt out of this lock entirely, for that page.
<% @Page EnableSessionState="False" %>
If none of your pages use session variables, just turn off session state in the web.config.
<sessionState mode="Off" />
I'm curious, what do you think "a ThreadSafe collection" would do to become thread-safe, if it doesn't use locks?
Edit: I should probably explain by what I mean by "opt out of most of this lock". Any number of read-only-session or no-session pages can be processed for a given session at the same time without blocking each other. However, a read-write-session page can't start processing until all read-only requests have completed, and while it is running it must have exclusive access to that user's session in order to maintain consistency. Locking on individual values wouldn't work, because what if one page changes a set of related values as a group? How would you ensure that other pages running at the same time would get a consistent view of the user's session variables?
I would suggest that you try to minimize the modifying of session variables once they have been set, if possible. This would allow you to make the majority of your pages read-only-session pages, increasing the chance that multiple simultaneous requests from the same user would not block each other.
This disables the script errors and also disables other windows.. such as the NTLM login window or the client certificate accept window. The below will suppress only javascript errors.
// Hides script errors without hiding other dialog boxes.
private void SuppressScriptErrorsOnly(WebBrowser browser)
{
// Ensure that ScriptErrorsSuppressed is set to false.
browser.ScriptErrorsSuppressed = false;
// Handle DocumentCompleted to gain access to the Document object.
browser.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(
browser_DocumentCompleted);
}
private void browser_DocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
((WebBrowser)sender).Document.Window.Error +=
new HtmlElementErrorEventHandler(Window_Error);
}
private void Window_Error(object sender,
HtmlElementErrorEventArgs e)
{
// Ignore the error and suppress the error dialog box.
e.Handled = true;
}
You could mask the problem by turning off errorOnUnhandledRejections, but the error says you're needing to "handle a possible rejection" so you just need to add a catch to your promise.
resource.get().$promise
.then(function (response) {
// do something with the response
}).catch(function (error)) {
// pass the error to the error service
return errorService.handleError(error);
});
Reference: https://github.com/angular-ui/ui-router/issues/2889
First of all, I suggest that you narrow the problem to which component throws the "Out of Memory Exception".
This could be:
The JVM parameters -xms
and -xmx
represent the heap's "start memory" and the "maximum memory". Forget the "start memory". This is not going to help you now and you should only change this parameter if you're sure your app will consume this amount of memory rapidly.
In production, I think the only parameter that you can change is the -xmx
under the Catalina.sh or Catalina.bat files. But if you are testing your webapp directly from Eclipse with a configured debug environment of Tomcat, you can simply go to your "Debug Configurations" > "Apache Tomcat" > "Arguments" > "VM arguments" and set the -xmx
there.
As for the optimal -xmx
for 2gb, this depends a lot of your environment and the number of requests your app might take. I would try values from 500mb up to 1gb. Check your OS virtual memory "zone" limit and the limit of the JVM itself.
If you want to send emails simultaneously to all the admins, you can do something like this:
In your .env file add all the emails as comma separated values:
[email protected],[email protected],[email protected]
so when you going to send the email just do this (yes! the 'to' method of message builder instance accepts an array):
So,
$to = explode(',', env('ADMIN_EMAILS'));
and...
$message->to($to);
will now send the mail to all the admins.
You can use -m -c -r to make migration, model and controller.
php artisan make:model Post -m -c -r
Windows 10:
open cmd
change directory where you want to create text file(movie_list.txt) for the folder (d:\videos\movies)
type following command
d:\videos\movies> dir /b /a-d > movie_list.txt
If you want to check on the object itself without interfering with the prototype, use hasOwnProperty()
:
var getIndexIfObjWithOwnAttr = function(array, attr, value) {
for(var i = 0; i < array.length; i++) {
if(array[i].hasOwnProperty(attr) && array[i][attr] === value) {
return i;
}
}
return -1;
}
to also include prototype attributes, use:
var getIndexIfObjWithAttr = function(array, attr, value) {
for(var i = 0; i < array.length; i++) {
if(array[i][attr] === value) {
return i;
}
}
return -1;
}
for springboot 2.1.7 working with url seems not to work. change with jdbcUrl instead.
In properties:
security:
datasource:
jdbcUrl: jdbc:mysql://ip:3306/security
username: user
password: pass
In java:
@ConfigurationProperties(prefix = "security.datasource")
@Bean("dataSource")
@Primary
public DataSource dataSource(){
return DataSourceBuilder
.create()
.build();
}
Use forEach its a built-in array function. Array.forEach()
:
yourArray.forEach(function (arrayItem) {
var x = arrayItem.prop1 + 2;
console.log(x);
});
As AraK said, the c++ streams interface will always work portably.
std::size_t s = 1024; std::cout << s; // or any other kind of stream like stringstream!
If you want C stdio, there is no portable answer to this for certain cases of "portable." And it gets ugly since as you've seen, picking the wrong format flags may yield a compiler warning or give incorrect output.
C99 tried to solve this problem with inttypes.h formats like "%"PRIdMAX"\n". But just as with "%zu", not everyone supports c99 (like MSVS prior to 2013). There are "msinttypes.h" files floating around to deal with this.
If you cast to a different type, depending on flags you may get a compiler warning for truncation or a change of sign. If you go this route pick a larger relevant fixed size type. One of unsigned long long and "%llu" or unsigned long "%lu" should work, but llu may also slow things down in a 32bit world as excessively large. (Edit - my mac issues a warning in 64 bit for %llu not matching size_t, even though %lu, %llu, and size_t are all the same size. And %lu and %llu are not the same size on my MSVS2012. So you may need to cast + use a format that matches.)
For that matter, you can go with fixed size types, such as int64_t. But wait! Now we're back to c99/c++11, and older MSVS fails again. Plus you also have casts (e.g. map.size() is not a fixed size type)!
You can use a 3rd party header or library such as boost. If you're not already using one, you may not want to inflate your project that way. If you're willing to add one just for this issue, why not use c++ streams, or conditional compilation?
So you're down to c++ streams, conditional compilation, 3rd party frameworks, or something sort of portable that happens to work for you.
One caveat to many of these answers: if you alias your controller your scope objects will be in an object within the returned object from scope()
.
For example, if your controller directive is created like so:
<div ng-controller="FormController as frm">
then to access a startDate
property of your controller, you would call angular.element($0).scope().frm.startDate
Use REPLACE:
SELECT REPLACE(t.column, 'est1', 'rest1')
FROM MY_TABLE t
If you want to update the values in the table, use:
UPDATE MY_TABLE t
SET column = REPLACE(t.column, 'est1', 'rest1')
Your JSON object in this case is a list. JSON is almost always an object with attributes; a set of one or more key:value pairs, so you most likely see a dictionary:
{ "MyStringArray" : ["somestring1", "somestring2"] }
then you can ask for the value of "MyStringArray"
and you would get back a list of two strings, "somestring1"
and "somestring2"
.
I got here looking for a way to add a key/value pair(s) as a group - in my case it was the output of a function call, so adding the pair using dictionary[key] = value
would require me to know the name of the key(s).
In this case, you can use the update method:
dictionary.update(function_that_returns_a_dict(*args, **kwargs)))
Beware, if dictionary
already contains one of the keys, the original value will be overwritten.
Another way to fix this would be to go to the properties of the server on eclipse (right click on server -> properties) In general tab you would see location as workspace.metadata. Click on switch location.
change your Production.rb file line
config.assets.compile = false
into
config.assets.compile = true
and also add
config.assets.precompile = ['*.js', '*.css', '*.css.erb']
Label's aren't form elements. They don't have a value
. They have innerHTML
and textContent
.
Thus,
$('#telefon').html()
// or
$('#telefon').text()
or
var telefon = document.getElementById('telefon');
telefon.innerHTML;
If you are starting with your form element, check out the labels
list of it. That is,
var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea
If X
and beta
do not have the same shape as the second term in the rhs of your last line (i.e. nsample
), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.
I would recommend looking at the numpy broadcasting rules.
I have netbeans 6.9.1 open right now and ALT+SHIFT+F indents only the lines you have selected.
If no lines are selected then it will indent the whole document you are in.
1 possibly unintended behavior is that if you have selected ONLY 1 line, it must be selected completely, otherwise it does nothing. But you don't have to completely select the last line of a group nor the first.
I expected it to indent only one line by just selecting the first couple of chars but didn't work, yea i know i am lazy as hell...
You could capture the (2001)
part and replace the rest with nothing.
public static string extractYearString(string input) {
return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}
var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"
.*\(([0-9]{4})\).*
means
.*
match anything\(
match a (
character(
begin capture[0-9]{4}
any single digit four times)
end capture\)
match a )
character.*
anything (rest of string)In case you want send your custom headers, you can do it this way:
curl -v -H @{'custom_header'='custom_header_value'} http://localhost:3000/action?result1=gh&result2=ghk
With the latest NodeJS you can experiment with this monkey patch:
const http = require("http");
const originalOnSocket = http.ClientRequest.prototype.onSocket;
require("http").ClientRequest.prototype.onSocket = function(socket) {
const that = this;
socket.setTimeout(this.timeout ? this.timeout : 3000);
socket.on('timeout', function() {
that.abort();
});
originalOnSocket.call(this, socket);
};
What's the default superuser username/password for postgres after a new install?:
CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!
This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.
What you should do is follow Chris James's answer:
sudo -u postgres psql postgres # \password postgres Enter new password:
To explain it a little bit...
Very strange that the very convenient
M-x eval-buffer
is not mentioned here.
It immediately evaluates all code in the buffer, its the quickest method, if your .emacs
is idempotent.
//It work in Chrome and IE ... I reviewed and readed a lot of answer. then i used it and tested in both ...
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var blob = new Blob([CSV], { type: 'text/csv;charset=utf-8;' });
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", fileName);
link.style = "visibility:hidden";
}
if (navigator.msSaveBlob) { // IE 10+
link.addEventListener("click", function (event) {
var blob = new Blob([CSV], {
"type": "text/csv;charset=utf-8;"
});
navigator.msSaveBlob(blob, fileName);
}, false);
}
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
//Regards
I had this issue on Android 10,
Changed targetSdkVersion 29
to targetSdkVersion 28
issue resolved. Not sure what is the actual problem.
I think not a good practice, but it worked.
before:
compileSdkVersion 29
minSdkVersion 14
targetSdkVersion 29
Now:
compileSdkVersion 29
minSdkVersion 14
targetSdkVersion 28
Logically it does not work and you should reverse your loop:
for (int i = position-1; i >= 0; i--) {
array[i+1] = array[i];
}
Alternatively you can use
System.arraycopy(array, 0, array, 1, position);
A python script from Sergiy Kolodyazhnyy posted on Copy only folders not files?:
#!/usr/bin/env python
import os,sys
dirs=[ r for r,s,f in os.walk(".") if r != "."]
for i in dirs:
os.makedirs(os.path.join(sys.argv[1],i))
or from the shell:
python -c 'import os,sys;dirs=[ r for r,s,f in os.walk(".") if r != "."];[os.makedirs(os.path.join(sys.argv[1],i)) for i in dirs]' ~/new_destination
FYI:
You can put the username() function in another page, and send the form to that page...
I just found out about hyphenator from this question. That might solve the problem.
Use Arrays.asList
:
if( Arrays.asList("a","b","c").contains("a") )
Your Gemfile has a line reading
ruby '2.2.5'
Change it to
ruby '2.3.0'
Then run
bundle install
With the excellent matplotlib
and numpy
packages
from matplotlib import pyplot as mp
import numpy as np
def gaussian(x, mu, sig):
return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))
x_values = np.linspace(-3, 3, 120)
for mu, sig in [(-1, 1), (0, 2), (2, 3)]:
mp.plot(x_values, gaussian(x_values, mu, sig))
mp.show()
Property order in normal Objects is a complex subject in Javascript.
While in ES5 explicitly no order has been specified, ES2015 has an order in certain cases. Given is the following object:
o = Object.create(null, {
m: {value: function() {}, enumerable: true},
"2": {value: "2", enumerable: true},
"b": {value: "b", enumerable: true},
0: {value: 0, enumerable: true},
[Symbol()]: {value: "sym", enumerable: true},
"1": {value: "1", enumerable: true},
"a": {value: "a", enumerable: true},
});
This results in the following order (in certain cases):
Object {
0: 0,
1: "1",
2: "2",
b: "b",
a: "a",
m: function() {},
Symbol(): "sym"
}
Thus, there are three segments, which may alter the insertion order (as happened in the example). And integer-like keys don't stick to the insertion order at all.
The question is, for what methods this order is guaranteed in the ES2015 spec?
The following methods guarantee the order shown:
The following methods/loops guarantee no order at all:
Conclusion: Even in ES2015 you shouldn't rely on the property order of normal objects in Javascript. It is prone to errors. Use Map
instead.
This is my working solution
View view = new View(getApplicationContext());
view.setBackgroundResource(R.color.background);
myEditText.setBackground(view.getBackground());
One of the best examples of Hadoop-like MapReduce implementation.
Keep in mind though that they are limited to key-value based implementations of the MapReduce idea (so they are limiting in applicability).
MySqldb python install windows
MySQL-python 1.2.3 for Windows and Python 2.7, 32bit and 64bit versions
@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ")
private WebElementFacade emailLinkToVerifyAccount;
This approach will work for you, hopefully.
Bellow code working as fine, when we don't know identity column name.
Need to copy data into new temp table like Invoice_DELETED
.
and next time we using:
insert into Invoice_DELETED select * from Invoice where ...
SELECT t1.*
INTO Invoice_DELETED
FROM Invoice t1
LEFT JOIN Invoice ON 1 = 0
--WHERE t1.InvoiceID = @InvoiceID
For more explanation see: https://dba.stackexchange.com/a/138345/101038
As with DATEDIFF, I do not consider the end date to be part of the interval. The number of (for example) Sundays between @StartDate and @EndDate is the number of Sundays between an "initial" Monday and the @EndDate minus the number of Sundays between this "initial" Monday and the @StartDate. Knowing this, we can calculate the number of workdays as follows:
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2018/01/01'
SET @EndDate = '2019/01/01'
SELECT DATEDIFF(Day, @StartDate, @EndDate) -- Total Days
- (DATEDIFF(Day, 0, @EndDate)/7 - DATEDIFF(Day, 0, @StartDate)/7) -- Sundays
- (DATEDIFF(Day, -1, @EndDate)/7 - DATEDIFF(Day, -1, @StartDate)/7) -- Saturdays
Best regards!
There are multiple options to set variables in Hive.
If you're looking to set Hive variable from inside the Hive shell, you can set it using hivevar
. You can set string or integer datatypes. There are no problems with them.
SET hivevar:which_date=20200808;
select ${which_date};
If you're planning to set variables from shell script and want to pass those variables into your Hive script (HQL) file, you can use --hivevar
option while calling hive or beeline command.
# shell script will invoke script like this
beeline --hivevar tablename=testtable -f select.hql
-- select.hql file
select * from <dbname>.${tablename};
From xaml code you can call a predefined SystemCommand:
Command="SystemCommands.MinimizeWindowCommand"
I think this should be the prefered way...
Response.Redirect()
throws an exception to abort the current request.
This KB article describes this behavior (also for the Request.End()
and Server.Transfer()
methods).
For Response.Redirect()
there exists an overload:
Response.Redirect(String url, bool endResponse)
If you pass endResponse=false, then the exception is not thrown (but the runtime will continue processing the current request).
If endResponse=true (or if the other overload is used), the exception is thrown and the current request will immediately be terminated.
You need the :not()
selector:
$('div[class^="first-"]:not(.first-bar)')
or, alternatively, the .not()
method:
$('div[class^="first-"]').not('.first-bar');
What about this? A javascript - CSS3 free solution.
http://jsfiddle.net/u1aks77x/1/
ul{}
li{float:left; list-style-type:none; }
a{position:relative; padding-right: 10px; text-decoration:none;}
a > .l1{}
a:hover > .l1{visibility:hidden;}
a:hover > .l2{display:inline;}
a > .l2{position: absolute; left:0; font-weight:bold; display:none;}
<ul>
<li><a href="/" title="Home"><span class="l1">Home</span><span class="l2">Home</span></a></li>
<li><a href="/" title="Contact"><span class="l1">Contact</span><span class="l2">Contact</span></a></li>
<li><a href="/" title="Sitemap"><span class="l1">Sitemap</span><span class="l2">Sitemap</span></a></li>
</ul>
DroidParts has ImageFetcher that requires zero configuration to get started.
Clone DroidPartsGram for an example:
Using gson it is much simpler. Use following code snippet:
// create a new Gson instance
Gson gson = new Gson();
// convert your list to json
String jsonCartList = gson.toJson(cartList);
// print your generated json
System.out.println("jsonCartList: " + jsonCartList);
// Converts JSON string into a List of Product object
Type type = new TypeToken<List<Product>>(){}.getType();
List<Product> prodList = gson.fromJson(jsonCartList, type);
// print your List<Product>
System.out.println("prodList: " + prodList);
If you want to make transformation your app setting from web config file to web.Release.config,you have to do the following steps. Let your web.config app setting file is this-
<appSettings>
<add key ="K1" value="Debendra Dash"/>
</appSettings>
Now here is the web.Release.config for the transformation.
<appSettings>
<add key="K1" value="value dynamicly from Realease"
xdt:Transform="SetAttributes"
xdt:Locator="Match(key)"
/>
</appSettings>
This will transform the value of K1 to the new value in realese Mode.
var x = "somestring"
alert(x.charAt(0));
The charAt() method allows you to specify the position of the character you want.
What you were trying to do is get the character at the position of an array "x", which is not defined as X is not an array.
I don't think that's possible, you could fake it with double parens ... just as long you don't need the arguments individually.
#define macro(ARGS) some_complicated (whatever ARGS)
// ...
macro((a,b,c))
macro((d,e))
In some cases the whole need for declaring a variable can be avoided by using With
statement.
For example,
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogSaveAs)
If fd.Show Then
'use fd.SelectedItems(1)
End If
this can be rewritten as
With Application.FileDialog(msoFileDialogSaveAs)
If .Show Then
'use .SelectedItems(1)
End If
End With
The raw info is in pg_index.
It can also be done with isinstance
as per Alex Hall's answer :
>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True
isinstance
is also intuitive but there is the complication that it requires the line
NoneType = type(None)
which isn't needed for types like int
and float
.
The compiler wants to know the function before it can use it
just declare the function before you call it
#include <stdio.h>
int Fibonacci(int number); //now the compiler knows, what the signature looks like. this is all it needs for now
int main(int argc, const char * argv[])
{
int input;
printf("Please give me a number : ");
scanf("%d", &input);
getchar();
printf("The fibonacci number of %d is : %d", input, Fibonacci(input)); //!!!
}/* main */
int Fibonacci(int number)
{
//…
Swift 5 answer based on @ZpaceZombor's excellent answer
If you have a UIImage, just use
var image: UIImage = ....
image.draw(in: CGRect)
If you have a CGImage use my category below
Note: Unlike some other answers, this one takes into account that the rect you want to draw in might have y != 0. Those answers that don't take that into account are incorrect and won't work in the general case.
extension CGContext {
final func drawImage(image: CGImage, inRect rect: CGRect) {
//flip coords
let ty: CGFloat = (rect.origin.y + rect.size.height)
translateBy(x: 0, y: ty)
scaleBy(x: 1.0, y: -1.0)
//draw image
let rect__y_zero = CGRect(x: rect.origin.x, y: 0, width: rect.width, height: rect.height)
draw(image, in: rect__y_zero)
//flip back
scaleBy(x: 1.0, y: -1.0)
translateBy(x: 0, y: -ty)
}
}
Use like this:
let imageFrame: CGRect = ...
let context: CGContext = ....
let img: CGImage = .....
context.drawImage(image: img, inRect: imageFrame)
When using postgres you can use the DISTINCT ON
syntex to limit the number of columns returned from either table.
Here is a sample of the code:
SELECT c.id, c.title, p.id AS product_id, p.title
FROM categories AS c
JOIN (
SELECT DISTINCT ON(p1.id) id, p1.title, p1.category_id
FROM products p1
) p ON (c.id = p.category_id)
The trick is not to join directly on the table with multiple occurrences of the id, rather, first create a table with only a single occurrence for each id
this should work
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
I had to do a :
git checkout -b master
as git said that it doesn't exists, because it's been wipe with the
git -D master
You code should look like this:
public int getElement(int[] arrayOfInts, int index) {
return arrayOfInts[index];
}
Main points here are method return type, it should match with array elements type and if you are working from main()
- this method must be static also.
Normally it happens when the target is null. So better check the invoke target first then do the linq query.
First you use startActivityForResult()
with parameters in first Activity
and if you want to send data from second Activity
to first Activity
then pass value using Intent
with setResult()
method and get that data inside onActivityResult()
method in first Activity
.
iOS 8 has changed notification registration in a non-backwards compatible way. While you need to support iOS 7 and 8 (and while apps built with the 8 SDK aren't accepted), you can check for the selectors you need and conditionally call them correctly for the running version.
Here's a category on UIApplication that will hide this logic behind a clean interface for you that will work in both Xcode 5 and Xcode 6.
Header:
//Call these from your application code for both iOS 7 and 8
//put this in the public header
@interface UIApplication (RemoteNotifications)
- (BOOL)pushNotificationsEnabled;
- (void)registerForPushNotifications;
@end
Implementation:
//these declarations are to quiet the compiler when using 7.x SDK
//put this interface in the implementation file of this category, so they are
//not visible to any other code.
@interface NSObject (IOS8)
- (BOOL)isRegisteredForRemoteNotifications;
- (void)registerForRemoteNotifications;
+ (id)settingsForTypes:(NSUInteger)types categories:(NSSet*)categories;
- (void)registerUserNotificationSettings:(id)settings;
@end
@implementation UIApplication (RemoteNotifications)
- (BOOL)pushNotificationsEnabled
{
if ([self respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
return [self isRegisteredForRemoteNotifications];
}
else
{
return ([self enabledRemoteNotificationTypes] & UIRemoteNotificationTypeAlert);
}
}
- (void)registerForPushNotifications
{
if ([self respondsToSelector:@selector(registerForRemoteNotifications)])
{
[self registerForRemoteNotifications];
Class uiUserNotificationSettings = NSClassFromString(@"UIUserNotificationSettings");
//If you want to add other capabilities than just banner alerts, you'll need to grab their declarations from the iOS 8 SDK and define them in the same way.
NSUInteger UIUserNotificationTypeAlert = 1 << 2;
id settings = [uiUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert categories:[NSSet set]];
[self registerUserNotificationSettings:settings];
}
else
{
[self registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert];
}
}
@end
You have to cast the selected item to your custom class (ComboboxItem) Try this:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ComboBox cmb = (ComboBox)sender;
int selectedIndex = cmb.SelectedIndex;
string selectedText = this.comboBox1.Text;
string selectedValue = ((ComboboxItem)cmb.SelectedItem).Value.ToString();
ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));
}
my 2cents: start with table with highest fragmentation
for table in `mysql -sss -e "select concat(table_schema,".",table_name) from information_schema.tables where table_schema not in ('mysql','information_schema','performance_schema') order by data_free desc;"
do
mysql -e "OPTIMIZE TABLE $table;"
done
To me this worked.
CREATE USER 'spowner'@'localhost' IDENTIFIED BY '1234';
GRANT ALL PRIVILEGES ON test.* To 'spowner'@'localhost';
FLUSH PRIVILEGES;
where
Traversing the string is probably the most efficient, though using Regex to do this might yield cleaner looking code (though you can always hide your traverse code in a function).
$("input[type='number']").bind("focus", function() {
var value = $(this).val();
$(this).bind("blur", function() {
if(value != $(this).val()) {
alert("Value changed");
}
$(this).unbind("blur");
});
});
OR
$("input[type='number']").bind("input", function() {
alert("Value changed");
});
You should not try to use perfmon, task manager or any tool like that to determine memory leaks. They are good for identifying trends, but not much else. The numbers they report in absolute terms are too vague and aggregated to be useful for a specific task such as memory leak detection.
A previous reply to this question has given a great explanation of what the various types are.
You ask about a tool recommendation: I recommend Memory Validator. Capable of monitoring applications that make billions of memory allocations.
http://www.softwareverify.com/cpp/memory/index.html
Disclaimer: I designed Memory Validator.
Er ... how about in a boolean function to indicate 'not true'?
What you're looking for is called a watchpoint.
Usage
(gdb) watch foo
: watch the value of variable foo
(gdb) watch *(int*)0x12345678
: watch the value pointed by an address, casted to whatever type you want
(gdb) watch a*b + c/d
: watch an arbitrarily complex expression, valid in the program's native language
Watchpoints are of three kinds:
You may choose the more appropriate for your needs.
For more information, check this out.
Yes, you can commit this file. From the npm's official docs:
package-lock.json
is automatically generated for any operations wherenpm
modifies either thenode_modules
tree, orpackage.json
. It describes the exact tree that was generated, such that subsequent installs are able to generate identical trees, regardless of intermediate dependency updates.This file is intended to be committed into source repositories[.]
Use this with WPF:
Cursor = Cursors.Wait;
// Your Heavy work here
Cursor = Cursors.Arrow;
Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want
x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)
WORD.C <- function(WORDS){
require(wordcloud)
L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))
# Takes a dataframe and the text you want to display
FUN <- function(X, text){
windows()
wordcloud(X[, 1], X[, 2], min.freq=1)
mtext(text, 3, padj=-4.5, col="red") #what I'm trying that isn't working
}
# Now creates the sequence 1,...,length(L2)
# Loops over that and then create an anonymous function
# to send in the information you want to use.
lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})
# Since you asked about loops
# you could use i in seq_along(L2)
# instead of 1:length(L2) if you wanted to
#for(i in 1:length(L2)){
# FUN(L2[[i]], names(L2)[i])
#}
}
WORD.C(list.xy)
Here's some code that might do the trick for you (taken from Ryan Farley's blog)
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
The solution was as simple as adding plt.show()
at the end of the code snippet:
import numpy as np
np.random.seed(123)
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.datasets import mnist
(X_train,y_train),(X_test,y_test) = mnist.load_data()
print X_train.shape
from matplotlib import pyplot as plt
plt.imshow(X_train[0])
plt.show()
This example made everything clear for me:
As you can see setSoTimeout prevent the program to hang! It wait for SO_TIMEOUT
time! if it does not get any signal it throw exception! It means that time expired!
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class SocketTest extends Thread {
private ServerSocket serverSocket;
public SocketTest() throws IOException {
serverSocket = new ServerSocket(8008);
serverSocket.setSoTimeout(10000);
}
public void run() {
while (true) {
try {
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
Socket client = serverSocket.accept();
System.out.println("Just connected to " + client.getRemoteSocketAddress());
client.close();
} catch (SocketTimeoutException s) {
System.out.println("Socket timed out!");
break;
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public static void main(String[] args) {
try {
Thread t = new SocketTest();
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below
e.g.
Exec N'Select bla..'
the N defines string literal is unicode.
You have an array of L.Marker:
let markers = [marker1, marker2, marker3]
let latlngs = markers.map(marker => marker.getLatLng())
let latlngBounds = L.latLngBounds(latlngs)
map.fitBounds(latlngBounds)
// OR with a smooth animation
// map.flyToBounds(latlngBounds)
Try this puglin simpleUpload, no need form
Html:
<input type="file" name="arquivo" id="simpleUpload" multiple >
<button type="button" id="enviar">Enviar</button>
Javascript:
$('#simpleUpload').simpleUpload({
url: 'upload.php',
trigger: '#enviar',
success: function(data){
alert('Envio com sucesso');
}
});
In case you prefer to use jQuery to set the image from Base64:
$("#img").attr('src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==');
For dropping all documents in a collection:
myMongooseModel.collection.drop();
as seen in the tests
final int[][] matrix = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Produces:
1 2 3
4 5 6
7 8 9
You can follow the below step to modify the .war file name if you are using maven project.
Open pom.xml file of your maven project and go to the tag <build></build>
,
In that give your desired name between this tag :
<finalName></finalName>
.
ex. : <finalName>krutik</finalName>
After deploying this .war you will be able to access url with:
http://localhost:8080/krutik/
If you want to access the url with slash '/' then you will have to specify then name as below:
e.x. : <finalName>krutik#maheta</finalName>
After deploying this .war you will be able to access url with:
http://localhost:8080/krutik/maheta
NEVER EVER use a selector like DATE(datecolumns) = '2012-12-24'
- it is a performance killer:
DATE()
for all rows, including those, that don't matchIt is much faster to use
SELECT * FROM tablename
WHERE columname BETWEEN '2012-12-25 00:00:00' AND '2012-12-25 23:59:59'
as this will allow index use without calculation.
EDIT
As pointed out by Used_By_Already, in the time since the inital answer in 2012, there have emerged versions of MySQL, where using '23:59:59' as a day end is no longer safe. An updated version should read
SELECT * FROM tablename
WHERE columname >='2012-12-25 00:00:00'
AND columname <'2012-12-26 00:00:00'
The gist of the answer, i.e. the avoidance of a selector on a calculated expression, of course still stands.
yes use \n, unless you are generating html code, in which you want to use <br />
TL; DR: use np.where
as it is the fastest option. Your options are np.where
, itertools.compress
, and list comprehension
.
See the detailed comparison below, where it can be seen np.where
outperforms both itertools.compress
and also list comprehension
.
>>> from itertools import compress
>>> import numpy as np
>>> t = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]`
>>> t = 1000*t
list comprehension
>>> %timeit [i for i, x in enumerate(t) if x]
457 µs ± 1.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
itertools.compress
>>> %timeit list(compress(range(len(t)), t))
210 µs ± 704 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
numpy.where
>>> %timeit np.where(t)
179 µs ± 593 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Now this answer is for those lost souls that got here with this problem because they force-unmounted the drive but their hard drive is NTFS Formatted. Assuming you have ntfs-3g installed (sudo apt-get install ntfs-3g).
sudo ntfs-3g /dev/hdd /mnt/mount_point -o force
Where hdd is the hard drive in question and the "/mnt/mount_point" directory exists.
NOTES: This fixed the issue on an Ubuntu 18.04 machine using NTFS drives that had their journal files reset through sudo ntfsfix /dev/hdd and unmounted by force using sudo umount -l /mnt/mount_point
Leaving my answer here in case this fix can aid anyone!
:goto 21490
will take you to the 21490th byte in the buffer.
This is whole story how date problem was and how Big DBMSs handled these problems.
During the period between 1 A.D. and today, the Western world has actually used two main calendars: the Julian calendar of Julius Caesar and the Gregorian calendar of Pope Gregory XIII. The two calendars differ with respect to only one rule: the rule for deciding what a leap year is. In the Julian calendar, all years divisible by four are leap years. In the Gregorian calendar, all years divisible by four are leap years, except that years divisible by 100 (but not divisible by 400) are not leap years. Thus, the years 1700, 1800, and 1900 are leap years in the Julian calendar but not in the Gregorian calendar, while the years 1600 and 2000 are leap years in both calendars.
When Pope Gregory XIII introduced his calendar in 1582, he also directed that the days between October 4, 1582, and October 15, 1582, should be skipped—that is, he said that the day after October 4 should be October 15. Many countries delayed changing over, though. England and her colonies didn't switch from Julian to Gregorian reckoning until 1752, so for them, the skipped dates were between September 4 and September 14, 1752. Other countries switched at other times, but 1582 and 1752 are the relevant dates for the DBMSs that we're discussing.
Thus, two problems arise with date arithmetic when one goes back many years. The first is, should leap years before the switch be calculated according to the Julian or the Gregorian rules? The second problem is, when and how should the skipped days be handled?
This is how the Big DBMSs handle these questions:
- Pretend there was no switch. This is what the SQL Standard seems to require, although the standard document is unclear: It just says that dates are "constrained by the natural rules for dates using the Gregorian calendar"—whatever "natural rules" are. This is the option that DB2 chose. When there is a pretence that a single calendar's rules have always applied even to times when nobody heard of the calendar, the technical term is that a "proleptic" calendar is in force. So, for example, we could say that DB2 follows a proleptic Gregorian calendar.
- Avoid the problem entirely. Microsoft and Sybase set their minimum date values at January 1, 1753, safely past the time that America switched calendars. This is defendable, but from time to time complaints surface that these two DBMSs lack a useful functionality that the other DBMSs have and that the SQL Standard requires.
- Pick 1582. This is what Oracle did. An Oracle user would find that the date-arithmetic expression October 15 1582 minus October 4 1582 yields a value of 1 day (because October 5–14 don't exist) and that the date February 29 1300 is valid (because the Julian leap-year rule applies). Why did Oracle go to extra trouble when the SQL Standard doesn't seem to require it? The answer is that users might require it. Historians and astronomers use this hybrid system instead of a proleptic Gregorian calendar. (This is also the default option that Sun picked when implementing the GregorianCalendar class for Java—despite the name, GregorianCalendar is a hybrid calendar.)
Just looking at the message it sounds like one or more of the components that you reference, or one or more of their dependencies is not registered properly.
If you know which component it is you can use regsvr32.exe to register it, just open a command prompt, go to the directory where the component is and type regsvr32 filename.dll
(assuming it's a dll), if it works, try to run the code again otherwise come back here with the error.
If you don't know which component it is, try re-installing/repairing the GIS software (I assume you've installed some GIS software that includes the component you're trying to use).
Try this:
git rev-parse --short HEAD
The command git rev-parse
can do a remarkable number of different things, so you'd need to go through the documentation very carefully to spot that though.
Your regex pattern should have the g modifier:
var pattern = /[somepattern]+/g;
notice the g at the end. it tells the replacer to do a global replace.
Also you dont need to use the RegExp object you can construct your pattern as above. Example pattern:
var pattern = /[0-9a-zA-Z]+/g;
a pattern is always surrounded by / on either side - with modifiers after the final /, the g modifier being the global.
EDIT: Why does it matter if pattern is a variable? In your case it would function like this (notice that pattern is still a variable):
var pattern = /[0-9a-zA-Z]+/g;
repeater.replace(pattern, "1234abc");
But you would need to change your replace function to this:
this.markup = this.markup.replace(pattern, value);
You can use the below code to change the button to Left side.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.zakasoft.mymap.MapsActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|top"
android:text="Send"
android:padding="10dp"
android:layout_marginTop="20dp"
android:paddingRight="10dp"/>
</fragment>
In SQL Server 2008 there are two new Dynamic Management Functions introduced to keep track of object dependencies: sys.dm_sql_referenced_entities and sys.dm_sql_referencing_entities:
1/ Returning the entities that refer to a given entity:
SELECT
referencing_schema_name, referencing_entity_name,
referencing_class_desc, is_caller_dependent
FROM sys.dm_sql_referencing_entities ('<TableName>', 'OBJECT')
2/ Returning entities that are referenced by an object:
SELECT
referenced_schema_name, referenced_entity_name, referenced_minor_name,
referenced_class_desc, is_caller_dependent, is_ambiguous
FROM sys.dm_sql_referenced_entities ('<StoredProcedureName>', 'OBJECT');
Alternatively, you can use sp_depends:
EXEC sp_depends '<TableName>'
Another option is to use a pretty useful tool called SQL Dependency Tracker from Red Gate.
I think you need to use Expr
with ->set()
(However THIS IS NOT SAFE and you shouldn't do it):
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', $qb->expr()->literal($username))
->set('u.email', $qb->expr()->literal($email))
->where('u.id = ?1')
->setParameter(1, $editId)
->getQuery();
$p = $q->execute();
It's much safer to make all your values parameters instead:
$qb = $this->em->createQueryBuilder();
$q = $qb->update('models\User', 'u')
->set('u.username', '?1')
->set('u.email', '?2')
->where('u.id = ?3')
->setParameter(1, $username)
->setParameter(2, $email)
->setParameter(3, $editId)
->getQuery();
$p = $q->execute();
Even though it is about international numbers I would want the code to be like :
/^(\+|\d)[0-9]{7,16}$/;
As you can have international numbers starting with '00' as well.
Why I prefer 15 digits : http://en.wikipedia.org/wiki/E.164
display: none
It will remove the element from the normal flow of the page, allowing other elements to fill in.
An element will not appear on the page at all but we can still interact with it through the DOM. There will be no space allocated for it between the other elements.
visibility: hidden
It will leave the element in the normal flow of the page such that is still occupies space.
An element is not visible and Element’s space is allocated for it on the page.
Some other ways to hide elements
Use z-index
#element {
z-index: -11111;
}
Move an element off the page
#element {
position: absolute;
top: -9999em;
left: -9999em;
}
Interesting information about visibility: hidden and display: none properties
visibility: hidden
and display: none
will be equally performant since they both re-trigger layout, paint and composite. However, opacity: 0
is functionality equivalent to visibility: hidden
and does not re-trigger the layout step.
And CSS-transition property is also important thing that we need to take care. Because toggling from visibility: hidden
to visibility: visible
allow for CSS-transitions to be use, whereas toggling from display: none
to display: block
does not. visibility: hidden
has the additional benefit of not capturing JavaScript events, whereas opacity: 0
captures events
suprised this doesn't have an answer using pathilib which was introduced in python 3.4
+
additionally, shutil updated in python 3.6
to accept a pathlib object more details in this PEP-0519
from pathlib import Path
src_path = '\tmp\files_to_move'
for each_file in Path(src_path).glob('*.*'): # grabs all files
trg_path = each_file.parent.parent # gets the parent of the folder
each_file.rename(trg_path.joinpath(each_file.name)) # moves to parent folder.
from pathlib import Path
import shutil
src_path = '\tmp\files_to_move'
trg_path = '\tmp'
for src_file in Path(src_path).glob('*.*'):
shutil.copy(src_file, trg_path)
if you add an #include <algorithm>
then you can use the for_each
function and a lambda function like so:
for_each(data.begin(), data.end(), [](Student *it)
{
std::cout<<it->name;
});
you can read more about the algorithm library at https://en.cppreference.com/w/cpp/algorithm
and about lambda functions in cpp at https://docs.microsoft.com/en-us/cpp/cpp/lambda-expressions-in-cpp?view=vs-2019
You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.
However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values--if doing an UPDATE--with OLD.
If you had a row named full_brand_name
and you wanted to use the first two letters as a short name in the field small_name
you could use:
CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END
Yes, it is possible. Though I wouldn't recommend it because input range
is not really supported properly by all browsers because is an new element added in HTML5 and HTML5 is only a draft (and will be for long) so going as far as to styling it is perhaps not the best choice.
Also, you'll need a bit of JavaScript too. I took the liberty of using jQuery library for this, for simplicity purposes.
Here you go: http://jsfiddle.net/JnrvG/1/.
Swift:
extension Double {
func getDateStringFromUnixTime(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = dateStyle
dateFormatter.timeStyle = timeStyle
return dateFormatter.string(from: Date(timeIntervalSince1970: self))
}
}
Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.
It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\
This should suffice your purpose. It compares two collections and checks if one collection has the values matching those in the other collection
fea_Features.Where(s => selectedFeatures.Contains(s.feaId))
TimeSpan.FromSeconds(80);
http://msdn.microsoft.com/en-us/library/system.timespan.fromseconds.aspx
If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.
In my case, I needed my images where stored in a blob column in a db table:
def select_all_X_values(conn):
cur = conn.cursor()
cur.execute("SELECT ImageData from PiecesTable")
rows = cur.fetchall()
return rows
I then created a helper function to change my dataset into np.array:
X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))
def convertToByteIO(imagesArray):
"""
# Converts an array of images into an array of Bytes
"""
imagesList = []
for i in range(len(imagesArray)):
img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
imagesList.insert(i, np.array(img))
return imagesList
After this, I was able to use the byteArrays in my Neural Network.
plt.imshow(imagesList[0])
FirebaseInstanceIdService
This class is deprecated. In favour of overriding onNewToken in FirebaseMessagingService. Once that has been implemented, this service can be safely removed.
The new way to do this would be to override the onNewToken
method from FirebaseMessagingService
public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onNewToken(String s) {
super.onNewToken(s);
Log.e("NEW_TOKEN",s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
}
}
Also dont forget to add the service in the Manifest.xml
<service
android:name=".MyFirebaseMessagingService"
android:stopWithTask="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
Like others said, the simpliest solution is just call draggable()
function from jQuery UI just after showing modal:
$('#my-modal').modal('show')
.draggable({ handle: ".modal-header" });
But there is a several problems with compatibility between Bootstrap and jQuery UI so we need some addition fixes in css:
.modal
{
overflow: hidden;
}
.modal-dialog{
margin-right: 0;
margin-left: 0;
}
.modal-header{ /* not necessary but imo important for user */
cursor: move;
}
I used Selva's solution but had two kinds of issues:
I fixed these two issues. You can find the solution (within my own project package) at
To change the default character set and collation of a table including those of existing columns (note the convert to clause):
alter table <some_table> convert to character set utf8mb4 collate utf8mb4_unicode_ci;
Edited the answer, thanks to the prompting of some comments:
Should avoid recommending utf8. It's almost never what you want, and often leads to unexpected messes. The utf8 character set is not fully compatible with UTF-8. The utf8mb4 character set is what you want if you want UTF-8. – Rich Remer Mar 28 '18 at 23:41
and
That seems quite important, glad I read the comments and thanks @RichRemer . Nikki , I think you should edit that in your answer considering how many views this gets. See here https://dev.mysql.com/doc/refman/8.0/en/charset-unicode-utf8.html and here What is the difference between utf8mb4 and utf8 charsets in MySQL? – Paulpro Mar 12 at 17:46
Do a chmod 400 yourkeyfile.pem If your instance is Amazon linux then use ssh -i yourkeyfile.pem ec2-user@ip for ubuntu ssh -i yourkeyfile.pem ubuntu@ip for centos ssh -i yourkeyfile.pem centos@ip
Laravel 5 gets its enviroment related variables from the .env
file located in the root of your project. You just need to set APP_ENV
to whatever you want, for example:
APP_ENV=development
This is used to identify the current enviroment. If you want to display errors, you'll need to enable debug mode in the same file:
APP_DEBUG=true
The role of the .env
file is to allow you to have different settings depending on which machine you are running your application. So on your production server, the .env
file settings would be different from your local development enviroment.
You can use String.Format function to add second class based on condition:
<div class="@String.Format("details {0}", Details.Count > 0 ? "show" : "hide")">
You asked WHY, not how to cheat it:
Usually because of laziness of programmers of the initial implementation, because they HAVE already put way more effort in other features, delivering more odd side-effects like floats, because they were more requested by designers back then and yet they haven't taken the time to allow this so we can use the FOUR properties to push/pull an element against its neighbors (now we only have four to push, and only 2 to pull).
When html was designed, magazines loved text reflown around images back then, now hated because today we have touch trends, and love squary things with lots of space and nothing to read. That's why they put more pressure on floats than on centering, or they could have designed something like margin-top: fill;
or margin: average 0;
to simply align the content to the bottom, or distribute its extra space around.
In this case I think it hasn't been implemented because of the same reason that makes CSS to lack of a :parent
pseudo-selector: To prevent looping evaluations.
Without being an engineer, I can see that CSS right now is made to paint elements once, remember some properties for future elements to be painted, but NEVER going back to already-painted elements.
That's why (I guess) padding is calculated on the width, because that's the value that was available at the time of starting to paint it.
If you had a negative value for padding, it would affect the outer limits, which has ALREADY been defined when the margin has already been set. I know, nothing has been painted yet, but when you read how the painting process goes, created by geniuses with 90's technology, I feel like I am asking dumb questions and just say "thanks" hehe.
One of the requirements of web pages is that they are quickly available, unlike an app that can take its time and eat the computer resources to get everything correct before displaying it, web pages need to use little resources (so they are fit in every device possible) and be scrolled in a breeze.
If you see applications with complex reflowing and positioning, like InDesign, you can't scroll that fast! It takes a big effort both from processors and graphic card to jump to next pages!
So painting and calculating forward and forgetting about an element once drawn, for now it seems to be a MUST.
I have remixed the answer by @isubuz and this answer by @Umur Kontaci on attribute directives into a version where your controller doesn't call a DOM-like operation like "dismiss", but instead tries to be more MVVM style, setting a boolean property isInEditMode
. The view in turn links this bit of info to the attribute directive that opens/closes the bootstrap modal.
var app = angular.module('myApp', []);_x000D_
_x000D_
app.directive('myModal', function() {_x000D_
return {_x000D_
restrict: 'A',_x000D_
scope: { myModalIsOpen: '=' },_x000D_
link: function(scope, element, attr) {_x000D_
scope.$watch(_x000D_
function() { return scope.myModalIsOpen; },_x000D_
function() { element.modal(scope.myModalIsOpen ? 'show' : 'hide'); }_x000D_
);_x000D_
}_x000D_
} _x000D_
});_x000D_
_x000D_
app.controller('MyCtrl', function($scope) {_x000D_
$scope.isInEditMode = false;_x000D_
$scope.toggleEditMode = function() { _x000D_
$scope.isInEditMode = !$scope.isInEditMode;_x000D_
};_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="MyCtrl as vm">_x000D_
_x000D_
<div class="modal fade" my-modal my-modal-is-open="isInEditMode">_x000D_
<div class="modal-dialog">_x000D_
<div class="modal-content">_x000D_
<div class="modal-body">_x000D_
Modal body! IsInEditMode == {{isInEditMode}}_x000D_
</div>_x000D_
<div class="modal-footer">_x000D_
<button class="btn" ng-click="toggleEditMode()">Close</button>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<p><button class="btn" ng-click="toggleEditMode()">Toggle Edit Mode</button></p> _x000D_
<pre>isInEditMode == {{isInEditMode}}</pre>_x000D_
_x000D_
</div>
_x000D_
Since you've included the C++ tag, you could use the {fmt} library and avoid the PRIu64
macro and other printf
issues altogether:
#include <fmt/core.h>
int main() {
uint64_t ui64 = 90;
fmt::print("test uint64_t : {}\n", ui64);
}
The formatting facility based on this library is proposed for standardization in C++20: P0645.
Disclaimer: I'm the author of {fmt}.
In Swift 4:
// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed colour
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
// Set the label
label.attributedText = attributedString
In Swift 3:
// Custom color
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
// create the attributed color
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
// create the attributed string
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
// Set the label
label.attributedText = attributedString
Enjoy.
use std::stringstream
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
the following example produces -65538
as its result:
#include <sstream>
#include <iostream>
int main() {
unsigned int x;
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;
}
In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string
So, the simplest answer for newer code would probably look like this:
std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);
NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).
It appears that since lexical_cast<>
is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast
and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.
Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:
try {
unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
// whatever you want to do...
}
If you don't feel like using boost, here's a light version of lexical cast which does no error checking:
template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
T2 out;
std::stringstream ss;
ss << in;
ss >> out;
return out;
}
which you can use like this:
// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef");
If you are looking for a hard limit across all uploads on the site, you can limit these in php.ini by setting the following:
`upload_max_filesize = 2M` `post_max_size = 2M`
that will set the maximum upload limit to 2 MB
I took the Methodology from Carbon above, and streamlined the code into a smaller function, this works very well for me.
Function Test-RegistryValue($key,$name)
{
if(Get-Member -InputObject (Get-ItemProperty -Path $key) -Name $name)
{
return $true
}
return $false
}
Or another typical standard in the industry is to have a Constants.java named class file containing all the constants to be used all over the project.
git remote prune origin
prunes tracking branches not on the remote.
git branch --merged
lists branches that have been merged into the current branch.
xargs git branch -d
deletes branches listed on standard input.
Be careful deleting branches listed by git branch --merged
. The list could include master
or other branches you'd prefer not to delete.
To give yourself the opportunity to edit the list before deleting branches, you could do the following in one line:
git branch --merged >/tmp/merged-branches && \
vi /tmp/merged-branches && xargs git branch -d </tmp/merged-branches
bool
is just a macro that expands to _Bool
. You can use _Bool
with no #include
very much like you can use int
or double
; it is a C99 keyword.
The macro is defined in <stdbool.h>
along with 3 other macros.
The macros defined are
bool
: macro expands to _Bool
false
: macro expands to 0
true
: macro expands to 1
__bool_true_false_are_defined
: macro expands to 1
The usual way to check whether something can be converted to an int
is to try
it and see, following the EAFP principle:
try:
int_value = int(string_value)
except ValueError:
# it wasn't an int, do something appropriate
else:
# it was an int, do something appropriate
So, in your case:
for item in mylist:
try:
int_value = int(item)
except ValueError:
pass
else:
mynewlist.append(item) # or append(int_value) if you want numbers
In most cases, a loop around some trivial code that ends with mynewlist.append(item)
can be turned into a list comprehension, generator expression, or call to map
or filter
. But here, you can't, because there's no way to put a try
/except
into an expression.
But if you wrap it up in a function, you can:
def raises(func, *args, **kw):
try:
func(*args, **kw)
except:
return True
else:
return False
mynewlist = [item for item in mylist if not raises(int, item)]
… or, if you prefer:
mynewlist = filter(partial(raises, int), item)
It's cleaner to use it this way:
def raises(exception_types, func, *args, **kw):
try:
func(*args, **kw)
except exception_types:
return True
else:
return False
This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True
, but if any unexpected exceptions are raised, they'll propagate out. So:
mynewlist = [item for item in mylist if not raises(ValueError, int, item)]
… will do what you want, but:
mynewlist = [item for item in mylist if not raises(ValueError, item, int)]
… will raise a TypeError
, as it should.
If your main element has some child elements or text, you could make use of it.
Position your main element relative (or absolute/fixed) and use both :before and :after positioned absolute (in my situation it had to be absolute, don't know about your's).
Now if you want one more pseudo-element, attach an absolute :before to one of the main element's children (if you have only text, put it in a span, now you have an element), which is not relative/absolute/fixed.
This element will start acting like his owner is your main element.
HTML
<div class="circle">
<span>Some text</span>
</div>
CSS
.circle {
position: relative; /* or absolute/fixed */
}
.circle:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle:after {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
.circle span {
/* not relative/absolute/fixed */
}
.circle span:before {
position: absolute;
content: "";
/* more styles: width, height, etc */
}
Simple program to write objects to file and read objects from file.
package program;_x000D_
_x000D_
import java.io.File;_x000D_
import java.io.FileInputStream;_x000D_
import java.io.FileOutputStream;_x000D_
import java.io.ObjectInputStream;_x000D_
import java.io.ObjectOutputStream;_x000D_
import java.io.Serializable;_x000D_
_x000D_
public class TempList {_x000D_
_x000D_
public static void main(String[] args) throws Exception {_x000D_
Counter counter = new Counter(10);_x000D_
_x000D_
File f = new File("MyFile.txt");_x000D_
FileOutputStream fos = new FileOutputStream(f);_x000D_
ObjectOutputStream oos = new ObjectOutputStream(fos);_x000D_
oos.writeObject(counter);_x000D_
oos.close();_x000D_
_x000D_
FileInputStream fis = new FileInputStream(f);_x000D_
ObjectInputStream ois = new ObjectInputStream(fis);_x000D_
Counter newCounter = (Counter) ois.readObject();_x000D_
System.out.println(newCounter.count);_x000D_
ois.close();_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
class Counter implements Serializable {_x000D_
_x000D_
private static final long serialVersionUID = -628789568975888036 L;_x000D_
_x000D_
int count;_x000D_
_x000D_
Counter(int count) {_x000D_
this.count = count;_x000D_
}_x000D_
}
_x000D_
After running the program the output in your console window will be 10 and you can find the file inside Test folder by clicking on the icon show in below image.
i know i'm years late xD but Here's how i did it
public static string convertDataTableToString(DataTable dataTable)
{
string data = string.Empty;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
DataRow row = dataTable.Rows[i];
for (int j = 0; j < dataTable.Columns.Count; j++)
{
data += dataTable.Columns[j].ColumnName + "~" + row[j];
if (j == dataTable.Columns.Count - 1)
{
if (i != (dataTable.Rows.Count - 1))
data += "$";
}
else
data += "|";
}
}
return data;
}
If someone ever optimizes this please let me know
i tried this :
public static string convertDataTableToString(DataTable dataTable)
{
string data = string.Empty;
int rowsCount = dataTable.Rows.Count;
for (int i = 0; i < rowsCount; i++)
{
DataRow row = dataTable.Rows[i];
int columnsCount = dataTable.Columns.Count;
for (int j = 0; j < columnsCount; j++)
{
data += dataTable.Columns[j].ColumnName + "~" + row[j];
if (j == columnsCount - 1)
{
if (i != (rowsCount - 1))
data += "$";
}
else
data += "|";
}
}
return data;
}
but this answer says it's worse
Xcode 8.X , Swift 3.X
Easy Use;
let params:NSMutableDictionary? = ["foo": "bar"];
let ulr = NSURL(string:"http://mywebsite.com/post-request" as String)
let request = NSMutableURLRequest(url: ulr! as URL)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
if let json = json {
print(json)
}
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue);
Alamofire.request(request as! URLRequestConvertible)
.responseJSON { response in
// do whatever you want here
print(response.request)
print(response.response)
print(response.data)
print(response.result)
}
if you want to escape double quote in JSON use \\ to escape it.
example if you want to create json of following javascript object
{time: '7 "o" clock'}
then you must write in following way
'{"time":"7 \\"o\\" clock"}'
if we parse it using JSON.parse()
JSON.parse('{"time":"7 \\"o\\" clock"}')
result will be
{time: "7 "o" clock"}
You can communicate with docker from inside of a container using unix socket via Docker Remote API:
https://docs.docker.com/engine/reference/api/docker_remote_api/
In a container, you can find out a shortedned docker id by examining $HOSTNAME
env var.
According to doc, there is a small chance of collision, I think that for small number of container, you do not have to worry about it. I don't know how to get full id directly.
You can inspect container similar way as outlined in banyan answer:
GET /containers/4abbef615af7/json HTTP/1.1
Response:
HTTP/1.1 200 OK
Content-Type: application/json
{
"Id": "4abbef615af7...... ",
"Created": "2013.....",
...
}
Alternatively, you can transfer docker id to the container in a file. The file is located on "mounted volume" so it is transfered to container:
docker run -t -i -cidfile /mydir/host1.txt -v /mydir:/mydir ubuntu /bin/bash
The docker id (shortened) will be in file /mydir/host1.txt in the container.
you can check the type. s3 has a special application/x-directory
bucket.objects({:delimiter=>"/", :prefix=>"f1/"}).each { |obj| p obj.object.content_type }
From Android Support Library v26 + Android Studio 3.0 onwards, this process has become easy as a flick!!
Follow these steps to change the font of Toolbar Title:
res > font
as per Fonts in XMLIn res > values > styles
, paste the following (use your imagination here!)
<style name="TitleBarTextAppearance" parent="android:TextAppearance">
<item name="android:fontFamily">@font/your_desired_font</item>
<item name="android:textSize">23sp</item>
<item name="android:textStyle">bold</item>
<item name="android:textColor">@android:color/white</item>
</style>
Insert a new line in your Toolbar properties app:titleTextAppearance="@style/TextAppearance.TabsFont"
as shown below
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:titleTextAppearance="@style/TitleBarTextAppearance"
app:popupTheme="@style/AppTheme.PopupOverlay"/>
Enjoy Custom Actionbar Title font styling!!
Try this.
EditText text = (EditText)findViewById(R.id.edittext1);
String str = text.getText().toString().trim();
You can use the BIT
field.
For adding a BIT column to an existing table, the SQL command would look like:
ALTER TABLE table_name ADD yes_no BIT
If you want to create a new table, you could do: CREATE TABLE table_name (yes_no BIT)
.
Store it either in a cookie (if it's acceptable for your situation), or in a session variable.
session_start();
if ( !isset( $_SESSION["origURL"] ) )
$_SESSION["origURL"] = $_SERVER["HTTP_REFERER"];
This is now possible in chrome 35 (today as of July 11, 2014). I don't know which version allowed it first though.
Just tested @gilly3 example on my machine and it works.
Open the console, in Sources
and the tab Snippets
, add a new snippet, paste the following code into it:
var g_n = 0;
function go()
{
var n = 0;
var o = { n: 0 };
return g_n + n + o.n; // breakpoint here
}
Right-click the snippet name, click 'Run' (this does not fire the function though)
go()
and the returned result g_n + n + o.n
is 30.
Put it inside your <footer>
by all means, but the most fitting element is the small element.
The HTML5 spec for this says:
Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.
To use the Like Button and have the Open Graph inspect your website, you need an application.
So you need to associate the Like Button with a fb:app_id
If you want other users to see the administration page for your website on Facebook you add fb:admins
. So if you are the developer of the application and the website owner there is no need to add fb:admins
Try this code:
private void RegisterInStartup(bool isChecked)
{
RegistryKey registryKey = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (isChecked)
{
registryKey.SetValue("ApplicationName", Application.ExecutablePath);
}
else
{
registryKey.DeleteValue("ApplicationName");
}
}
Source (dead): http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/
Archived link: https://web.archive.org/web/20110104113608/http://www.dotnetthoughts.net/2010/09/26/run-the-application-at-windows-startup/
Don't use device-width/height anymore.
device-width, device-height and device-aspect-ratio are deprecated in Media Queries Level 4: https://developer.mozilla.org/en-US/docs/Web/CSS/@media#Media_features
Just use width/height (without min/max) in combination with orientation & (min/max-)resolution to target specific devices. On mobile width/height should be the same as device-width/height.
JavaScript
var myObj = {
id: "c001",
name: "Hello Test"
}
Result(JSON)
{
"id": "c001",
"name": "Hello Test"
}
There is no straight forward way of doing this.
What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).
Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript
My favorite is(not applicable always):
<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");
Google's closure also provides similar functionality.
Exchange rate from Euro to NOK on the first of January 2016:
=INDEX(GOOGLEFINANCE("CURRENCY:EURNOK"; "close"; DATE(2016;1;1)); 2; 2)
The INDEX()
function is used because GOOGLEFINANCE()
function actually prints out in 4 separate cells (2x2) when you call it with these arguments, with it the result will only be one cell.