If it's a .mdf database and the connection string was saved when it was created, you should be able to access it via:
Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString)
Hope that helps someone.
I'll probably get flamed for this, but what is the point of testing for existence if you are just going to delete it? One of my major pet peeves is an app throwing an error dialog with something like "Could not delete file, it does not exist!"
On Error Resume Next
aFile = "c:\file_to_delete.txt"
Kill aFile
On Error Goto 0
return Len(Dir$(aFile)) > 0 ' Make sure it actually got deleted.
If the file doesn't exist in the first place, mission accomplished!
While createting the bat file, you can easly avoid the space. If you want to mentioned "program files "folder in batch file.
Do following steps:
1. Type c:
then press enter
2. cd program files
3. cd "choose your own folder name"
then continue as you wish.
This way you can create batch file and you can mention program files folder.
I ran into an issue with external API providing dates in this format, some times even with UTC difference info like /Date(123232313131+1000)/
. I was able to turn it js Date
object with following code
var val = '/Date(123232311-1000)/';
var pattern = /^\/Date\([0-9]+((\+|\-)[0-9]+)?\)\/$/;
var date = null;
// Check that the value matches /Date(123232311-1000)/ format
if (pattern.test(val)) {
var number = val.replace('/Date(', '',).replace(')/', '');
if (number.indexOf('+') >= 0) {
var split = number.split('+');
number = parseInt(split[0]) + parseInt(split[1]);
} else if (number.indexOf('-') >= 0) {
var split = number.split('-');
number = parseInt(split[0]) - parseInt(split[1]);
} else {
number = parseInt(number);
date = new Date(number);
}
}
find the below explanation:
int main()
{
int a = 10;// say address of 'a' is 2000;
int *p = &a; //it means 'p' is pointing[referencing] to 'a'. i.e p->2000
int c = *p; //*p means dereferncing. it will give the content of the address pointed by 'p'. in this case 'p' is pointing to 2000[address of 'a' variable], content of 2000 is 10. so *p will give 10.
}
conclusion :
&
[address operator] is used for referencing.*
[star operator] is used for de-referencing .Not a lot to go on there, but I think what you're looking for is to flip the width
and max-width
values:
#container2 {
width: 90%;
max-width: 960px;
/* etc, etc... */
}
That'll give you a container that's 90% of the width of the available space, up to a maximum of 960px, but that's dependent on its container being resizable itself. Responsive design is a whole big ball of wax though, so this doesn't even scratch the surface.
Pass java.text.Collator.getInstance()
to Collections.sort
method ; it will sort Alphabetically while ignoring case sensitive.
ArrayList<String> myArray = new ArrayList<String>();
myArray.add("zzz");
myArray.add("xxx");
myArray.add("Aaa");
myArray.add("bb");
myArray.add("BB");
Collections.sort(myArray,Collator.getInstance());
I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:
if l:
print "list has items"
elif not l:
print "list is empty"
the error will be:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:
select *
from (
select 1 as Rank, id, add_date from Table
union all
select 2 as Rank, id, add_date from Table where distance < 5
union all
select 3 as Rank, id, add_date from Table where distance between 5 and 15
) a
order by rank, id, add_date desc
You need to set the text to something other than an empty string. In addition, the .html() function should do it while preserving the HTML structure of the div.
$('#one').html($('#one').html().replace('text','replace'));
The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g"
, containing way too many slashes.
Since sed
can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:
replacement="/my/path"
sed --expression "s@pattern@$replacement@"
Note that this is not bullet proof: if the replacement string later contains @
it will break for the same reason, and any backslash sequences like \1
will still be interpreted according to sed
rules. Using |
as a delimiter is also a nice option as it is similar in readability to /
.
As per: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
9.2 OPTIONS
The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
Responses to this method are not cacheable.
If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed queries on the server. A server that does not support such an extension MAY discard the request body.
If the Request-URI is an asterisk ("*"), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the "*" request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof).
If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.
A 200 response SHOULD include any header fields that indicate optional features implemented by the server and applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The response body, if any, SHOULD also include information about the communication options. The format for such a body is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY be used to select the appropriate response format. If no response body is included, the response MUST include a Content-Length field with a field-value of "0".
The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a Max-Forwards field. If the Max-Forwards field-value is zero ("0"), the proxy MUST NOT forward the message; instead, the proxy SHOULD respond with its own communication options. If the Max-Forwards field-value is an integer greater than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is present in the request, then the forwarded request MUST NOT include a Max-Forwards field.
9.4 HEAD
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.
The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.
This works for me:
URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/9/9c/Image-Porkeri_001.jpg");
InputStream in = new BufferedInputStream(url.openStream());
OutputStream out = new BufferedOutputStream(new FileOutputStream("Image-Porkeri_001.jpg"));
for ( int i; (i = in.read()) != -1; ) {
out.write(i);
}
in.close();
out.close();
The following code stops the execution right after an exception is thrown. You need to set a windows_exception_handler along with a termination handler. I tested this in MinGW 32bits.
void beforeCrash(void);
static const bool SET_TERMINATE = std::set_terminate(beforeCrash);
void beforeCrash() {
__asm("int3");
}
int main(int argc, char *argv[])
{
SetUnhandledExceptionFilter(windows_exception_handler);
...
}
Check the following code for the windows_exception_handler function: http://www.codedisqus.com/0ziVPgVPUk/exception-handling-and-stacktrace-under-windows-mingwgcc.html
Use this it will work,
<body>
<h1>Adding 'a' and 'b'</h1>
<form>
a: <input type="number" name="a" id="a"><br>
b: <input type="number" name="b" id="a"><br>
<button onclick="add()">Add</button>
</form>
<script>
function add() {
var m = document.getElementById("a").value;
var n = document.getElementById("b").value;
var sum = m + n;
alert(sum);
}
</script>
</body>
Goes to the right and can be used the same way for the left
.yourComponent
{
float: right;
bottom: 0;
}
You are getting NullReferenceExeption
because of you are using the cmb.SelectedValue
which is null. the comboBox
doesn't know what is the value of your custom class ComboboxItem
, so either do:
ComboboxItem selectedCar = (ComboboxItem)comboBox2.SelectedItem;
int selecteVal = Convert.ToInt32(selectedCar.Value);
Or better of is use data binding like:
ComboboxItem item1 = new ComboboxItem();
item1.Text = "test";
item1.Value = "123";
ComboboxItem item2 = new ComboboxItem();
item2.Text = "test2";
item2.Value = "456";
List<ComboboxItem> items = new List<ComboboxItem> { item1, item2 };
this.comboBox1.DisplayMember = "Text";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = items;
This worked for me:
:%s/^[^a-zA-Z0-9]$\n//ig
It basically deletes all the lines that don't have a number or letter. Since all the items in my list had letters, it deleted all the blank lines.
a {
outline: 0;
}
But read this before change it:
Just came across this and the short code for transparency is simply #00000000.
You have to use setOnItemClickListener
someone said.
The code should be like this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// When clicked, show a toast with the TextView text or do whatever you need.
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
Your currently selected backend, 'agg' does not support show().
AGG
backend is for writing to file, not for rendering in a window. See the backend FAQ at the matplotlib web site.
ImportError: No module named _backend_gdk
For the second error, maybe your matplotlib distribution is not compiled with GTK support, or you miss the PyGTK package. Try to install it.
Do you call the show()
method inside a terminal or application that has access to a graphical environment?
Try other GUI backends, in this order:
TkAgg
WX
QTAgg
QT4Agg
You can try these lines:
$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value
Sometimes, PHP will emit a X-Powered-By:
response header which you can look at e.g. using Firebug.
If this setting (controlled by the ini setting expose_php
) is turned off (it often is), there is no way to tell the PHP version used - and rightly so. What PHP version is running is none of the outside world's business, and it's good to obscure this from a security perspective.
str.count(sub[, start[, end]])
Return the number of non-overlapping occurrences of substring
sub
in the range[start, end]
. Optional argumentsstart
andend
are interpreted as in slice notation.
>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4
Use Control.BringToFront
:
myForm.BringToFront();
this worked great:
UPDATE
table_Name
SET
column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
ID = @ID
INSERT INTO prices(group, id, price)
SELECT 7, articleId, 1.50
FROM article where name like 'ABC%';
No, it doesn't have one. For this reason most popular libraries come with one in their utility packages. Check out jQuery's inArray and Prototype's Array.indexOf for examples.
jQuery's implementation of it is as simple as you might expect:
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
If you are dealing with a sane amount of array elements the above will do the trick nicely.
EDIT: Whoops. I didn't even notice you wanted to see if an array was inside another. According to the PHP documentation this is the expected behavior of PHP's in_array
:
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
// Output:
// 'ph' was found
// 'o' was found
The code posted by Chris and Alex does not follow this behavior. Alex's is the official version of Prototype's indexOf, and Chris's is more like PHP's array_intersect
. This does what you want:
function arrayCompare(a1, a2) {
if (a1.length != a2.length) return false;
var length = a2.length;
for (var i = 0; i < length; i++) {
if (a1[i] !== a2[i]) return false;
}
return true;
}
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(typeof haystack[i] == 'object') {
if(arrayCompare(haystack[i], needle)) return true;
} else {
if(haystack[i] == needle) return true;
}
}
return false;
}
And this my test of the above on it:
var a = [['p','h'],['p','r'],'o'];
if(inArray(['p','h'], a)) {
alert('ph was found');
}
if(inArray(['f','i'], a)) {
alert('fi was found');
}
if(inArray('o', a)) {
alert('o was found');
}
// Results:
// alerts 'ph' was found
// alerts 'o' was found
Note that I intentionally did not extend the Array prototype as it is generally a bad idea to do so.
Adding what worked for me in case others have the same issue and end up here. I had an older project that had the CLANG_ENABLE_MODULES setting set to No. After hours of frustration I compared to a working project and found I had Enable Modules Set to no under my LLVM build settings. Setting this to Yes solved my problem and the app builds fine.
Project Settings -> Build Settings -> search for 'Modules' and Update Enable Modules (C and Objective-C) to YES.
Old versions of JavaScript (< ES5) require using a for..in
loop:
for (var key in data) {
if (data.hasOwnProperty(key)) {
// do something with key
}
}
ES5 introduces Object.keys and Array#forEach which makes this a little easier:
var data = { foo: 'bar', baz: 'quux' };
Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
// do something with data[key]
});
ES2017 introduces Object.values
and Object.entries
.
Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]
Set it with a px value. Changing the code like below should work
el.css('marginLeft', mrg + 'px');
One of the Related posts gave me the (simple) answer.
Apparently the auto
value on the grid-template-rows
property does exactly what I was looking for.
.grid {
display:grid;
grid-template-columns: 1fr 1.5fr 1fr;
grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
grid-gap:10px;
height: calc(100vh - 10px);
}
There may be a more eloquent way, but this is the way I came up with:
The function to find the last populated cell in a column is:
=INDEX( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ; ROWS( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ) )
So if you combine it with your current function it would look like this:
=DAYS360(A2,INDEX( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ; ROWS( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ) ))
Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx
1. See information about the SQL server
tsql -LH SERVER_IP_ADDRESS
locale is "C"
locale charset is "646"
ServerName TITAN
InstanceName MSSQLSERVER
IsClustered No
Version 8.00.194
tcp 1433
np \\TITAN\pipe\sql\query
2. Set your freetds.conf
tsql -C
freetds.conf directory: /usr/local/etc
[TITAN]
host = SERVER_IP_ADDRESS
port = 1433
tds version = 7.2
3 Try
tsql -S TITAN -U user -P password
OR
'dsn' => 'dblib:host=TITAN:1433;dbname=YOURDBNAME',
See also http://www.freetds.org/userguide/confirminstall.htm (Example 3-5.)
If you get message 20009, remember you haven't connected to the machine. It's a configuration or network issue, not a protocol failure. Verify the server is up, has the name and IP address FreeTDS is using, and is listening to the configured port.
Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.
On Linux, with NuGet CLI, the commands are similar. To install my.nupkg, run
nuget add -Source some/directory my.nupkg
Then run dotnet restore
from that directory
dotnet restore --source some/directory Project.sln
or add that directory as a NuGet source
nuget sources Add -Name MySource -Source some/directory
and then tell msbuild
to use that directory with /p:RestoreAdditionalSources=MySource
or /p:RestoreSources=MySource
. The second switch will disable all other sources, which is good for offline scenarios, for example.
public class SmsListener extends BroadcastReceiver{
private SharedPreferences preferences;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
Bundle bundle = intent.getExtras(); //---get the SMS message passed in---
SmsMessage[] msgs = null;
String msg_from;
if (bundle != null){
//---retrieve the SMS message received---
try{
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
msg_from = msgs[i].getOriginatingAddress();
String msgBody = msgs[i].getMessageBody();
}
}catch(Exception e){
// Log.d("Exception caught",e.getMessage());
}
}
}
}
}
Note: In your manifest file add the BroadcastReceiver-
<receiver android:name=".listener.SmsListener">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Add this permission:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
The reason everyone always says to avoid System.gc()
is that it is a pretty good indicator of fundamentally broken code. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken.
You don't know what sort of garbage collector you are running under. There are certainly some that do not "stop the world" as you assert, but some JVMs aren't that smart or for various reasons (perhaps they are on a phone?) don't do it. You don't know what it's going to do.
Also, it's not guaranteed to do anything. The JVM may just entirely ignore your request.
The combination of "you don't know what it will do," "you don't know if it will even help," and "you shouldn't need to call it anyway" are why people are so forceful in saying that generally you shouldn't call it. I think it's a case of "if you need to ask whether you should be using this, you shouldn't"
EDIT to address a few concerns from the other thread:
After reading the thread you linked, there's a few more things I'd like to point out.
First, someone suggested that calling gc()
may return memory to the system. That's certainly not necessarily true - the Java heap itself grows independently of Java allocations.
As in, the JVM will hold memory (many tens of megabytes) and grow the heap as necessary. It doesn't necessarily return that memory to the system even when you free Java objects; it is perfectly free to hold on to the allocated memory to use for future Java allocations.
To show that it's possible that System.gc()
does nothing, view:
http://bugs.sun.com/view_bug.do?bug_id=6668279
and in particular that there's a -XX:DisableExplicitGC VM option.
Not quite sure why everyone is giving you a hard time for wanting to do this - there are several scenarios where you'd want a fixed size initialised list. And you've correctly deduced that arrays are sensible in these cases.
import array
verts=array.array('i',(0,)*1000)
For the non-pythonistas, the (0,)*1000
term is creating a tuple containing 1000 zeros. The comma forces python to recognise (0)
as a tuple, otherwise it would be evaluated as 0.
I've used a tuple instead of a list because they are generally have lower overhead.
Check out numpy.count_nonzero.
>>> np.count_nonzero(np.eye(4))
4
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])
5
You might want to chose based on what is widely available. I had the same question and here are the results of my limited research.
Hardware limitations
STM32L (low energy ARM cores) from ST Micro support ECB, CBC,CTR GCM
CC2541 (Bluetooth Low Energy) from TI supports ECB, CBC, CFB, OFB, CTR, and CBC-MAC
Open source limitations
Original rijndael-api source - ECB, CBC, CFB1
OpenSSL - command line CBC, CFB, CFB1, CFB8, ECB, OFB
OpenSSL - C/C++ API CBC, CFB, CFB1, CFB8, ECB, OFB and CTR
EFAES lib [1] - ECB, CBC, PCBC, OFB, CFB, CRT ([sic] CTR mispelled)
OpenAES [2] - ECB, CBC
[1] http://www.codeproject.com/Articles/57478/A-Fast-and-Easy-to-Use-AES-Library
If you are using eclipse and maven for handling dependencies, you may need to take these extra steps to make sure eclipse copies the dependencies properly Maven dependencies not visible in WEB-INF/lib (namely the Deployment Assembly for Dynamic web application)
You can do it like this, too:
<?php
if(isset($_POST['select1'])){
$select1 = $_POST['select1'];
switch ($select1) {
case 'value1':
echo 'this is value1<br/>';
break;
case 'value2':
echo 'value2<br/>';
break;
default:
# code...
break;
}
}
?>
<form action="" method="post">
<select name="select1">
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
Actually there is. There is a static method valueOf in the java.sql.Date
object which does exactly that. So we have
java.util.Date date = java.sql.Date.valueOf(localDate);
and that's it. No explicit setting of time zones because the local time zone is taken implicitly.
From docs:
The provided LocalDate is interpreted as the local date in the local time zone.
The java.sql.Date
subclasses java.util.Date
so the result is a java.util.Date
also.
And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:
LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();
This is borderline programming, but look into using tr:
$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'
Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.
If anyone is using a Navigation Controller and wants all of their navigation controllers to have the black style, you can write an extension to UINavigationController like this in Swift 3 and it will apply to all navigation controllers (instead of assigning it to one controller at a time).
extension UINavigationController {
override open func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.barStyle = UIBarStyle.black
}
}
You can use Nullable{T}
GetValueOrDefault()
method. This will return false if null.
bool? nullableBool = null;
bool actualBool = nullableBool.GetValueOrDefault();
In order to load local images to your React.js application, you need to add require
parameter in media sections like or Image tags, as below:
image={require('./../uploads/temp.jpg')}
OK! I done this soon in my web,I try two ways to create the custom google map marker, this run code use canvg.js is the best compatibility for browser.the Commented-Out Code is not support IE11 urrently.
var marker;_x000D_
var CustomShapeCoords = [16, 1.14, 21, 2.1, 25, 4.2, 28, 7.4, 30, 11.3, 30.6, 15.74, 25.85, 26.49, 21.02, 31.89, 15.92, 43.86, 10.92, 31.89, 5.9, 26.26, 1.4, 15.74, 2.1, 11.3, 4, 7.4, 7.1, 4.2, 11, 2.1, 16, 1.14];_x000D_
_x000D_
function initMap() {_x000D_
var map = new google.maps.Map(document.getElementById('map'), {_x000D_
zoom: 13,_x000D_
center: {_x000D_
lat: 59.325,_x000D_
lng: 18.070_x000D_
}_x000D_
});_x000D_
var markerOption = {_x000D_
latitude: 59.327,_x000D_
longitude: 18.067,_x000D_
color: "#" + "000",_x000D_
text: "ha"_x000D_
};_x000D_
marker = createMarker(markerOption);_x000D_
marker.setMap(map);_x000D_
marker.addListener('click', changeColorAndText);_x000D_
};_x000D_
_x000D_
function changeColorAndText() {_x000D_
var iconTmpObj = createSvgIcon( "#c00", "ok" );_x000D_
marker.setOptions( {_x000D_
icon: iconTmpObj_x000D_
} );_x000D_
};_x000D_
_x000D_
function createMarker(options) {_x000D_
//IE MarkerShape has problem_x000D_
var markerObj = new google.maps.Marker({_x000D_
icon: createSvgIcon(options.color, options.text),_x000D_
position: {_x000D_
lat: parseFloat(options.latitude),_x000D_
lng: parseFloat(options.longitude)_x000D_
},_x000D_
draggable: false,_x000D_
visible: true,_x000D_
zIndex: 10,_x000D_
shape: {_x000D_
coords: CustomShapeCoords,_x000D_
type: 'poly'_x000D_
}_x000D_
});_x000D_
_x000D_
return markerObj;_x000D_
};_x000D_
_x000D_
function createSvgIcon(color, text) {_x000D_
var div = $("<div></div>");_x000D_
_x000D_
var svg = $(_x000D_
'<svg width="32px" height="43px" viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">' +_x000D_
'<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>' +_x000D_
'<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>' +_x000D_
'<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>' +_x000D_
'</svg>'_x000D_
);_x000D_
div.append(svg);_x000D_
_x000D_
var dd = $("<canvas height='50px' width='50px'></cancas>");_x000D_
_x000D_
var svgHtml = div[0].innerHTML;_x000D_
_x000D_
canvg(dd[0], svgHtml);_x000D_
_x000D_
var imgSrc = dd[0].toDataURL("image/png");_x000D_
//"scaledSize" and "optimized: false" together seems did the tricky ---IE11 && viewBox influent IE scaledSize_x000D_
//var svg = '<svg width="32px" height="43px" viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">'_x000D_
// + '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>'_x000D_
// + '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>'_x000D_
// + '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>'_x000D_
// + '</svg>';_x000D_
//var imgSrc = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);_x000D_
_x000D_
var iconObj = {_x000D_
size: new google.maps.Size(32, 43),_x000D_
url: imgSrc,_x000D_
scaledSize: new google.maps.Size(32, 43)_x000D_
};_x000D_
_x000D_
return iconObj;_x000D_
};
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Your Custom Marker </title>_x000D_
<style>_x000D_
/* Always set the map height explicitly to define the size of the div_x000D_
* element that contains the map. */_x000D_
#map {_x000D_
height: 100%;_x000D_
}_x000D_
/* Optional: Makes the sample page fill the window. */_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="map"></div>_x000D_
<script src="https://canvg.github.io/canvg/canvg.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Like Jan It took me a while to get it .. =S So for anyone else who's blinded with frustration.
Props down, events up. That's Vue's Pattern. The point is that if you try to mutate props passing from a parent. It won't work and it just gets overwritten repeatedly by the parent component. Child component can only emit an event to notify parent component to do sth. If you don't like these restrict, you can use VUEX(actually this pattern will suck in complex components structure, you should use VUEX!)
Some special characters give this type of error, so use
$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";
If you are using Gradle, you can add it as a compile
dependency.
Instructions
Make sure you have the Android Support Repository
SDK package installed. Android Studio automatically recognizes this repository during the build process (not sure about plain IntelliJ).
Add the dependency to {project}/build.gradle
dependencies {
compile 'com.android.support:appcompat-v7:+'
}
Click the Sync Project with Gradle Files
button.
EDIT: Looks like these same instructions are on the documentation under Adding libraries with resources -> Using Android Studio
.
The following code returns the wanted "folder" as Path regardless of if it is inside a jar or not.
private Path getFolderPath() throws URISyntaxException, IOException {
URI uri = getClass().getClassLoader().getResource("folder").toURI();
if ("jar".equals(uri.getScheme())) {
FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap(), null);
return fileSystem.getPath("path/to/folder/inside/jar");
} else {
return Paths.get(uri);
}
}
Requires java 7+.
function empty()
does not work for testing empty arrays!
example:
$a=array("","");
if(empty($a)) echo "empty";
else echo "not empty"; //this case is true
a function is necessary:
function is_array_empty($a){
foreach($a as $elm)
if(!empty($elm)) return false;
return true;
}
ok, this is a very old question :) , but i found this thread searching for a solution and i didnt find a good one.
bye (sorry for my english)
I'll just comment you can get a lot of mileage out of table
when trying to "fake" a dictionary also, e.g.
> x <- c("a","a","b","b","b","c")
> (t <- table(x))
x
a b c
2 3 1
> names(t)
[1] "a" "b" "c"
> o <- order(as.numeric(t))
> names(t[o])
[1] "c" "a" "b"
etc.
I just wanted to follow up on something I found working with Python 2.7 on Centos 6. Adding the package_data or data_files as mentioned above did not work for me. I added a MANIFEST.IN with the files I wanted which put the non-python files into the tarball, but did not install them on the target machine via RPM.
In the end, I was able to get the files into my solution using the "options" in the setup/setuptools. The option files let you modify various sections of the spec file from setup.py. As follows.
from setuptools import setup
setup(
name='theProjectName',
version='1',
packages=['thePackage'],
url='',
license='',
author='me',
author_email='[email protected]',
description='',
options={'bdist_rpm': {'install_script': 'filewithinstallcommands'}},
)
file - MANIFEST.in:
include license.txt
file - filewithinstallcommands:
mkdir -p $RPM_BUILD_ROOT/pathtoinstall/
#this line installs your python files
python setup.py install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES
#install license.txt into /pathtoinstall folder
install -m 700 license.txt $RPM_BUILD_ROOT/pathtoinstall/
echo /pathtoinstall/license.txt >> INSTALLED_FILES
Additionally you can use an app like AutoStart if you dont want to modify the code, to launch an android application at startup: AutoStart - No root
I'm sure git subtree is all fine and wonderful, but my subdirectories of git managed code that I wanted to move was all in eclipse. So if you're using egit, it's painfully easy. Take the project you want to move and team->disconnect it, and then team->share it to the new location. It will default to trying to use the old repo location, but you can uncheck the use-existing selection and pick the new place to move it. All hail egit.
You can use paste
:
paste file1.txt file2.txt > fileresults.txt
For me, I tried most of the answers, and didn't work. My Android Studio version is 4.0.1. I changed my git branch to the master branch, and then returned to my own branch, and it worked. This time I could run my branch. So weird I know
HTML
<body>
<div id="load"></div>
<div id="contents">
jlkjjlkjlkjlkjlklk
</div>
</body>
JS
document.onreadystatechange = function () {
var state = document.readyState
if (state == 'interactive') {
document.getElementById('contents').style.visibility="hidden";
} else if (state == 'complete') {
setTimeout(function(){
document.getElementById('interactive');
document.getElementById('load').style.visibility="hidden";
document.getElementById('contents').style.visibility="visible";
},1000);
}
}
CSS
#load{
width:100%;
height:100%;
position:fixed;
z-index:9999;
background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}
Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.
DEMO
http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)
update
Come, let us recurse together.
def locations_of_substring(string, substring):
"""Return a list of locations of a substring."""
substring_length = len(substring)
def recurse(locations_found, start):
location = string.find(substring, start)
if location != -1:
return recurse(locations_found + [location], location+substring_length)
else:
return locations_found
return recurse([], 0)
print(locations_of_substring('this is a test for finding this and this', 'this'))
# prints [0, 27, 36]
No need for regular expressions this way.
html { overflow-y: scroll; }
This css
rule causes a vertical scrollbar to always appear.
Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/
This is the fastest and easiest way that I have found;
while (tableModel.getRowCount()>0)
{
tableModel.removeRow(0);
}
This clears the table lickety split and leaves it ready for new data.
Hopefully this helps someone else.
My issue was that I had commented HTML in a PHP callback function via AJAX that was parsing the comments and return invalid JSON.
Once I removed the commented HTML, all was good and the JSON was parsed with no issues.
componentWillReceiveProps is depcricated since react 16: use getDerivedStateFromProps instead
If I understand correctly, you have a parent component that is passing start_time
down to the ModalBody
component which assigns it to its own state? And you want to update that time from the parent, not a child component.
React has some tips on dealing with this scenario. (Note, this is an old article that has since been removed from the web. Here's a link to the current doc on component props).
Using props to generate state in
getInitialState
often leads to duplication of "source of truth", i.e. where the real data is. This is becausegetInitialState
is only invoked when the component is first created.Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.
Basically, whenever you assign parent's props
to a child's state
the render method isn't always called on prop update. You have to invoke it manually, using the componentWillReceiveProps
method.
componentWillReceiveProps(nextProps) {
// You don't have to do this check first, but it can help prevent an unneeded render
if (nextProps.startTime !== this.state.startTime) {
this.setState({ startTime: nextProps.startTime });
}
}
I know it's a very late answer but I'd like to share what I did as per this link:
I added the below code to the pom.xml:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<id>build-info</id>
<goals>
<goal>build-info</goal>
</goals>
</execution>
</executions>
</plugin>
And this Advice Controller in order to get the version as model attribute:
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
@ControllerAdvice
public class CommonControllerAdvice
{
@Autowired
BuildProperties buildProperties;
@ModelAttribute("version")
public String getVersion() throws IOException
{
String version = buildProperties.getVersion();
return version;
}
}
See String.replaceAll
.
Use the regex "\s"
and replace with " "
.
Then use String.trim
.
From version 1.9 Easier and official way of getting json
from django.http import JsonResponse
from django.forms.models import model_to_dict
return JsonResponse( model_to_dict(modelinstance) )
You can use a lambda with an input parameter, like so:
.Returns((string myval) => { return myval; });
Or slightly more readable:
.Returns<string>(x => x);
You can't.
So just don't apply styles directly like that, and apply a class "foo", and then define that in your CSS specification:
a.foo { color : orange; }
a.foo:hover { font-weight : bold; }
You can also output your file in xdot format, then render it in a browser using canviz, a JavaScript library.
To see an example, there is a "Canviz Demo" link on the page above as of November 2, 2014.
Use your own judgement and be smart. Don't always do what others (like me) are saying. You will hear "prefer interfaces to abstract classes" but it really depends. It depends what the class is.
In the above mentioned case where we have a hierarchy of objects, interface is a good idea. Interface helps to work with collections of these objects and it also helps when implementing a service working with any object of the hierarchy. You just define a contract for working with objects from the hierarchy.
On the other hand when you implement a bunch of services that share a common functionality you can either separate the common functionality into a complete separate class or you can move it up into a common base class and make it abstract so that nobody can instantiate the base class.
Also consider this how to support your abstractions over time. Interfaces are fixed: You release an interface as a contract for a set of functionality that any type can implement. Base classes can be extended over time. Those extensions become part of every derived class.
better way here
if _, ok := dict["foo"]; ok {
//do something here
}
You can use isin
method:
In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})
In [2]: df
Out[2]:
A B
0 5 1
1 6 2
2 3 3
3 4 5
In [3]: df[df['A'].isin([3, 6])]
Out[3]:
A B
1 6 2
2 3 3
And to get the opposite use ~
:
In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
A B
0 5 1
3 4 5
I am using rails 6 and Model.all(:order 'columnName DESC') is not working. I have found the correct answer in OrderInRails
This is very simple.
@variable=Model.order('columnName DESC')
I had a problem with the answer by @mwaskorn, namely that
g.set_xticklabels(rotation=30)
fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add
plt.xticks(rotation=45)
I’ve found the following library to be the most helpful when doing any kind of date math. I’m still amazed nothing like this is part of the .Net framework.
http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET
To attempt command line arguments directly is not possible.
One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).
This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html
so sudo systemctl restart myprog -v
-- systemctl will think you're trying to set one of its flags, not myprog's flag.
sudo systemctl restart myprog someotheroption
-- systemctl will restart myprog and the someotheroption service, if it exists.
Step 1: Create separate component like this
Component name : pagebase.js
Step 2: Inside this use code this
export const BASE_URL = "http://192.168.10.10:4848/";
export const API_KEY = 'key_token';
Step 3: Use it in any component, for using it first import this component then use it. Import it and use it:
import * as base from "./pagebase";
base.BASE_URL
base.API_KEY
GISTS The Gist is an outstanding service provided by GitHub. Using this service, you can share your work publically or privately. You can share a single file, articles, full applications or source code etc.
The GitHub is much more than just Gists. It provides immense services to group together a project or programs digital resources in a centralized location called repository and share among stakeholder. The GitHub repository will hold or maintain the multiple version of the files or history of changes and you can retrieve a specific version of a file when you want. Whereas gist will create each post as a new repository and will maintain the history of the file.
Is adb installed? To check, run the following command in Terminal:
~/Library/Android/sdk/platform-tools/adb
If that prints output, skip these following install steps and go straight to the final Terminal command I list:
Run the following command on your Mac and restart your Terminal session:
echo export "PATH=~/Library/Android/sdk/platform-tools:$PATH" >> ~/.bash_profile
Note: If you've switched to zsh, the above command should use .zshenv
rather than .bash_profile
My solution was to add
location ~ \.php$ {
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/run/php/php7.0-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
to my custom configuration file, for example etc/nginx/sites-available/example.com.conf
Adding to /etc/nginx/sites-available/default
didn't work for me.
Make sure that all functions with non-void return type have a return
statement.
While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.
If you want to throw the latest four commits away, use:
git reset --hard HEAD^^^^
Alternatively, you can specify the hash of a commit you want to reset to:
git reset --hard 6e559cb
Like this:
>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)
The best way to read that is the clockwise/spiral rule by David Anderson.
These are terms usually used when describing a "FIFO" queue, that is "first in, first out". This works like a line. You decide to go to the movies. There is a long line to buy tickets, you decide to get into the queue to buy tickets, that is "Enqueue". at some point you are at the front of the line, and you get to buy a ticket, at which point you leave the line, that is "Dequeue".
Open up terminal first and then go to directory of web server
cd /Library/WebServer/Documents
and then type this and what you will do is you will give read
and write
permission
sudo chmod -R o+w /Library/WebServer/Documents
This will surely work!
Actually for some reason wireshark uses two different kind of filter syntax one on display filter and other on capture filter. Display filter is only useful to find certain traffic just for display purpose only. its like you are interested in all trafic but for now you just want to see specific.
but if you are interested only in certian traffic and does not care about other at all then you use the capture filter.
The Syntax for display filter is (as mentioned earlier)
ip.addr = x.x.x.x
or
ip.src = x.x.x.x
or
ip.dst = x.x.x.x
but above syntax won't work in capture filters, following are the filters
host x.x.x.x
see more example on wireshark wiki page
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
for(int i=0;i<strings.length;i++) {
intarray[i]=Integer.parseInt(strings[i]);
}
for(Integer temp:intarray) {
System.out.println("convert int array from String"+temp);
}
}
If you use eclipse (Eclipse can put utf8 code for you even you write utf8 character. You will see normal utf8 character when you programming but background will be utf8 code) ;
P.S : this will ok if you static value in code. For Example String test = "IIIIIiiiiiiççççç";
You missed the *
in front of NgIf (like we all have, dozens of times):
<div *ngIf="answer.accepted">✔</div>
Without the *
, Angular sees that the ngIf
directive is being applied to the div
element, but since there is no *
or <template>
tag, it is unable to locate a template, hence the error.
If you get this error with Angular v5:
Error: StaticInjectorError[TemplateRef]:
StaticInjectorError[TemplateRef]:
NullInjectorError: No provider for TemplateRef!
You may have <template>...</template>
in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>
.
Try
Where have you specified the mapping code (CreateMap)? Reference: Where do I configure AutoMapper?
If you're using the static Mapper method, configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.asax file for ASP.NET applications.
If the configuration isn't registered before calling the Map method, you will receive Missing type map configuration or unsupported mapping.
As @CraigHyatt mentioned in one of the comments:
"Control Panel -> Programs and Features -> Turn Windows features on or off -> Remote Server Administration Tools -> AD DS and AD LDS Tools"
This worked like a charm in Windows Server 2008. A reboot was necessary, but the Active Directory Users and Computers
snap in was available after that.
Use this function:
function searchThroughArray($search,array $lists){
try{
foreach ($lists as $key => $value) {
if(is_array($value)){
array_walk_recursive($value, function($v, $k) use($search ,$key,$value,&$val){
if(strpos($v, $search) !== false ) $val[$key]=$value;
});
}else{
if(strpos($value, $search) !== false ) $val[$key]=$value;
}
}
return $val;
}catch (Exception $e) {
return false;
}
}
and call function.
print_r(searchThroughArray('breville-one-touch-tea-maker-BTM800XL',$products));
To find a listener on a port, do this:
netstat -tln
You should see a line that looks like this if mysql is indeed listening on that port.
tcp 0 0 127.0.0.1:3306 0.0.0.0:* LISTEN
Port 3306 is MySql's default port.
To connect, you just have to use whatever client you require, such as the basic mysql client.
mysql -h localhost -u user database
Or a url that is interpreted by your library code.
fixed based on How to validate youtube video ids?
<?php
$links = [
"youtube.com/v/tFad5gHoBjY",
"youtube.com/vi/tFad5gHoBjY",
"youtube.com/?v=tFad5gHoBjY",
"youtube.com/?vi=tFad5gHoBjY",
"youtube.com/watch?v=tFad5gHoBjY",
"youtube.com/watch?vi=tFad5gHoBjY",
"youtu.be/tFad5gHoBjY",
"http://youtu.be/qokEYBNWA_0?t=30m26s",
"youtube.com/v/vidid",
"youtube.com/vi/vidid",
"youtube.com/?v=vidid",
"youtube.com/?vi=vidid",
"youtube.com/watch?v=vidid",
"youtube.com/watch?vi=vidid",
"youtu.be/vidid",
"youtube.com/embed/vidid",
"http://youtube.com/v/vidid",
"http://www.youtube.com/v/vidid",
"https://www.youtube.com/v/vidid",
"youtube.com/watch?v=vidid&wtv=wtv",
"http://www.youtube.com/watch?dev=inprogress&v=vidid&feature=related",
"youtube.com/watch?v=7HCZvhRAk-M"
];
foreach($links as $link){
preg_match("#([\/|\?|&]vi?[\/|=]|youtu\.be\/|embed\/)([a-zA-Z0-9_-]+)#", $link, $matches);
var_dump(end($matches));
}
put this code in your html header:
<style type="text/css">
html {
overflow: auto;
}
</style>
A much better way is to use inline-block
, because you don't need to use clear:both
at the end of your list anymore.
Try this:
<ul>
<li>
<a href="#">some item</a>
</li>
<li>
<a href="#">another item</a>
</li>
</ul>
CSS:
ul > li{
display:inline-block;
}
Have a look at it here : http://jsfiddle.net/shahverdy/4N6Ap/
Works fine, except if you have spaces or escaped characters. I don't find the way to capture arguments in this case and send to a ssh inside of script.
This could be useful but is so ugly
_command_opts=$( echo "$@" | awk -F\- 'BEGIN { OFS=" -" } { for (i=2;i<=NF;i++) { gsub(/^[a-z] /,"&@",$i) ; gsub(/ $/,"",$i );gsub (/$/,"@",$i) }; print $0 }' | tr '@' \' )
Your second example is correct; you don't need to delete the monsters
array itself, just the individual objects you created.
=arrayformula(if(isblank(B2:B),iferror(1/0),mmult(sign(B2:B=TRANSPOSE(A2:A)),A2:A)))
I got this from a good tutorial - can't remember the title - probably about using MMult
To work off the answer above (https://stackoverflow.com/a/44860918/2011818), you can also send the objects inline the "To" inside the Link object.
<Route path="/foo/:fooId" component={foo} / >
<Link to={{pathname:/foo/newb, sampleParam: "Hello", sampleParam2: "World!" }}> CLICK HERE </Link>
this.props.match.params.fooId //newb
this.props.location.sampleParam //"Hello"
this.props.location.sampleParam2 //"World!"
React.JS People, remember allowFullScreen
and frameBorder="0"
Without camel-case, react strips these tags out!
Just want to point out something on @codingbadger answer. When using "ProgressBarRenderer" you should always check for "ProgressBarRenderer.IsSupported" before using the class. For me, this has been a nightmare with Visual Styles errors in Win7 that I couldn't fix. So, a better approach and workaround for the solution would be:
Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
if (ProgressBarRenderer.IsSupported)
ProgressBarRenderer.DrawHorizontalChunks(g, clip);
else
g.FillRectangle(new SolidBrush(this.ForeColor), clip);
Notice that the fill will be a simple rectangle and not chunks. Chunks will be used only if ProgressBarRenderer is supported
I was also facing the same issue. The following helped me fix the problem go to control panel-> Administrative tools-->services inside this you will most certainly see the MySQL servce: right click and say start(force start).
You can try as follows it works for me
select * from nm_admission where trunc(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');
OR
select * from nm_admission where trunc(entry_timestamp) = '09-SEP-2018';
You can also try using to_char but remember to_char is too expensive
select * from nm_admission where to_char(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');
The TRUNC(17-SEP-2018 08:30:11) will give 17-SEP-2018 00:00:00 as a result, you can compare the only date portion independently and time portion will skip.
I was pondering a similar problem when asking how the view model for a task or dialog should look like.
My current solution looks like this:
public class SelectionTaskModel<TChoosable> : ViewModel
where TChoosable : ViewModel
{
public SelectionTaskModel(ICollection<TChoosable> choices);
public ReadOnlyCollection<TChoosable> Choices { get; }
public void Choose(TChoosable choosen);
public void Abort();
}
When the view model decides that user input is required, it pulls up a instance of SelectionTaskModel
with the possible choices for the user. The infrastructure takes care of bringing up the corresponding view, which in proper time will call the Choose()
function with the user's choice.
This can be caused by not using the same version clients all over.
Using a version 1.5 client and a version 1.6 client towards the same repository can create this kind of problem. (I was just bitten myself.)
You can use the [TOC] at the first line and then on the bottom, the only thing you need to do is making sure that the titles are in the same bigger font. The table of content would come out automatically. ( But this only appear in some markdown editors, I didn't try all)
Using macros you can check if you're on Windows, Linux, Mac or Unix, and call the respective function depending on the current platform. Something as follows:
void clear(){
#if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
system("clear");
#endif
#if defined(_WIN32) || defined(_WIN64)
system("cls");
#endif
}
right-click the view in the object-explorer, select "script view as...", then "create to" and then "new query editor window"
One way to do it using a List<Character>
constructed using overloaded convenience factory methods in java9 is as :
if(List.of('A','B','C','D','E').contains(symbol) {
// do something
}
I have created the following class and used across the application wherever required in place of GridView
:
/// <summary>
/// Represents a view mode that displays data items in columns for a System.Windows.Controls.ListView control with auto sized columns based on the column content
/// </summary>
public class AutoSizedGridView : GridView
{
protected override void PrepareItem(ListViewItem item)
{
foreach (GridViewColumn column in Columns)
{
// Setting NaN for the column width automatically determines the required
// width enough to hold the content completely.
// If the width is NaN, first set it to ActualWidth temporarily.
if (double.IsNaN(column.Width))
column.Width = column.ActualWidth;
// Finally, set the column with to NaN. This raises the property change
// event and re computes the width.
column.Width = double.NaN;
}
base.PrepareItem(item);
}
}
Without mutations:
const groupBy = (xs, key) => xs.reduce((acc, x) => Object.assign({}, acc, {
[x[key]]: (acc[x[key]] || []).concat(x)
}), {})
console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {3: ["one", "two"], 5: ["three"]}
A char array is returned by char*, but the function you wrote does not work because you are returning an automatic variable that disappears when the function exits.
Use something like this:
char *testfunc() {
char* arr = malloc(100);
strcpy(arr,"xxxx");
return arr;
}
This is of course if you are returning an array in the C sense, not an std:: or boost:: or something else.
As noted in the comment section: remember to free the memory from the caller.
declare @TempTable table([Date] datetime)
insert into @TempTable([Date])
values('2008-01-02'),('2007-08-21')
select datepart(year, [Date]) as [year]
,convert(varchar(10),datepart(year, [Date])) + '-Q' + convert(varchar(3),datename(quarter, [Date])) as quarter_with_year
,datefromparts(datepart(year, [Date]),(convert(varchar(3),datename(quarter, [Date])) * 3)-2,1) as quarter_startdate
,eomonth(datefromparts(datepart(year, [Date]),convert(varchar(3),datename(quarter, [Date])) * 3,1)) as quarter_enddate
FROM @TempTable
This returns the year,quarter, and start end date of quarter.
First day of week (Monday):
SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)-1 first_day_week FROM dual;
Last day of week (Sunday):
SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)+5 last_day_week FROM dual;
Substituting your date or date field in these formulas will work for you!
list(NULL) also works:
dat <- mtcars
colnames(dat)
# [1] "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear"
# [11] "carb"
dat[,c("mpg","cyl","wt")] <- list(NULL)
colnames(dat)
# [1] "disp" "hp" "drat" "qsec" "vs" "am" "gear" "carb"
$("video").prop('muted', true); //mute
AND
$("video").prop('muted', false); //unmute
See all events here
(side note: use attr
if in jQuery < 1.6)
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm()
returns false
, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Within Apache Commons, commons-codec-1.7.jar contains a Base64 class which can be used to encode.
Via Maven:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>20041127.091804</version>
</dependency>
Similar to many of the answers above that use df.to_string(index=False), I often find it necessary to extract a single column of values in which case you can specify an individual column with .to_string using the following:
data = pd.DataFrame({'col1': np.random.randint(0, 100, 10),
'col2': np.random.randint(50, 100, 10),
'col3': np.random.randint(10, 10000, 10)})
print(data.to_string(columns=['col1'], index=False)
print(data.to_string(columns=['col1', 'col2'], index=False))
Which provides an easy to copy (and index free) output for use pasting elsewhere (Excel). Sample output:
col1 col2
49 62
97 97
87 94
85 61
18 55
Updated 2020 Answer
Since Laravel 5.5 the @switch is built into the Blade. Use it as shown below.
@switch($login_error)
@case(1)
<span> `E-mail` input is empty!</span>
@break
@case(2)
<span>`Password` input is empty!</span>
@break
@default
<span>Something went wrong, please try again</span>
@endswitch
Older Answer
Unfortunately Laravel Blade does not have switch statement. You can use Laravel if else approach or use use plain PHP switch. You can use plain PHP in blade templates like in any other PHP application. Starting from Laravel 5.2 and up use @php statement.
Option 1:
@if ($login_error == 1)
`E-mail` input is empty!
@elseif ($login_error == 2)
`Password` input is empty!
@endif
Of course:
curl http://example.com:11740
curl https://example.com:11740
Port 80 and 443 are just default port numbers.
hibernate-distribution-3.6.10.Final\lib\jpa : Add this jar to solve the issue. It is present in lib folder inside that you have a folder called jpa ---> inside that you have hibernate-jpa-2.0-1.0.1.Final jar
You can use this extension method on enum, for any type of enums:
public static bool IsSingle(this Enum value)
{
var items = Enum.GetValues(value.GetType());
var counter = 0;
foreach (var item in items)
{
if (value.HasFlag((Enum)item))
{
counter++;
}
if (counter > 1)
{
return false;
}
}
return true;
}
You have the alias inside of the case, it needs to be outside of the END
:
Insert into TblStuff (FullName,Address,City,Zip)
Select
Case
When Middle is Null
Then Fname + LName
Else Fname +' ' + Middle + ' '+ Lname
End as FullName,
Case
When Address2 is Null Then Address1
else Address1 +', ' + Address2
End as Address,
City as City,
Zip as Zip
from tblImport
What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient
request.
At worst, it won't work.
INFORMATION_SCHEMA
is your friend. It has all kinds of views that show all kinds of schema information. Check your system views. You will find you have three views dealing with constraints, one being CHECK_CONSTRAINTS
.
Not best answer but you can reuse an already created ca bundle using --cert
option of pip
, for instance:
pip install SQLAlchemy==1.1.15 --cert="C:\Users\myUser\certificates\my_ca-bundle.crt"
Handling exceptions at different points in your views could really be cumbersome..What about defining a custom Model Manager, in the models.py file, like
class ContentManager(model.Manager):
def get_nicely(self, **kwargs):
try:
return self.get(kwargs)
except(KeyError, Content.DoesNotExist):
return None
and then including it in the content Model class
class Content(model.Model):
...
objects = ContentManager()
In this way it can be easily dealt in the views i.e.
post = Content.objects.get_nicely(pk = 1)
if post:
# Do something
else:
# This post doesn't exist
Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644
or 755
(spelled (100644
and 100755
; the 100
part means "regular file"):
diff --git a/path b/path
new file mode 100644
The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask
setting, which would normally be 022
to remove write permission from "group" and "other", or 002
to remove write permission only from "other". It might also be 077
if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".
1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664
in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.
The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.
Try looking into the following CSS:
word-wrap:break-word;
Web browsers should not break-up "words" by default so what you are experiencing is normal behaviour of a browser. However you can override this with the word-wrap CSS directive.
You would need to set a width on the overall table then a width on the columns. "width:100%;" should also be OK depending on your requirements.
Using word-wrap may not be what you want however it is useful for showing all of the data without deforming the layout.
Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf
and postgres.conf
files I finally found out that my firewall was overriding everything and therefore blocking connections
List last updated on December 1, 2020:
As of November 30, 2020, AWS now has EC2 Mac instances:
We previously used and had good experiences with:
Here are some other sites that I am aware of:
When we were with MacStadium, we loved them. We had great connectivity/uptime. When I've needed hands-on support to plug in a Time Machine backup, they've been great. They performed a seamless upgrade to better hardware for us over one weekend (when we could afford a bit of downtime), and that went off without a hitch. Highly recommended. (Not affiliated - just happy).
In April of 2020, we stopped using MacStadium, simply because we no longer needed a Mac server. If I need another Mac host, I would be happy to go back to them.
numpy.random.randint
accepts a third argument (size
) , in which you can specify the size of the output array. You can use this to create your DataFrame
-
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
Here - np.random.randint(0,100,size=(100, 4))
- creates an output array of size (100,4)
with random integer elements between [0,100)
.
Demo -
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
which produces:
A B C D
0 45 88 44 92
1 62 34 2 86
2 85 65 11 31
3 74 43 42 56
4 90 38 34 93
5 0 94 45 10
6 58 23 23 60
.. .. .. .. ..
in addition to UseSsl, you have to include smtp port 587 to make it work.
Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'
I had this problem too. I was trying to run an old 32-bit dll in a 64 bit system. I got it working by copying the .dll to the C:\Windows\SysWoW64\ directory and running this:
%systemroot%\SysWoW64\regsvr32 "C:\Windows\SysWoW64\thenameofyourdll.dll"
And also enabling IIS to run 32 bit apps
When I started with $ nohup storm dev-zookeper
,
METHOD1 : using jobs
,
prayagupd@prayagupd:/home/vmfest# jobs -l
[1]+ 11129 Running nohup ~/bin/storm/bin/storm dev-zookeeper &
METHOD2 : using ps
command.
$ ps xw
PID TTY STAT TIME COMMAND
1031 tty1 Ss+ 0:00 /sbin/getty -8 38400 tty1
10582 ? S 0:01 [kworker/0:0]
10826 ? Sl 0:18 java -server -Dstorm.options= -Dstorm.home=/root/bin/storm -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dsto
10853 ? Ss 0:00 sshd: vmfest [priv]
TTY column with ?
=> nohup
running programs.
Description
Reference
$ man ps
# then search /PROCESS STATE CODES
Theres these available options:-
DB2 has several strategies to cope with this problem.
You can use the "scrollable cursor" in feature.
In this case you can open a cursor and, instead of re-issuing a query you can FETCH forward and backward.
This works great if your application can hold state since it doesn't require DB2 to rerun the query every time.
You can use the ROW_NUMBER() OLAP function to number rows and then return the subset you want.
This is ANSI SQL
You can use the ROWNUM pseudo columns which does the same as ROW_NUMBER() but is suitable if you have Oracle skills.
You can use LIMIT and OFFSET if you are more leaning to a mySQL or PostgreSQL dialect.
Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
freopen("path to file", "rb", stdin);
string line;
while(getline(cin, line))
cout << line << endl;
return 0;
}
If you need one ore more fixed-width columns while other columns should resize, try setting both min-width
and max-width
to the same value.
Simplest Understanding for default export
is
Export
is ES6's feature which is used to Export a module(file) and use it in some other module(file).
Default Export:
default export
is the convention if you want to export only one object(variable, function, class) from the file(module).Export or Named Export:
It is used to export the object(variable, function, calss) with the same name.
It is used to export multiple objects from one file.
It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as
operator.
In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.
Here is an alternative solution that I found on the matplotlib mailing list:
import matplotlib.pylab as plt
x = range(1000)
ax = plt.axes()
ax.semilogx(x, x)
ax.xaxis.set_ticks_position('none')
(Posted on behalf of the OP).
I believe I figured it out.
In my case, I added [class*="col-"] {padding: 0 7.5px;};
.
Then added .row {margin: 0 -7.5px;}
.
This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;}
to .row {margin: 0 -8.5px;}
, then it works perfectly.
I have no idea why there is a 1px margin. Maybe someone can explain it?
See the sample I created:
You can create temp stored procedures like:
create procedure #mytemp as
begin
select getdate() into #mytemptable;
end
in an SQL script, but not functions. You could have the proc store it's result in a temp table though, then use that information later in the script ..
Few points
struct Vector y = (struct Vector*)malloc(sizeof(struct Vector));
is wrong
it should be struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector));
since y
holds pointer to struct Vector
.
1st malloc()
only allocates memory enough to hold Vector structure (which is pointer to double + int)
2nd malloc()
actually allocate memory to hold 10 double.
if {le_gur_bond.gur1}="" or IsNull({le_gur_bond.gur1}) Then
""
else
"and " + {le_gur_bond.gur2} + " of "+ {le_gur_bond.grr_2_address2}
The post is old but I found a perfect CSS for the purpose and I want to share it.
A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).
div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
}
The most efficient way would be to always use []byte
instead of string
.
In case you need to print data received from the io.ReadCloser
, the fmt
package can handle []byte
, but it isn't efficient because the fmt
implementation will internally convert []byte
to string
. In order to avoid this conversion, you can implement the fmt.Formatter
interface for a type like type ByteSlice []byte
.
Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.
In your class, do something like this:
public void setSqlResource(Resource sqlResource) {
this.sqlResource = sqlResource;
}
And then in your application context file, in the bean definition, just set a property:
<bean id="someBean" class="...">
<property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>
And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.
You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.
useTimezone is an older workaround. MySQL team rewrote the setTimestamp/getTimestamp code fairly recently, but it will only be enabled if you set the connection parameter useLegacyDatetimeCode=false and you're using the latest version of mysql JDBC connector. So for example:
String url =
"jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false
If you download the mysql-connector source code and look at setTimestamp, it's very easy to see what's happening:
If use legacy date time code = false, newSetTimestampInternal(...) is called. Then, if the Calendar passed to newSetTimestampInternal is NULL, your date object is formatted in the database's time zone:
this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US);
this.tsdf.setTimeZone(this.connection.getServerTimezoneTZ());
timestampString = this.tsdf.format(x);
It's very important that Calendar is null - so make sure you're using:
setTimestamp(int,Timestamp).
... NOT setTimestamp(int,Timestamp,Calendar).
It should be obvious now how this works. If you construct a date: January 5, 2011 3:00 AM in America/Los_Angeles (or whatever time zone you want) using java.util.Calendar and call setTimestamp(1, myDate), then it will take your date, use SimpleDateFormat to format it in the database time zone. So if your DB is in America/New_York, it will construct the String '2011-01-05 6:00:00' to be inserted (since NY is ahead of LA by 3 hours).
To retrieve the date, use getTimestamp(int) (without the Calendar). Once again it will use the database time zone to build a date.
Note: The webserver time zone is completely irrelevant now! If you don't set useLegacyDatetimecode to false, the webserver time zone is used for formatting - adding lots of confusion.
Note:
It's possible MySQL my complain that the server time zone is ambiguous. For example, if your database is set to use EST, there might be several possible EST time zones in Java, so you can clarify this for mysql-connector by telling it exactly what the database time zone is:
String url =
"jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false&serverTimezone=America/New_York";
You only need to do this if it complains.
Your code (or some code called by you) is making a call to a COM method which is returning an unknown value. If you can find that then you're half way there.
You could try breaking when the exception is thrown. Go to Debug > Exceptions... and use the Find... option to locate System.Runtime.InteropServices.COMException
. Tick the option to break when it's thrown and then debug your application.
Hopefully it will break somewhere meaningful and you'll be able to trace back and find the source of the error.
I have solve this problem in my program using:
number_input = float("{:.1f}".format(float(input())))
list.append(number_input)
I've run into the very same issue, when mistakenly named variable with the very same name, as function.
So this:
isLive = isLive(data);
failed, generating OP's mentioned error message.
Fix to this was as simple as changing above line to:
isItALive = isLive(data);
I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.
Notification.Builder API 11 or NotificationCompat.Builder API 1
This is a usage example.
Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
YOUR_PI_REQ_CODE, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.some_img)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
.setTicker(res.getString(R.string.your_ticker))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(res.getString(R.string.your_notif_title))
.setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();
nm.notify(YOUR_NOTIF_ID, n);
My tags were correct but Facebook only scrapes every 24 hours, according to their documentation. Using the Facebook Lint page got the image into Facebook.
Enter your URL here and FB will update the metadata from your page:
https://developers.facebook.com/tools/debug (updated link)
I just had the same problem and discovered an alternative solution using the validation API - works without black magic in all major browsers (Chrome, Firefox, Safari) except IE. This solution simply prevents users from entering invalid values. I also included a fallback for IE, which is not nice but works at least.
Context: onInput function is called on input events, setInputValue is used to set the value of the input element, previousInputValue contains the last valid input value (updated in setInputValue calls).
function onInput (event) {
const inputValue = event.target.value;
// badInput supported on validation api (except IE)
// in IE it will be undefined, so we need strict value check
const badInput = event.target.validity.badInput;
// simply prevent modifying the value
if (badInput === true) {
// it's still possible to enter invalid values in an empty input, so we'll need this trick to prevent that
if (previousInputValue === '') {
setInputValue(' ');
setTimeout(() => {
setInputValue('');
}, 1);
}
return;
}
if (badInput === false) {
setInputValue(inputValue);
return;
}
// fallback case for IE and other abominations
// remove everything from the string expect numbers, point and comma
// replace comma with points (parseFloat works only with points)
let stringVal = String(inputValue)
.replace(/([^0-9.,])/g, '')
.replace(/,/g, '.');
// remove all but first point
const pointIndex = stringVal.indexOf('.');
if (pointIndex !== -1) {
const pointAndBefore = stringVal.substring(0, pointIndex + 1);
const afterPoint = stringVal.substring(pointIndex + 1);
// removing all points after the first
stringVal = `${pointAndBefore}${afterPoint.replace(/\./g, '')}`;
}
const float = parseFloat(stringVal);
if (isNaN(float)) {
// fallback to emptying the input if anything goes south
setInputValue('');
return;
}
setInputValue(stringVal);
}
Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import
to Tkinter
rather than tkinter
(the difference being the capitalization):
import tkinter as tk
#import Tkinter as tk # for python 2
def create_window():
window = tk.Toplevel(root)
root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()
root.mainloop()
This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.
Construct a List<AppMeta>
from the excluded List and use the Except Linq operator.
var ex = excludedAppIds.Select(x => new AppMeta{Id = x}).ToList();
var result = ex.Except(unfilteredApps).ToList();
You should look at the File method of the Controller. This is exactly what it's for. It returns a FilePathResult instead of an ActionResult.
A new answer to an old question: in ES6 you can do shorter:
Math.max(...(x.map(el => el.length)));
I experienced a similar problem where my attempts to use adb
such as adb logcat
provided this error output:
adb server version (40) doesn't match this client (36); killing...
This solution worked for me in 2018 on Ubuntu 18.04 from Android Studio 3.2.1 using terminal.
The commands are as follows:
adb kill-server sudo cp ~/Android/Sdk/platform-tools/adb /usr/bin/adb sudo chmod +x /usr/bin/adb adb start-server
You may need to adjust the cp
command arguments based on the path to Android/
on your system.
2nd generation kudos to my source: https://stackoverflow.com/a/40991118/7015599
You'll have to construct the query-string.
<?php
$ids = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($ids), '?'));
$db = new PDO(...);
$stmt = $db->prepare(
'SELECT *
FROM table
WHERE id IN(' . $inQuery . ')'
);
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $id);
$stmt->execute();
?>
Both chris (comments) and somebodyisintrouble suggested that the foreach-loop ...
(...)
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
$stmt->bindValue(($k+1), $id);
$stmt->execute();
... might be redundant, so the foreach
loop and the $stmt->execute
could be replaced by just ...
<?php
(...)
$stmt->execute($ids);
It is very simple to solve this problem with Activity Result Code Simple try this method
if (reqCode == RECORD_VIDEO) {
if(resCode == RESULT_OK) {
if (uri != null) {
compress();
}
} else if(resCode == RESULT_CANCELED && data!=null){
Toast.makeText(MainActivity.this,"No Video Recorded",Toast.LENGTH_SHORT).show();
}
}
No.
The content-type should be whatever it is known to be, if you know it. application/octet-stream
is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.
You can combine the use of Content-Disposition
with other content-types, such as image/png
or even text/html
to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html
but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).
RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline
to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename
part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.
Hence:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"
Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"
Means "This is a PNG image. Please save it as a file, preferably named picture.png".
Content-Type: image/png
Content-Disposition: inline; filename="picture.png"
Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".
Of those browsers that recognise inline
some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).
The WITH
clause for Common Table Expressions go at the top.
Wrapping every insert in a CTE has the benefit of visually segregating the query logic from the column mapping.
Spot the mistake:
WITH _INSERT_ AS (
SELECT
[BatchID] = blah
,[APartyNo] = blahblah
,[SourceRowID] = blahblahblah
FROM Table1 AS t1
)
INSERT Table2
([BatchID], [SourceRowID], [APartyNo])
SELECT [BatchID], [APartyNo], [SourceRowID]
FROM _INSERT_
Same mistake:
INSERT Table2 (
[BatchID]
,[SourceRowID]
,[APartyNo]
)
SELECT
[BatchID] = blah
,[APartyNo] = blahblah
,[SourceRowID] = blahblahblah
FROM Table1 AS t1
A few lines of boilerplate make it extremely easy to verify the code inserts the right number of columns in the right order, even with a very large number of columns. Your future self will thank you later.
Since it has not been mentioned just for completion. The good ol' filter to filter your to be filtered elements.
Functional programming ftw.
####### Set Up #######
class X:
def __init__(self, val):
self.val = val
elem = 5
my_unfiltered_list = [X(1), X(2), X(3), X(4), X(5), X(5), X(6)]
####### Set Up #######
### Filter one liner ### filter(lambda x: condition(x), some_list)
my_filter_iter = filter(lambda x: x.val == elem, my_unfiltered_list)
### Returns a flippin' iterator at least in Python 3.5 and that's what I'm on
print(next(my_filter_iter).val)
print(next(my_filter_iter).val)
print(next(my_filter_iter).val)
### [1, 2, 3, 4, 5, 5, 6] Will Return: ###
# 5
# 5
# Traceback (most recent call last):
# File "C:\Users\mousavin\workspace\Scripts\test.py", line 22, in <module>
# print(next(my_filter_iter).value)
# StopIteration
# You can do that None stuff or whatever at this point, if you don't like exceptions.
I know that generally in python list comprehensions are preferred or at least that is what I read, but I don't see the issue to be honest. Of course Python is not an FP language, but Map / Reduce / Filter are perfectly readable and are the most standard of standard use cases in functional programming.
So there you go. Know thy functional programming.
filter condition list
It won't get any easier than this:
next(filter(lambda x: x.val == value, my_unfiltered_list)) # Optionally: next(..., None) or some other default value to prevent Exceptions
Follow these steps:
Run below command to see that all the container services both running and stopped on. Option -a
is given to see that the container stops as well
docker ps -a
Then start the docker container either by container_id
or container tag names
docker start <CONTAINER_ID> or <NAMES>
Say from the above picture, container id
4b161b302337
So command to be run is
docker start 4b161b302337
One can verify whether the container is running with
docker ps
I use PyCharm and stand by it all the way. It cost me a little but I have to say the advantage that I get out of it is priceless. I tried debugging from console and I do give people a lot of credit who can do that, but for me being able to visually debug my application(s) is great.
I have to say though, PyCharm does take a lot of memory. But then again, nothing good is free in life. They just came with their latest version 3. It also plays very well with Django, Flask and Google AppEngine. So, all in all, I'd say it's a great handy tool to have for any developer.
If you are not using it yet, I'd recommend to get the trial version for 30 days to take a look at the power of PyCharm. I'm sure there are other tools also available, such as Aptana. But I guess I just also like the way PyCharm looks. I feel very comfortable debugging my apps there.
You can achieve fall through like c++ by the goto keyword.
EX:
switch(num)
{
case 1:
goto case 3;
case 2:
goto case 3;
case 3:
//do something
break;
case 4:
//do something else
break;
case default:
break;
}
In terms of usage, GROUP BY is used for grouping those rows you want to calculate. DISTINCT will not do any calculation. It will show no duplicate rows.
I always used DISTINCT if I want to present data without duplicates.
If I want to do calculations like summing up the total quantity of mangoes, I will use GROUP BY
lib
.lib\__init__.py
.In lib\BoxTime.py
, write a function foo()
like this:
def foo():
print "foo!"
In your client code in the directory above lib
, write:
from lib import BoxTime
BoxTime.foo()
Run your client code. You will get:
foo!
Much later -- in linux, it would look like this:
% cd ~/tmp
% mkdir lib
% touch lib/__init__.py
% cat > lib/BoxTime.py << EOF
heredoc> def foo():
heredoc> print "foo!"
heredoc> EOF
% tree lib
lib
+-- BoxTime.py
+-- __init__.py
0 directories, 2 files
% python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib import BoxTime
>>> BoxTime.foo()
foo!
If you are using on the same domain then you can create a seperate HTML file and then import this using the code from this answer by @Stano :
Do you need to look up objects by the key? If not, consider using List<Tuple<string, string>>
or List<KeyValuePair<string, string>>
if you're not using .NET 4.
C++ supplies a string
class that can be used like this:
#include <string>
#include <iostream>
int main() {
std::string Something = "Some text";
std::cout << Something << std::endl;
}
JSL 1.7
The Oracle documentation mentions:
unchecked
: Unchecked warnings are identified by the string "unchecked". deprecation
: A Java compiler must produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with the annotation @Deprecated is used (i.e. overridden, invoked, or referenced by name), unless: [...] The use is within an entity that is annotated to suppress the warning with the annotation @SuppressWarnings("deprecation"); orIt then explains that implementations can add and document their own:
Compiler vendors should document the warning names they support in conjunction with this annotation type. Vendors are encouraged to cooperate to ensure that the same names work across multiple compilers.
With a vector iterators do no offer any real advantage. The syntax is uglier, longer to type and harder to read.
Iterating over a vector using iterators is not faster and is not safer (actually if the vector is possibly resized during the iteration using iterators will put you in big troubles).
The idea of having a generic loop that works when you will change later the container type is also mostly nonsense in real cases. Unfortunately the dark side of a strictly typed language without serious typing inference (a bit better now with C++11, however) is that you need to say what is the type of everything at each step. If you change your mind later you will still need to go around and change everything. Moreover different containers have very different trade-offs and changing container type is not something that happens that often.
The only case in which iteration should be kept if possible generic is when writing template code, but that (I hope for you) is not the most frequent case.
The only problem present in your explicit index loop is that size
returns an unsigned value (a design bug of C++) and comparison between signed and unsigned is dangerous and surprising, so better avoided. If you use a decent compiler with warnings enabled there should be a diagnostic on that.
Note that the solution is not to use an unsiged as the index, because arithmetic between unsigned values is also apparently illogical (it's modulo arithmetic, and x-1
may be bigger than x
). You instead should cast the size to an integer before using it.
It may make some sense to use unsigned sizes and indexes (paying a LOT of attention to every expression you write) only if you're working on a 16 bit C++ implementation (16 bit was the reason for having unsigned values in sizes).
As a typical mistake that unsigned size may introduce consider:
void drawPolyline(const std::vector<P2d>& points)
{
for (int i=0; i<points.size()-1; i++)
drawLine(points[i], points[i+1]);
}
Here the bug is present because if you pass an empty points
vector the value points.size()-1
will be a huge positive number, making you looping into a segfault.
A working solution could be
for (int i=1; i<points.size(); i++)
drawLine(points[i - 1], points[i]);
but I personally prefer to always remove unsinged
-ness with int(v.size())
.
PS: If you really don't want to think by to yourself to the implications and simply want an expert to tell you then consider that a quite a few world recognized C++ experts agree and expressed opinions on that unsigned values are a bad idea except for bit manipulations.
Discovering the ugliness of using iterators in the case of iterating up to second-last is left as an exercise for the reader.
Unfortunately, no. This feature is not available for facebook albums.
I usually find that the simpler approach of checking the visibility of a particular element (say burger icon) that is only visible on mobile views works well and is far safer than relying on a very complicated regex. That would be difficult to test works 100%.
function isHidden(el) {
return (el.offsetParent === null);
}
You could use numpy.fromfile
, which can read data from both text and binary files. You would first construct a data type, which represents your file format, using numpy.dtype
, and then read this type from file using numpy.fromfile
.
Basically,
LAZY = fetch when needed
EAGER = fetch immediately
There is a syntax problem, because the right syntax to alter command is ALTER TABLE tablename CHANGE OldColumnName NewColunmName DATATYPE;
Here is a different solution, that also allows the replacement of a single group in multiple matches. It uses stacks to reverse the execution order, so the string operation can be safely executed.
private static void demo () {
final String sourceString = "hello world!";
final String regex = "(hello) (world)(!)";
final Pattern pattern = Pattern.compile(regex);
String result = replaceTextOfMatchGroup(sourceString, pattern, 2, world -> world.toUpperCase());
System.out.println(result); // output: hello WORLD!
}
public static String replaceTextOfMatchGroup(String sourceString, Pattern pattern, int groupToReplace, Function<String,String> replaceStrategy) {
Stack<Integer> startPositions = new Stack<>();
Stack<Integer> endPositions = new Stack<>();
Matcher matcher = pattern.matcher(sourceString);
while (matcher.find()) {
startPositions.push(matcher.start(groupToReplace));
endPositions.push(matcher.end(groupToReplace));
}
StringBuilder sb = new StringBuilder(sourceString);
while (! startPositions.isEmpty()) {
int start = startPositions.pop();
int end = endPositions.pop();
if (start >= 0 && end >= 0) {
sb.replace(start, end, replaceStrategy.apply(sourceString.substring(start, end)));
}
}
return sb.toString();
}
You can use $locationChangeStart
event to store the previous value in $rootScope
or in a service. When you come back, just initialize all previously stored values. Here is a quick demo using $rootScope
.
var app = angular.module("myApp", ["ngRoute"]);_x000D_
app.controller("tab1Ctrl", function($scope, $rootScope) {_x000D_
if ($rootScope.savedScopes) {_x000D_
for (key in $rootScope.savedScopes) {_x000D_
$scope[key] = $rootScope.savedScopes[key];_x000D_
}_x000D_
}_x000D_
$scope.$on('$locationChangeStart', function(event, next, current) {_x000D_
$rootScope.savedScopes = {_x000D_
name: $scope.name,_x000D_
age: $scope.age_x000D_
};_x000D_
});_x000D_
});_x000D_
app.controller("tab2Ctrl", function($scope) {_x000D_
$scope.language = "English";_x000D_
});_x000D_
app.config(function($routeProvider) {_x000D_
$routeProvider_x000D_
.when("/", {_x000D_
template: "<h2>Tab1 content</h2>Name: <input ng-model='name'/><br/><br/>Age: <input type='number' ng-model='age' /><h4 style='color: red'>Fill the details and click on Tab2</h4>",_x000D_
controller: "tab1Ctrl"_x000D_
})_x000D_
.when("/tab2", {_x000D_
template: "<h2>Tab2 content</h2> My language: {{language}}<h4 style='color: red'>Now go back to Tab1</h4>",_x000D_
controller: "tab2Ctrl"_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>_x000D_
<body ng-app="myApp">_x000D_
<a href="#/!">Tab1</a>_x000D_
<a href="#!tab2">Tab2</a>_x000D_
<div ng-view></div>_x000D_
</body>_x000D_
</html>
_x000D_
What resolution and density should I set?
How can I indicate that this is large screen device?
What hardware does this tablet support?
What is max heap size?
Which Android version?
Hope that helps - check the spec page for all unanswered questions.
Returning falsy value in the render() function will render nothing. So you can just do
render() {
let finalClasses = "" + (this.state.classes || "");
return !isTimeout && <div>{this.props.children}</div>;
}
This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).
When you type in a command at the Unix prompt, you are interacting with the shell.
E.g., #!/bin/csh
refers to the C-shell, /bin/tcsh
the t-shell, /bin/bash
the bash shell, etc.
You can tell which interactive shell you are using the
echo $SHELL
command, or alternatively
env | grep -i shell
You can change your command shell with the chsh
command.
Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.
This page might be of interest as it "translates" between bash and tcsh commands/syntax.
Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh
shell interactively, but often run bash scripts using /bin/bash in the script file.
Aside:
This concept extends to other scripts too. For instance if you program in Python you'd put
#!/usr/bin/python
at the top of your Python program
string userName;
string userId;
if (HttpContext.Current != null && HttpContext.Current.User != null
&& HttpContext.Current.User.Identity.Name != null)
{
userName = HttpContext.Current.User.Identity.Name;
userId = HttpContext.Current.User.Identity.GetUserId();
}
Or based on Darrel Miller's comment, maybe use this to retrieve the HttpContext first.
// get httpContext
object httpContext;
actionContext.Request.Properties.TryGetValue("MS_HttpContext", out httpContext);
See also:
In Python 3 there is an exit()
function:
elif choice == "q":
exit()
Yes there is possible to close TCP or UDP port there is a command in DOS
TASKKILL /f /pid 1234
I hope this will work for You