Follow the above image to edit rows from 200 to 100,000 Rows
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
'a,b,c,d'
This won't work if the list contains integers
And if the list contains non-string types (such as integers, floats, bools, None) then do:
my_string = ','.join(map(str, my_list))
I would follow this guide: https://github.com/bmoeskau/Extensible/blob/master/recurrence-overview.md
Also make sure you use the iCal format so not to reinvent the wheel and remember Rule #0: Do NOT store individual recurring event instances as rows in your database!
Working demo:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
onload = function(){
var divg = document.createElement("div");
divg.appendChild(document.createTextNode("New DIV"));
document.body.appendChild(divg);
};
</script>
</head>
<body>
</body>
</html>
This is a part from a REST-Service I´ve written recently.
var select = $("#productSelect")
for (var prop in data) {
var option = document.createElement('option');
option.innerHTML = data[prop].ProduktName
option.value = data[prop].ProduktName;
select.append(option)
}
The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.
Here's one that works well in JavaScript. It's in a string because that's what the Dojo widget was expecting.
It matches a 10 digit North America NANP number with optional extension. Spaces, dashes and periods are accepted delimiters.
"^(\\(?\\d\\d\\d\\)?)( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$"
in command line first reach the directory where psql is present then write commands like this:
psql [database name] [username]
and then press enter psql asks for password give the user password:
then write
> \i [full path and file name with extension]
then press enter insertion done.
For me the above solutions were close but added some unwanted /n's and dtype:object, so here's a modified version:
df.groupby(['name', 'month'])['text'].apply(lambda text: ''.join(text.to_string(index=False))).str.replace('(\\n)', '').reset_index()
In this case, you could create e new String from your array of chars and then do an indeoxOf("e") on that String:
System.out.println(new String(list).indexOf("e"));
But in other cases of primitive data types, you'll have to iterate over it.
You can also install gems in your local environment (without sudo
) with
gem install --user-install <gemname>
I recommend that so you don't mess with your system-level configuration even if it's a single-user computer.
You can check where the gems go by looking at gempaths with gem environment
. In my case it's "~/.gem/ruby/1.8".
If you need some binaries from local installs added to your path, you can add something to your bashrc like:
if which ruby >/dev/null && which gem >/dev/null; then
PATH="$(ruby -r rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi
This worked for me:
File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)
clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.
Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.
then in:
Run >> Edit Configurations
Add this line to VM Options:
--module-path /path/to/JavaFX/lib --add-modules=javafx.controls
(oh and don't forget to set the SDK)
You can store the SVG in a variable. Then manipulate the SVG string depending on your needs (i.e., set width, height, color, etc). Then use the result to set the background, e.g.
$circle-icon-svg: '<svg xmlns="http://www.w3.org/2000/svg"><circle cx="10" cy="10" r="10" /></svg>';
$icon-color: #f00;
$icon-color-hover: #00f;
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
@function svg-fill ($svg, $color) {
@return str-replace($svg, '<svg', '<svg fill="#{$color}"');
}
@function svg-size ($svg, $width, $height) {
$svg: str-replace($svg, '<svg', '<svg width="#{$width}"');
$svg: str-replace($svg, '<svg', '<svg height="#{$height}"');
@return $svg;
}
.icon {
$icon-svg: svg-size($circle-icon-svg, 20, 20);
width: 20px; height: 20px; background: url('data:image/svg+xml;utf8,#{svg-fill($icon-svg, $icon-color)}');
&:hover {
background: url('data:image/svg+xml;utf8,#{svg-fill($icon-svg, $icon-color-hover)}');
}
}
I have made a demo too, http://sassmeister.com/gist/4cf0265c5d0143a9e734.
This code makes a few assumptions about the SVG, e.g. that <svg />
element does not have an existing fill colour and that neither width or height properties are set. Since the input is hardcoded in the SCSS document, it is quite easy to enforce these constraints.
Do not worry about the code duplication. gzip compression makes the difference negligible.
It should be understood that from a performance standpoint there are no differences between @temp tables and #temp tables that favor variables. They reside in the same place (tempdb) and are implemented the same way. All the differences appear in additional features. See this amazingly complete writeup: https://dba.stackexchange.com/questions/16385/whats-the-difference-between-a-temp-table-and-table-variable-in-sql-server/16386#16386
Although there are cases where a temp table can't be used such as in table or scalar functions, for most other cases prior to v2016 (where even filtered indexes can be added to a table variable) you can simply use a #temp table.
The drawback to using named indexes (or constraints) in tempdb is that the names can then clash. Not just theoretically with other procedures but often quite easily with other instances of the procedure itself which would try to put the same index on its copy of the #temp table.
To avoid name clashes, something like this usually works:
declare @cmd varchar(500)='CREATE NONCLUSTERED INDEX [ix_temp'+cast(newid() as varchar(40))+'] ON #temp (NonUniqueIndexNeeded);';
exec (@cmd);
This insures the name is always unique even between simultaneous executions of the same procedure.
Now all you need in Python3 is open(Filename, 'r', encoding='utf-8')
[Edit on 2016-02-10 for requested clarification]
Python3 added the encoding parameter to its open function. The following information about the open function is gathered from here: https://docs.python.org/3/library/functions.html#open
open(file, mode='r', buffering=-1,
encoding=None, errors=None, newline=None,
closefd=True, opener=None)
Encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.
So by adding encoding='utf-8'
as a parameter to the open function, the file reading and writing is all done as utf8 (which is also now the default encoding of everything done in Python.)
In my opinion that is easiest and fastest way:
$ npm -v
4.2.0
$ npm install -g npm@latest-3
...
$ npm -v
3.10.10
The accepted answer is correct, but I prefer:
@{int count = 0;}
@foreach (var item in Model.Resources)
{
@Html.Raw(count <= 3 ? "<div class=\"resource-row\">" : "")
// some code
@Html.Raw(count <= 3 ? "</div>" : "")
@(count++)
}
I hope this inspires someone, even though I'm late to the party.
If you want to get everything after |
excluding set character use this code.
[^|]*$
Others solutions \|.*$
Results : | mypcworld
This one [^|]*$
Results : mypcworld
C# is strongly typed so you can't create variables dynamically. You could use an array but a better C# way would be to use a Dictionary as follows. More on C# dictionaries here.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuickTest
{
class Program
{
static void Main(string[] args)
{
Dictionary<string, int> names = new Dictionary<string,int>();
for (int i = 0; i < 10; i++)
{
names.Add(String.Format("name{0}", i.ToString()), i);
}
var xx1 = names["name1"];
var xx2 = names["name2"];
var xx3 = names["name3"];
}
}
}
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20140603-1326
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
512M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms2000m
-Xmx3512m
The following API can be used in c++ as shown in my article.
You need to define several constants:
//
#define GroupAdmin <YOUR GROUP ADMIN MOBILE PHONE>
#define GroupName <YOUR GROUP NAME>
#define CLIENT_ID <YOUR CLIENT ID>
#define CLIENT_SECRET <YOUR CLIENT SECRET>
#define GROUP_API_SERVER L"api.whatsmate.net"
#define GROUP_API_PATH L"/v3/whatsapp/group/text/message/12"
#define IMAGE_SINGLE_API_URL L"http://api.whatsmate.net/v3/whatsapp/group/image/message/12"
//
Then you connect to the API’s endpoint.
hOpenHandle = InternetOpen(_T("HTTP"), INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);
if (hOpenHandle == NULL)
{
return false;
}
hConnectHandle = InternetConnect(hOpenHandle,
GROUP_API_SERVER,
INTERNET_DEFAULT_HTTP_PORT,
NULL, NULL, INTERNET_SERVICE_HTTP,
0, 1);
if (hConnectHandle == NULL)
{
InternetCloseHandle(hOpenHandle);
return false;
}
Then send both header and body and wait for the result that needs to be “OK”.
Step 1 - open an HTTP request:
const wchar_t *AcceptTypes[] = { _T("application/json"),NULL };
HINTERNET hRequest = HttpOpenRequest(hConnectHandle, _T("POST"), GROUP_API_PATH, NULL, NULL, AcceptTypes, 0, 0);
if (hRequest == NULL)
{
InternetCloseHandle(hConnectHandle);
InternetCloseHandle(hOpenHandle);
return false;
}
Step 2 - send the header:
std::wstring HeaderData;
HeaderData += _T("X-WM-CLIENT-ID: ");
HeaderData += _T(CLIENT_ID);
HeaderData += _T("\r\nX-WM-CLIENT-SECRET: ");
HeaderData += _T(CLIENT_SECRET);
HeaderData += _T("\r\n");
HttpAddRequestHeaders(hRequest, HeaderData.c_str(), HeaderData.size(), NULL);
Step 3 - send the message:
std::wstring WJsonData;
WJsonData += _T("{");
WJsonData += _T("\"group_admin\":\"");
WJsonData += groupAdmin;
WJsonData += _T("\",");
WJsonData += _T("\"group_name\":\"");
WJsonData += groupName;
WJsonData += _T("\",");
WJsonData += _T("\"message\":\"");
WJsonData += message;
WJsonData += _T("\"");
WJsonData += _T("}");
const std::string JsonData(WJsonData.begin(), WJsonData.end());
bResults = HttpSendRequest(hRequest, NULL, 0, (LPVOID)(JsonData.c_str()), JsonData.size());
Now just check the result:
TCHAR StatusText[BUFFER_LENGTH] = { 0 };
DWORD StatusTextLen = BUFFER_LENGTH;
HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_TEXT, &StatusText, &StatusTextLen, NULL);
bResults = (StatusTextLen && wcscmp(StatusText, L"OK")==FALSE);
Here it is:
[chr(i) for i in xrange(127)]
The root cause of IllegalStateException exception is a java servlet is attempting to write to the output stream (response) after the response has been committed.
It is always better to ensure that no content is added to the response after the forward or redirect is done to avoid IllegalStateException. It can be done by including a ‘return’ statement immediately next to the forward or redirect statement.
If you want to select only one of two nodes with union operator, you can use this solution:
(//bookstore/book/title | //bookstore/city/zipcode/title)[1]
It might be better to see the standard designed by W3.org. Here is the address: http://www.w3.org/
A "DIV" tag can wrap "P" tag whereas, a "P" tag can not wrap "DIV" tag-so far I know this difference. There may be more other differences.
If the run method ends, the thread will end.
If you use a loop, a proper way is like following:
// In your imlemented Runnable class:
private volatile boolean running = true;
public void run()
{
while (running)
{
...
}
}
public void stopRunning()
{
running = false;
}
Of course returning is the best way.
Trying
ng-keypress="console.log($event)"
ng-keypress="alert(123)"
did nothing for me.
Strangley the sample at https://docs.angularjs.org/api/ng/directive/ngKeypress, which does ng-keypress="count = count + 1", works.
I found an alternate solution, which has pressing Enter invoke the button's ng-click.
<input ng-model="..." onkeypress="if (event.which==13) document.getElementById('button').click()"/>
<button id="button" ng-click="doSomething()">Done</button>
It depends. If it's a dynamically allocated array, that is, you created it calling malloc, then as others suggest you must either save the size of the array/number of elements somewhere or have a sentinel (a struct with a special value, that will be the last one).
If it's a static array, you can sizeof it's size/the size of one element. For example:
int array[10], array_size;
...
array_size = sizeof(array)/sizeof(int);
Note that, unless it's global, this only works in the scope where you initialized the array, because if you past it to another function it gets decayed to a pointer.
Hope it helps.
This might help to match balanced parenthesis.
\s*\w+[(][^+]*[)]\s*
Seeing that it appears you are running using the SQL syntax, try with the correct wild card.
SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4;
Try this...
//global declaration
private TextView timeUpdate;
Calendar calendar;
.......
timeUpdate = (TextView) findViewById(R.id.timeUpdate); //initialize in onCreate()
.......
//in onStart()
calendar = Calendar.getInstance();
//date format is: "Date-Month-Year Hour:Minutes am/pm"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a"); //Date and time
String currentDate = sdf.format(calendar.getTime());
//Day of Name in full form like,"Saturday", or if you need the first three characters you have to put "EEE" in the date format and your result will be "Sat".
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
Date date = new Date();
String dayName = sdf_.format(date);
timeUpdate.setText("" + dayName + " " + currentDate + "");
The result is...
happy coding.....
Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.
If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.
Beware! While it's true that "sort -u" and "sort|uniq" are equivalent, any additional options to sort can break the equivalence. Here's an example from the coreutils manual:
For example, 'sort -n -u' inspects only the value of the initial numeric string when checking for uniqueness, whereas 'sort -n | uniq' inspects the entire line.
Similarly, if you sort on key fields, the uniqueness test used by sort won't necessarily look at the entire line anymore. After being bitten by that bug in the past, these days I tend to use "sort|uniq" when writing Bash scripts. I'd rather have higher I/O overhead than run the risk that someone else in the shop won't know about that particular pitfall when they modify my code to add additional sort parameters.
The abstract version can be:
import numpy as np
myList = [10, 20, 30, 40, 50, 60, 70, 80, 90]
myInt = 10
newList = np.divide(myList, myInt)
Ok, after some time, here's what I landed on:
.parent {_x000D_
position: relative;_x000D_
top: 0;_x000D_
left: 0;_x000D_
}_x000D_
.image1 {_x000D_
position: relative;_x000D_
top: 0;_x000D_
left: 0;_x000D_
border: 1px red solid;_x000D_
}_x000D_
.image2 {_x000D_
position: absolute;_x000D_
top: 30px;_x000D_
left: 30px;_x000D_
border: 1px green solid;_x000D_
}
_x000D_
<div class="parent">_x000D_
<img class="image1" src="https://placehold.it/50" />_x000D_
<img class="image2" src="https://placehold.it/100" />_x000D_
</div>
_x000D_
As the simplest solution. That is:
Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.
<div ng-class="{'has-error': userForm.mobileno.$error.pattern ,'has-success': userForm.mobileno.$valid}">
<input type="text" name="mobileno" ng-model="mobileno" ng-pattern="/^[7-9][0-9]{9}$/" required>
Here "userForm" is my form name.
#!/bin/bash
read X
read Y
echo "$(($X+$Y))"
If you get this error in CollectionView try to create CustomCell file and Custom xib also.
add this code in ViewDidLoad() at mainVC.
let nib = UINib(nibName: "CustomnibName", bundle: nil)
self.collectionView.register(nib, forCellWithReuseIdentifier: "cell")
It worked for me:
Products.find({}).then(a => console.log(a.map(p => p.toJSON())))
also if you want use getters, you should add its option also (on defining schema):
new mongoose.Schema({...}, {toJSON: {getters: true}})
I had this problem too but managed to solve it, the error is that ur computer has saved a git username and password so if you shift to another account the error 403 will appear. Below is the solution For Windows you can find the keys here:
control panel > user accounts > credential manager > Windows credentials > Generic credentials
Next remove the Github keys.
You could do this:
#if __WORDSIZE == 64
char *size = "64bits";
#else
char *size = "32bits";
#endif
In your product.service.ts you are using stringify method in a wrong way..
Just use
JSON.stringify(product)
instead of
JSON.stringify({product})
i have checked your problem and after this it's working absolutely fine.
You could also try like below eg. to show only Outbound Shipments
SELECT shp_awb_no,shpr_ctry_cd, recvr_ctry_cd,
CASE WHEN shpr_ctry_cd = record_ctry_cd
THEN "O"
ELSE "I"
END AS route
FROM shipment_details
WHERE record_ctry_cd = "JP"
AND "O" = CASE WHEN shpr_ctry_cd = record_ctry_cd
THEN "O"
ELSE "I"
END
#include<stdio.h>
void main ()
{
int num;
printf ("=====This Program Converts ASCII to Alphabet!=====\n");
printf ("Enter ASCII: ");
scanf ("%d", &num);
printf("%d is ASCII value of '%c'", num, (char)num );
}
#include<stdio.h>
void main ()
{
char alphabet;
printf ("=====This Program Converts Alphabet to ASCII code!=====\n");
printf ("Enter Alphabet: ");
scanf ("%c", &alphabet);
printf("ASCII value of '%c' is %d", alphabet, (char)alphabet );
}
It just means "different of", some languages uses !=
, others (like SQL) <>
try this
var insert = DateTime.ParseExact(line[i], "M/d/yyyy h:mm", CultureInfo.InvariantCulture);
Quick comparison of timings in response to the post by Abbafei:
import timeit
def func1():
phrase = 'Lucky Dog'
return any(i in 'LD' for i in phrase)
def func2():
phrase = 'Lucky Dog'
if ('L' in phrase) or ('D' in phrase):
return True
else:
return False
if __name__ == '__main__':
func1_time = timeit.timeit(func1, number=100000)
func2_time = timeit.timeit(func2, number=100000)
print('Func1 Time: {0}\nFunc2 Time: {1}'.format(func1_time, func2_time))
Output:
Func1 Time: 0.0737484362111
Func2 Time: 0.0125144964371
So the code is more compact with any, but faster with the conditional.
EDIT : TL;DR -- For long strings, if-then is still much faster than any!
I decided to compare the timing for a long random string based on some of the valid points raised in the comments:
# Tested in Python 2.7.14
import timeit
from string import ascii_letters
from random import choice
def create_random_string(length=1000):
random_list = [choice(ascii_letters) for x in range(length)]
return ''.join(random_list)
def function_using_any(phrase):
return any(i in 'LD' for i in phrase)
def function_using_if_then(phrase):
if ('L' in phrase) or ('D' in phrase):
return True
else:
return False
if __name__ == '__main__':
random_string = create_random_string(length=2000)
func1_time = timeit.timeit(stmt="function_using_any(random_string)",
setup="from __main__ import function_using_any, random_string",
number=200000)
func2_time = timeit.timeit(stmt="function_using_if_then(random_string)",
setup="from __main__ import function_using_if_then, random_string",
number=200000)
print('Time for function using any: {0}\nTime for function using if-then: {1}'.format(func1_time, func2_time))
Output:
Time for function using any: 0.1342546
Time for function using if-then: 0.0201827
If-then is almost an order of magnitude faster than any!
Try using rowMeans
:
z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
I think the solutions being provided have unnecessarily added stuff and does not use semaphores to its full potential. Here's what my solution is.
package com.test.threads;
import java.util.concurrent.Semaphore;
public class EvenOddThreadTest {
public static int MAX = 100;
public static Integer number = new Integer(0);
//Unlocked state
public Semaphore semaphore = new Semaphore(1);
class PrinterThread extends Thread {
int start = 0;
String name;
PrinterThread(String name ,int start) {
this.start = start;
this.name = name;
}
@Override
public void run() {
try{
while(start < MAX){
// try to acquire the number of semaphore equal to your value
// and if you do not get it then wait for it.
semaphore.acquire(start);
System.out.println(name + " : " + start);
// prepare for the next iteration.
start+=2;
// release one less than what you need to print in the next iteration.
// This will release the other thread which is waiting to print the next number.
semaphore.release(start-1);
}
} catch(InterruptedException e){
}
}
}
public static void main(String args[]) {
EvenOddThreadTest test = new EvenOddThreadTest();
PrinterThread a = test.new PrinterThread("Even",1);
PrinterThread b = test.new PrinterThread("Odd", 2);
try {
a.start();
b.start();
} catch (Exception e) {
}
}
}
Here's the answer to my question I got back from Apple support.
Hi XXX,
I am following up with you about the deletion of your app, “XXX”. Recent changes have been made to the App Delete feature. In order to delete your app from iTunes Connect, you must now have one approved version before the delete button becomes available. For more information on the recent changes, please see the "Deleting an App" section of the iTunes Connect Guide (page 96-97):
You can only delete an app from the App Store if it was previously approved (meaning has one approved version).
From iTunes Connect Developer Guide - Transferring and Deleting Apps:
Apps that have not been approved yet can’t be deleted; instead, reject the app.
As of 2016, new changes have been made to iTunes Connect. Here are the screenshots of deleting an approved app from your account.
foreach(Foos foo in Enum.GetValues(typeof(Foos)))
You can't get any better than that.
After all, any solution will have to read the entire file, figure out how many \n
you have, and return that result.
Do you have a better way of doing that without reading the entire file? Not sure... The best solution will always be I/O-bound, best you can do is make sure you don't use unnecessary memory, but it looks like you have that covered.
jQuery way to change value on text input field is:
$('#colorpickerField1').attr('value', '#000000')
this will change attribute value
for the DOM element with ID #colorpickerField1
from #EEEEEE
to #000000
In my case, I needed to watch a service, which contains an address object also watched by several other controllers. I was stuck in a loop until I added the 'true' parameter, which seems to be the key to success when watching objects.
$scope.$watch(function() {
return LocationService.getAddress();
}, function(address) {
//handle address object
}, true);
Nowadays, Alpine images will boot directly into /bin/sh
by default, without having to specify a shell to execute:
$ sudo docker run -it --rm alpine
/ # echo $0
/bin/sh
This is since the alpine
image Dockerfiles now contain a CMD
command, that specifies the shell to execute when the container starts: CMD ["/bin/sh"]
.
In older Alpine image versions (pre-2017), the CMD command was not used, since Docker used to create an additional layer for CMD which caused the image size to increase. This is something that the Alpine image developers wanted to avoid. In recent Docker versions (1.10+), CMD no longer occupies a layer, and so it was added to alpine
images. Therefore, as long as CMD is not overridden, recent Alpine images will boot into /bin/sh
.
For reference, see the following commit to the official Alpine Dockerfiles by Glider Labs:
https://github.com/gliderlabs/docker-alpine/commit/ddc19dd95ceb3584ced58be0b8d7e9169d04c7a3#diff-db3dfdee92c17cf53a96578d4900cb5b
If you want to use dynamic variables
This won't work:
{{#each obj[key]}}
...
{{/each}}
You need to do:
{{#each (lookup obj key)}}
...
{{/each}}
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << stod(" 99.999 ") << endl;
}
Output: 99.999
(which is double, whitespace was automatically stripped)
Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double
I want a function that returns 0 when the string is not numerical.
You can add try catch statement when stod
throws an exception.
buttion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new com.google.zxing.integration.android.IntentIntegrator(Fragment.this).initiateScan();
}
});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.2.0@aar'
compile 'com.google.zxing:core:3.2.1'
compile 'com.android.support:appcompat-v7:23.1.0'
}
It seems you can provide just the local image name, assuming it is in the same folder...
It suffices like:
background-image: url("img1.png")
Code example is given on the author site's. You can use babelfish to translate the texts (Japanese to English).
As far as I understand Japanese, this zip inflate code is meant to decode ZIP data (streams) not ZIP archive.
try this, this will search all MyFolder under root dir and delete all folders named MyFolder
for /d /r "C:\Users\test" %%a in (MyFolder\) do if exist "%%a" rmdir /s /q "%%a"
file:///
is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://
.
It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www
has a file called index.html
located in the assets
folder in the root of the project".
That is how assets are loaded at runtime, for example, a WebView
widget would know exactly where to load the embedded resource file by specifying the file:///
URI.
Consider the code example:
WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");
A very easy mistake to make here is this, some would infer it to as file:///android_assets
, notice the plural of assets in the URI and wonder why the embedded resource is not working!
First of all, stay away from Arraylist
or Hashtable
. Those classes are to be considered deprecated, in favor of generics. They are still in the language for legacy purposes.
Now, what you are looking for is the List<T>
class. Note that if T is a value type you will have contiguos memory, but not if T is a reference type, for obvious reasons.
I know that is late to respond, but there are a basic way to do it, with no libraries. If your number is less than 100, then:
(number/100).toFixed(2).toString().slice(2);
You don't say which version of Excel you are using. This is written for 2007/2010 (a different apprach is required for Excel 2003 )
You also don't say how you are calling addDataToTable
and what you are passing into arrData
.
I'm guessing you are passing a 0
based array. If this is the case (and the Table starts in Column A
) then iCount
will count from 0
and .Cells(lLastRow + 1, iCount)
will try to reference column 0
which is invalid.
You are also not taking advantage of the ListObject
. Your code assumes the ListObject
1 is located starting at row 1
. If this is not the case your code will place the data in the wrong row.
Here's an alternative that utilised the ListObject
Sub MyAdd(ByVal strTableName As String, ByRef arrData As Variant)
Dim Tbl As ListObject
Dim NewRow As ListRow
' Based on OP
' Set Tbl = Worksheets(4).ListObjects(strTableName)
' Or better, get list on any sheet in workbook
Set Tbl = Range(strTableName).ListObject
Set NewRow = Tbl.ListRows.Add(AlwaysInsert:=True)
' Handle Arrays and Ranges
If TypeName(arrData) = "Range" Then
NewRow.Range = arrData.Value
Else
NewRow.Range = arrData
End If
End Sub
Can be called in a variety of ways:
Sub zx()
' Pass a variant array copied from a range
MyAdd "MyTable", [G1:J1].Value
' Pass a range
MyAdd "MyTable", [G1:J1]
' Pass an array
MyAdd "MyTable", Array(1, 2, 3, 4)
End Sub
A little late to the party, so mostly a reminder to me next time I do this search!
I have been able to use:
p/x *(&vec[2])@4
to print 4 elements (as hex) from vec
starting at vec[2]
.
Send HTTP POST/GET request with parameters using HttpURLConnection
:
POST with Parameters:
fun sendPostRequest(userName:String, password:String) {
var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")
val mURL = URL("<Your API Link>")
with(mURL.openConnection() as HttpURLConnection) {
// optional default is GET
requestMethod = "POST"
val wr = OutputStreamWriter(getOutputStream());
wr.write(reqParam);
wr.flush();
println("URL : $url")
println("Response Code : $responseCode")
BufferedReader(InputStreamReader(inputStream)).use {
val response = StringBuffer()
var inputLine = it.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
println("Response : $response")
}
}
}
GET with Parameters:
fun sendGetRequest(userName:String, password:String) {
var reqParam = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
reqParam += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8")
val mURL = URL("<Yout API Link>?"+reqParam)
with(mURL.openConnection() as HttpURLConnection) {
// optional default is GET
requestMethod = "GET"
println("URL : $url")
println("Response Code : $responseCode")
BufferedReader(InputStreamReader(inputStream)).use {
val response = StringBuffer()
var inputLine = it.readLine()
while (inputLine != null) {
response.append(inputLine)
inputLine = it.readLine()
}
it.close()
println("Response : $response")
}
}
}
using System.IO;
...
foreach (string file in Directory.EnumerateFiles(folderPath, "*.xml"))
{
string contents = File.ReadAllText(file);
}
Note the above uses a .NET 4.0 feature; in previous versions replace EnumerateFiles
with GetFiles
). Also, replace File.ReadAllText
with your preferred way of reading xml files - perhaps XDocument
, XmlDocument
or an XmlReader
.
For the Background, make sure you have imported java.awt.Color
into your package.
In your main
method, i.e. public static void main(String[] args)
, call the already imported method:
JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);
NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.
Try this
span {
display: block;
width: 150px;
}
1) putting quotes is a good habit
2) it can be relative path for example:
background-image: url('images/slides/background.jpg');
will look for images folder in the folder from which css is loaded. So if images are in another folder or out of the CSS folder tree you should use absolute path or relative to the root path (starting with /)
3) you should use complete declaration for background-image to make it behave consistently across standards compliant browsers like:
background:blue url('/images/clouds.jpg') no-repeat scroll left center;
Look for Controllers mapped to "/" or with no path mapped.
I had a problem like this, getting 405 errors, and banged my head hard for days. The problem turned out to be a @RestController
annotated controller that I had forgot to annotate with a @RequestMapping
annotation. I guess this mapped path defaulted to "/" and blocked the static content resource mapping.
Sure it's possible... use Export Wizard in source option use SQL SERVER NATIVE CLIENT 11, later your source server ex.192.168.100.65\SQLEXPRESS next step select your new destination server ex.192.168.100.65\SQL2014
Just be sure to be using correct instance and connect each other
Just pay attention in Stored procs must be recompiled
I had a similar problem where the following queries wouldn't work;
update tbl_Lot_Valuation_Details as LVD
set LVD.LGAName = (select LGA.LGA_NAME from tbl_Prop_LGA as LGA where LGA.LGA_CODE = LVD.LGCode)
where LVD.LGAName is null;
update tbl_LOT_VALUATION_DETAILS inner join tbl_prop_LGA on tbl_LOT_VALUATION_DETAILS.LGCode = tbl_prop_LGA.LGA_CODE
set tbl_LOT_VALUATION_DETAILS.LGAName = [tbl_Prop_LGA].[LGA_NAME]
where tbl_LOT_VALUATION_DETAILS.LGAName is null;
However using DLookup resolved the problem;
update tbl_Lot_Valuation_Details as LVD
set LVD.LGAName = dlookup("LGA_NAME", "tbl_Prop_LGA", "LGA_CODE="+LVD.LGCode)
where LVD.LGAName is null;
This solution was originally proposed at https://stackoverflow.com/questions/537161/sql-update-woes-in-ms-access-operation-must-use-an-updateable-query
Using Python will be one easy way to achieve what you want.
I found one using Google.
"convert from json to csv using python" is an example.
You can use from root directory:
RewriteEngine On
RewriteRule ^(?:system)\b.* /403.html
Or:
RewriteRule ^(?:system)\b.* /403.php # with header('HTTP/1.0 403 Forbidden');
With Android Studio 1.4, the template project with boiler plate code sets Overlay
theme on your AppbarLayout and/or Toolbar. They are also set to be rendered behind the status bar by fitSystemWindow
attribute = true. This will cause only toolbar to be rendered directly below the status bar and everything else will rendered beneath the toolbar. So the solutions provided above won't work on their own. You will have to make the following changes.
Put the following code in your styles-21.xml file.
@android:color/transparent
Assign this theme to the activity containing the navigation drawer in the AndroidManifest.xml file.
This will make the Navigation drawer to render behind the transparent status bar.
Try the following in your view to check the output from each. The first one updates when the view is called a second time. My controller uses the key ShowCreateButton and has the optional parameter _createAction with a default value - you can change this to your key/parameter
@Html.TextBox("_createAction", null, new { Value = (string)ViewBag.ShowCreateButton })
@Html.TextBox("_createAction", ViewBag.ShowCreateButton )
@ViewBag.ShowCreateButton
It is not good to use this method but if you really want to split it with regex
<primaryAddress.*>((.|\n)*?)<\/primaryAddress>
the verified answer returns the tags but this just return the value between tags.
In case anyone needed the above in swift :
SWIFT 3.0 and above :
this will capitalize your string, make the first letter capital :
viewNoteDateMonth.text = yourString.capitalized
this will uppercase your string, make all the string upper case :
viewNoteDateMonth.text = yourString.uppercased()
Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.
To clear a canvas, use the delete method. Give it the special parameter "all"
to delete all items on the canvas (the string "all"
" is a special tag that represents all items on the canvas):
canvas.delete("all")
If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all"
, you could supply the name of a tag.
If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.
Your understanding is mostly correct. You use select_related
when the object that you're going to be selecting is a single object, so OneToOneField
or a ForeignKey
. You use prefetch_related
when you're going to get a "set" of things, so ManyToManyField
s as you stated or reverse ForeignKey
s. Just to clarify what I mean by "reverse ForeignKey
s" here's an example:
class ModelA(models.Model):
pass
class ModelB(models.Model):
a = ForeignKey(ModelA)
ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship
The difference is that select_related
does an SQL join and therefore gets the results back as part of the table from the SQL server. prefetch_related
on the other hand executes another query and therefore reduces the redundant columns in the original object (ModelA
in the above example). You may use prefetch_related
for anything that you can use select_related
for.
The tradeoffs are that prefetch_related
has to create and send a list of IDs to select back to the server, this can take a while. I'm not sure if there's a nice way of doing this in a transaction, but my understanding is that Django always just sends a list and says SELECT ... WHERE pk IN (...,...,...) basically. In this case if the prefetched data is sparse (let's say U.S. State objects linked to people's addresses) this can be very good, however if it's closer to one-to-one, this can waste a lot of communications. If in doubt, try both and see which performs better.
Everything discussed above is basically about the communications with the database. On the Python side however prefetch_related
has the extra benefit that a single object is used to represent each object in the database. With select_related
duplicate objects will be created in Python for each "parent" object. Since objects in Python have a decent bit of memory overhead this can also be a consideration.
os.walk is the answer, this will find the first match:
import os
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
And this will find all matches:
def find_all(name, path):
result = []
for root, dirs, files in os.walk(path):
if name in files:
result.append(os.path.join(root, name))
return result
And this will match a pattern:
import os, fnmatch
def find(pattern, path):
result = []
for root, dirs, files in os.walk(path):
for name in files:
if fnmatch.fnmatch(name, pattern):
result.append(os.path.join(root, name))
return result
find('*.txt', '/path/to/dir')
I use Lodash for defensive coding reasons.
In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.
A "fully defensive" approach with Lodash would use both keys as well as get:
const firstKey = _.get(_.keys(ahash), 0);
Add programatically noborder class to specific row to hide it
<style>
.noborder
{
border:none;
}
</style>
<table>
<tr>
<th>heading1</th>
<th>heading2</th>
</tr>
<tr>
<td>content1</td>
<td>content2</td>
</tr>
/*no border for this row */
<tr class="noborder">
<td>content1</td>
<td>content2</td>
</tr>
</table>
Problem fixed, download https://curl.haxx.se/ca/cacert.pem and put it "somewhere", and add this line in php.ini
:
curl.cainfo = "C:/somewhere/cacert.pem"
PS: I got this error by trying to install module on drupal with xampp.
Try this one in Java
for (int i = 6, k = 0; i > 0 && k < 6; i--, k++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
for (int j = 0; j < k; j++) {
System.out.print("*");
}
for (int j = 1; j < k; j++) {
System.out.print("*");
}
System.out.println();
}
If you are sure that it is not a typo spelling-wise, perhaps it is a typo case-wise.
What collation are you using? Check it.
Awesome answers I found here and I also tried this return statement see StatusCode(whatever code you wish)
and it worked!!!
return Ok(new {
Token = new JwtSecurityTokenHandler().WriteToken(token),
Expiration = token.ValidTo,
username = user.FullName,
StatusCode = StatusCode(200)
});
Javascript version of the original function
/**
* Get a center latitude,longitude from an array of like geopoints
*
* @param array data 2 dimensional array of latitudes and longitudes
* For Example:
* $data = array
* (
* 0 = > array(45.849382, 76.322333),
* 1 = > array(45.843543, 75.324143),
* 2 = > array(45.765744, 76.543223),
* 3 = > array(45.784234, 74.542335)
* );
*/
function GetCenterFromDegrees(data)
{
if (!(data.length > 0)){
return false;
}
var num_coords = data.length;
var X = 0.0;
var Y = 0.0;
var Z = 0.0;
for(i = 0; i < data.length; i++){
var lat = data[i][0] * Math.PI / 180;
var lon = data[i][1] * Math.PI / 180;
var a = Math.cos(lat) * Math.cos(lon);
var b = Math.cos(lat) * Math.sin(lon);
var c = Math.sin(lat);
X += a;
Y += b;
Z += c;
}
X /= num_coords;
Y /= num_coords;
Z /= num_coords;
var lon = Math.atan2(Y, X);
var hyp = Math.sqrt(X * X + Y * Y);
var lat = Math.atan2(Z, hyp);
var newX = (lat * 180 / Math.PI);
var newY = (lon * 180 / Math.PI);
return new Array(newX, newY);
}
In my case I had special instruction into nginx configuration file:
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
}
All clients have received '404' because nginx nothing known about Flask.
I hope it help someone.
Please don't use printf("%s", your_string.c_str());
Use cout << your_string;
instead. Short, simple and typesafe. In fact, when you're writing C++, you generally want to avoid printf
entirely -- it's a leftover from C that's rarely needed or useful in C++.
As to why you should use cout
instead of printf
, the reasons are numerous. Here's a sampling of a few of the most obvious:
printf
isn't type-safe. If the type you pass differs from that given in the conversion specifier, printf
will try to use whatever it finds on the stack as if it were the specified type, giving undefined behavior. Some compilers can warn about this under some circumstances, but some compilers can't/won't at all, and none can under all circumstances.printf
isn't extensible. You can only pass primitive types to it. The set of conversion specifiers it understands is hard-coded in its implementation, and there's no way for you to add more/others. Most well-written C++ should use these types primarily to implement types oriented toward the problem being solved.It makes decent formatting much more difficult. For an obvious example, when you're printing numbers for people to read, you typically want to insert thousands separators every few digits. The exact number of digits and the characters used as separators varies, but cout
has that covered as well. For example:
std::locale loc("");
std::cout.imbue(loc);
std::cout << 123456.78;
The nameless locale (the "") picks a locale based on the user's configuration. Therefore, on my machine (configured for US English) this prints out as 123,456.78
. For somebody who has their computer configured for (say) Germany, it would print out something like 123.456,78
. For somebody with it configured for India, it would print out as 1,23,456.78
(and of course there are many others). With printf
I get exactly one result: 123456.78
. It is consistent, but it's consistently wrong for everybody everywhere. Essentially the only way to work around it is to do the formatting separately, then pass the result as a string to printf
, because printf
itself simply will not do the job correctly.
printf
format strings can be quite unreadable. Even among C programmers who use printf
virtually every day, I'd guess at least 99% would need to look things up to be sure what the #
in %#x
means, and how that differs from what the #
in %#f
means (and yes, they mean entirely different things).All you need to do is use the file object as an iterator.
for line in open("log.txt"):
do_something_with(line)
Even better is using context manager in recent Python versions.
with open("log.txt") as fileobject:
for line in fileobject:
do_something_with(line)
This will automatically close the file as well.
Communicating through processes
Example:
Python: This python code block should return random temperatures.
# sensor.py
import random, time
while True:
time.sleep(random.random() * 5) # wait 0 to 5 seconds
temperature = (random.random() * 20) - 5 # -5 to 15
print(temperature, flush=True, end='')
Javascript (Nodejs): Here we will need to spawn a new child process to run our python code and then get the printed output.
// temperature-listener.js
const { spawn } = require('child_process');
const temperatures = []; // Store readings
const sensor = spawn('python', ['sensor.py']);
sensor.stdout.on('data', function(data) {
// convert Buffer object to Float
temperatures.push(parseFloat(data));
console.log(temperatures);
});
def datetime_to_epoch(d1):
# create 1,1,1970 in same timezone as d1
d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
time_delta = d1 - d2
ts = int(time_delta.total_seconds())
return ts
def epoch_to_datetime_string(ts, tz_name="UTC"):
x_timezone = timezone(tz_name)
d1 = datetime.fromtimestamp(ts, x_timezone)
x = d1.strftime("%d %B %Y %H:%M:%S")
return x
Maybe something like this:
import matplotlib.pyplot
import pylab
x = [1,2,3,4]
y = [3,4,8,6]
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
EDIT:
Let me see if I understand you correctly now:
You have:
test1 | test2 | test3
test3 | 1 | 0 | 1
test4 | 0 | 1 | 0
test5 | 1 | 1 | 0
Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.
Let's say you results are stored in a 2-D list:
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
We want to transform them into two variables so we are able to plot them.
And I believe this code will give you what you are looking for:
import matplotlib
import pylab
results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]
x = []
y = []
for ind_1, sublist in enumerate(results):
for ind_2, ele in enumerate(sublist):
if ele == 1:
x.append(ind_1)
y.append(ind_2)
matplotlib.pyplot.scatter(x,y)
matplotlib.pyplot.show()
Notice that I do need to import pylab
, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.
Why do you use Restrictions.like(...
)?
You should use Restrictions.eq(...)
.
Note you can also use .le
, .lt
, .ge
, .gt
on date objects as comparison operators. LIKE
operator is not appropriate for this case since LIKE
is useful when you want to match results according to partial content of a column.
Please see http://www.sql-tutorial.net/SQL-LIKE.asp for the reference.
For example if you have a name column with some people's full name, you can do where name like 'robert %'
so that you will return all entries with name starting with 'robert '
(%
can replace any character).
In your case you know the full content of the date you're trying to match so you shouldn't use LIKE
but equality. I guess Hibernate doesn't give you any exception in this case, but anyway you will probably have the same problem with the Restrictions.eq(...)
.
Your date object you got with the code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
Date date = formatter.parse(myDate);
This date object is equals to the 17-04-2011 at 0h, 0 minutes, 0 seconds and 0 nanoseconds.
This means that your entries in database must have exactly that date. What i mean is that if your database entry has a date "17-April-2011 19:20:23.707000000", then it won't be retrieved because you just ask for that date: "17-April-2011 00:00:00.0000000000".
If you want to retrieve all entries of your database from a given day, you will have to use the following code:
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-YYYY");
String myDate = "17-04-2011";
// Create date 17-04-2011 - 00h00
Date minDate = formatter.parse(myDate);
// Create date 18-04-2011 - 00h00
// -> We take the 1st date and add it 1 day in millisecond thanks to a useful and not so known class
Date maxDate = new Date(minDate.getTime() + TimeUnit.DAYS.toMillis(1));
Conjunction and = Restrictions.conjunction();
// The order date must be >= 17-04-2011 - 00h00
and.add( Restrictions.ge("orderDate", minDate) );
// And the order date must be < 18-04-2011 - 00h00
and.add( Restrictions.lt("orderDate", maxDate) );
GPS, the Global Positioning System run by the United States Military, is free for civilian use, though the reality is that we're paying for it with tax dollars.
However, GPS on cell phones is a bit more murky. In general, it won't cost you anything to turn on the GPS in your cell phone, but when you get a location it usually involves the cell phone company in order to get it quickly with little signal, as well as get a location when the satellites aren't visible (since the gov't requires a fix even if the satellites aren't visible for emergency 911 purposes). It uses up some cellular bandwidth. This also means that for phones without a regular GPS receiver, you cannot use the GPS at all if you don't have cell phone service.
For this reason most cell phone companies have the GPS in the phone turned off except for emergency calls and for services they sell you (such as directions).
This particular kind of GPS is called assisted GPS (AGPS), and there are several levels of assistance used.
A normal GPS receiver listens to a particular frequency for radio signals. Satellites send time coded messages at this frequency. Each satellite has an atomic clock, and sends the current exact time as well.
The GPS receiver figures out which satellites it can hear, and then starts gathering those messages. The messages include time, current satellite positions, and a few other bits of information. The message stream is slow - this is to save power, and also because all the satellites transmit on the same frequency and they're easier to pick out if they go slow. Because of this, and the amount of information needed to operate well, it can take 30-60 seconds to get a location on a regular GPS.
When it knows the position and time code of at least 3 satellites, a GPS receiver can assume it's on the earth's surface and get a good reading. 4 satellites are needed if you aren't on the ground and you want altitude as well.
As you saw above, it can take a long time to get a position fix with a normal GPS. There are ways to speed this up, but unless you're carrying an atomic clock with you all the time, or leave the GPS on all the time, then there's always going to be a delay of between 5-60 seconds before you get a location.
In order to save cost, most cell phones share the GPS receiver components with the cellular components, and you can't get a fix and talk at the same time. People don't like that (especially when there's an emergency) so the lowest form of GPS does the following:
This saves a lot of money on the phone design, but it has a heavy load on cellular bandwidth, and with a lot of requests coming it requires a lot of fast servers. Still, overall it can be cheaper and faster to implement. They are reluctant, however, to release GPS based features on these phones due to this load - so you won't see turn by turn navigation here.
More recent designs include a full GPS chip. They still get data from the phone company - such as current location based on tower positioning, and current satellite locations - this provides sub 1 second fix times. This information is only needed once, and the GPS can keep track of everything after that with very little power. If the cellular network is unavailable, then they can still get a fix after awhile. If the GPS satellites aren't visible to the receiver, then they can still get a rough fix from the cellular towers.
But to completely answer your question - it's as free as the phone company lets it be, and so far they do not charge for it at all. I doubt that's going to change in the future. In the higher end phones with a full GPS receiver you may even be able to load your own software and access it, such as with mologogo on a motorola iDen phone - the J2ME development kit is free, and the phone is only $40 (prepaid phone with $5 credit). Unlimited internet is about $10 a month, so for $40 to start and $10 a month you can get an internet tracking system. (Prices circa August 2008)
It's only going to get cheaper and more full featured from here on out...
Re: Google maps and such
Yes, Google maps and all other cell phone mapping systems require a data connection of some sort at varying times during usage. When you move far enough in one direction, for instance, it'll request new tiles from its server. Your average phone doesn't have enough storage to hold a map of the US, nor the processor power to render it nicely. iPhone would be able to if you wanted to use the storage space up with maps, but given that most iPhones have a full time unlimited data plan most users would rather use that space for other things.
There's also this quick (and somewhat dirty) one-liner:
$linecount=0; $i=0; Get-Content .\BIG_LOG_FILE.txt | %{ Add-Content OUT$i.log "$_"; $linecount++; if ($linecount -eq 3000) {$I++; $linecount=0 } }
You can tweak the number of first lines per batch by changing the hard-coded 3000 value.
I was trying to upgrade my anaconda 2 with anaconda 3. I tried installing Anaconda3-2018.12-Windows-x86 and Anaconda3-2019.03-Windows-x86_64 on my Windows 10 machine and failed with this error. For me, using Anaconda3-4.4.0-Windows-x86_64 for anaconda 3 worked the trick after trying everything listed in answers here.
You can implicitly convert between numerical types, even when that loses precision:
char c = i;
However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast
for the conversion.
Of the other casts:
dynamic_cast
only works for pointers or references to polymorphic class types;const_cast
can't change types, only const
or volatile
qualifiers;reinterpret_cast
is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.static_cast
, const_cast
and reinterpret_cast
is needed to get the job done.I've had success mutex-promise.
I agree with other answers that you might not need locking in your case. But it's not true that one never needs locking in Javascript. You need mutual exclusivity when accessing external resources that do not handle concurrency.
For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.
Try something like
convert -density 300 image.eps -resize 1024x1024 image.jpg
Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.
The order of the arguments matters! The -density X
argument needs to go before image.eps
because you want to affect the resolution that the input file is rendered at.
This is not super obvious in the manpage for convert
, but is hinted at:
SYNOPSIS
convert [input-option] input-file [output-option] output-file
Check it Out-->
For getting text
$("#selme").change(function(){
$(this[this.selectedIndex]).text();
});
For getting value
$("#selme").change(function(){
$(this[this.selectedIndex]).val();
});
If you need a simple working solution, try using DefaultTableModel.
If you have created your own table model, that extends AbstractTableModel, then you should also implement removeRow() method. The exact implementation depends on the underlying structure, that you have used to store data.
For example, if you have used Vector, then it may be something like this:
public class SimpleTableModel extends AbstractTableModel {
private Vector<String> columnNames = new Vector<String>();
// Each value in the vector is a row; String[] - row data;
private Vector<String[]> data = new Vector<String[]>();
...
public String getValueAt(int row, int col) {
return data.get(row)[col];
}
...
public void removeRow(int row) {
data.removeElementAt(row);
}
}
If you have used List, then it would be very much alike:
// Each item in the list is a row; String[] - row data;
List<String[]> arr = new ArrayList<String[]>();
public void removeRow(int row) {
data.remove(row);
}
HashMap:
//Integer - row number; String[] - row data;
HashMap<Integer, String[]> data = new HashMap<Integer, String[]>();
public void removeRow(Integer row) {
data.remove(row);
}
And if you are using arrays like this one
String[][] data = { { "a", "b" }, { "c", "d" } };
then you're out of luck, because there is no way to dynamically remove elements from arrays. You may try to use arrays by storing separately some flags notifying which rows are deleted and which are not, or by some other devious way, but I would advise against it... That would introduce unnecessary complexity, and would in fact just be solving a problem by creating another. That's a sure-fire way to end up here. Try one of the above ways to store your table data instead.
For better understanding of how this works, and what to do to make your own model work properly, I strongly advise you to refer to Java Tutorial, DefaultTableModel API and it's source code.
I have this in my .vimrc file:
imap <F5> <Esc>:w<CR>:!clear;python %<CR>
When I'm done editing a Python script, I just press <F5>
. The script is saved and then executed in a blank screen.
For kotlin lovers.
fun numberPickerCustom() {
val d = AlertDialog.Builder(context)
val inflater = this.layoutInflater
val dialogView = inflater.inflate(R.layout.number_picker_dialog, null)
d.setTitle("Title")
d.setMessage("Message")
d.setView(dialogView)
val numberPicker = dialogView.findViewById<NumberPicker>(R.id.dialog_number_picker)
numberPicker.maxValue = 15
numberPicker.minValue = 1
numberPicker.wrapSelectorWheel = false
numberPicker.setOnValueChangedListener { numberPicker, i, i1 -> println("onValueChange: ") }
d.setPositiveButton("Done") { dialogInterface, i ->
println("onClick: " + numberPicker.value)
}
d.setNegativeButton("Cancel") { dialogInterface, i -> }
val alertDialog = d.create()
alertDialog.show()
}
and number_picker_dialog.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:gravity="center_horizontal">
<NumberPicker
android:id="@+id/dialog_number_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
One more solution for the pile, change your .m file to .mm so that it becomes Objective-C++ and use C++ raw literals, like this:
const char *sql_query = R"(SELECT word_id
FROM table1, table2
WHERE table2.word_id = table1.word_id
ORDER BY table1.word ASC)";
Raw literals ignore everything until the termination sequence, which in the default case is parenthesis-quote.
If the parenthesis-quote sequence has to appear in the string somewhere, you can easily specify a custom delimiter too, like this:
const char *sql_query = R"T3RM!N8(
SELECT word_id
FROM table1, table2
WHERE table2.word_id = table1.word_id
ORDER BY table1.word ASC
)T3RM!N8";
If your platform matrix supports Java 7 then you can use like below
List<List<String>> myList = new ArrayList<>();
it depends what sort of t-test you want to do (one sided or two sided dependent or independent) but it should be as simple as:
from scipy.stats import ttest_ind
cat1 = my_data[my_data['Category']=='cat1']
cat2 = my_data[my_data['Category']=='cat2']
ttest_ind(cat1['values'], cat2['values'])
>>> (1.4927289925706944, 0.16970867501294376)
it returns a tuple with the t-statistic & the p-value
see here for other t-tests http://docs.scipy.org/doc/scipy/reference/stats.html
The isConnected
method won't help, it will return true
even if the remote side has closed the socket. Try this:
public class MyServer {
public static final int PORT = 12345;
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(PORT);
Socket s = ss.accept();
Thread.sleep(5000);
ss.close();
s.close();
}
}
public class MyClient {
public static void main(String[] args) throws IOException, InterruptedException {
Socket s = SocketFactory.getDefault().createSocket("localhost", MyServer.PORT);
System.out.println(" connected: " + s.isConnected());
Thread.sleep(10000);
System.out.println(" connected: " + s.isConnected());
}
}
Start the server, start the client. You'll see that it prints "connected: true" twice, even though the socket is closed the second time.
The only way to really find out is by reading (you'll get -1 as return value) or writing (an IOException
(broken pipe) will be thrown) on the associated Input/OutputStreams.
var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();
Where unixtime
is the time returned by your sql db. Here is a fiddle if it helps.
For example, using it for the current time:
document.write( new Date().toUTCString() );
_x000D_
Bourne shell doesn't support arrays. However, there are two ways to handle the issue.
Use positional shell parameters $1, $2, etc.:
$ set one two three
$ echo $*
one two three
$ echo $#
3
$ echo $2
two
Use variable evaluations:
$ n=1 ; eval a$n="one"
$ n=2 ; eval a$n="two"
$ n=3 ; eval a$n="three"
$ n=2
$ eval echo \$a$n
two
If you look at the docs for bytes
, it points you to bytearray
:
bytearray([source[, encoding[, errors]]])
Return a new array of bytes. The bytearray type is a mutable sequence of integers in the range 0 <= x < 256. It has most of the usual methods of mutable sequences, described in Mutable Sequence Types, as well as most methods that the bytes type has, see Bytes and Byte Array Methods.
The optional source parameter can be used to initialize the array in a few different ways:
If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
If it is an integer, the array will have that size and will be initialized with null bytes.
If it is an object conforming to the buffer interface, a read-only buffer of the object will be used to initialize the bytes array.
If it is an iterable, it must be an iterable of integers in the range 0 <= x < 256, which are used as the initial contents of the array.
Without an argument, an array of size 0 is created.
So bytes
can do much more than just encode a string. It's Pythonic that it would allow you to call the constructor with any type of source parameter that makes sense.
For encoding a string, I think that some_string.encode(encoding)
is more Pythonic than using the constructor, because it is the most self documenting -- "take this string and encode it with this encoding" is clearer than bytes(some_string, encoding)
-- there is no explicit verb when you use the constructor.
Edit: I checked the Python source. If you pass a unicode string to bytes
using CPython, it calls PyUnicode_AsEncodedString, which is the implementation of encode
; so you're just skipping a level of indirection if you call encode
yourself.
Also, see Serdalis' comment -- unicode_string.encode(encoding)
is also more Pythonic because its inverse is byte_string.decode(encoding)
and symmetry is nice.
simple we can also use for an imageview
imageView.setColorFilter(ContextCompat.getColor(context,
R.color.COLOR_YOUR_COLOR));
Using angular 1.5.9
I made it working like this by setting the window.location to the csv file download url. Tested and its working with the latest version of Chrome and IE11.
Angular
$scope.downloadStats = function downloadStats{
var csvFileRoute = '/stats/download';
$window.location = url;
}
html
<a target="_self" ng-click="downloadStats()"><i class="fa fa-download"></i> CSV</a>
In php set the below headers for the response:
$headers = [
'content-type' => 'text/csv',
'Content-Disposition' => 'attachment; filename="export.csv"',
'Cache-control' => 'private, must-revalidate, post-check=0, pre-check=0',
'Content-transfer-encoding' => 'binary',
'Expires' => '0',
'Pragma' => 'public',
];
top
refers to the window object which contains all the current frames ( father of the rest of the windows ). window
is the current window
.
http://www.howtocreate.co.uk/tutorials/javascript/browserinspecific
so top.location.href
can contain the "master" page link containing all the frames, while window.location.href
just contains the "current" page link.
What you are after are numerical indexes in the way classic arrays work, however there is no such thing with json object/associative arrays.
"key1", "key2" themeselves are the indexes and there is no numerical index associated with them. If you want to have such functionality you have to assiciate them yourself.
Also note that setting a header to "text/plain"
will result in all html and php (in part) printing the characters on the screen as TEXT, not as HTML. So be aware of possible HTML not parsing when using text type plain
.
Using:
header('Content-type: text/html; charset=utf-8');
Can return HTML and PHP as well. Not just text.
ZShape
is not static so it requires an instance of the outer class.
The simplest solution is to make ZShape and any nested class static
if you can.
I would also make any fields final
or static final
that you can as well.
From Collections#synchronizedList(List)
javadoc
Returns a synchronized (thread-safe) list backed by the specified list. In order to guarantee serial access, it is critical that all access to the backing list is accomplished through the returned list ... It is imperative that the user manually synchronize on the returned list when iterating over it. Failure to follow this advice may result in non-deterministic behavior.
To add to the good answer by @Tomalak:
Here are some unmentioned and important differences:
xsl:apply-templates
is much richer and deeper than xsl:call-templates
and even from xsl:for-each
, simply because we don't know what code will be applied on the nodes of
the selection -- in the general case this code will be different for
different nodes of the node-list.
The code that will be applied
can be written way after the xsl:apply template
s was written and by
people that do not know the original author.
The FXSL library's implementation of higher-order functions (HOF) in XSLT wouldn't be possible if XSLT didn't have the <xsl:apply-templates>
instruction.
Summary: Templates and the <xsl:apply-templates>
instruction is how XSLT implements and deals with polymorphism.
Reference: See this whole thread: http://www.biglist.com/lists/lists.mulberrytech.com/xsl-list/archives/200411/msg00546.html
You can upgrade to Subversion 1.7. In order to update to Subversion 1.7 you have to launch existing project in Xcode 5 or above. This will prompt an warning ‘The working copy ProjectName should be upgraded to Subversion 1.7
’ (shown in below screenshot).
You should select ‘Upgrade
’ button to upgrade to Subversion 1.7. This will take a bit of time.
If you are using terminal then you can upgrade to Subversion 1.7 by running below command in your project directory: svn upgrade
Note that once you have upgraded to Subversion 1.7 you cannot go back to Subversion 1.6.
To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.
The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.
You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.
$array = array(
'something' => array(1,2,3),
'somethingelse' => array(1,2,3,4)
);
$last_value = end($array);
$last_key = key($array); // 'somethingelse'
This works because PHP moves it's array pointer internally for $array
Faced same problem. Problem lies in required version not installed. Hack is simple Goto Platforms>platforms.json Edit platforms.json in front of android modify the version to the one which is installed on system.
You could use pandas
:
In [1]: import pandas as pd
In [2]: a = [[1.2,'abc',3],[1.2,'werew',4],[1.4,'qew',2]]
In [3]: my_df = pd.DataFrame(a)
In [4]: my_df.to_csv('my_csv.csv', index=False, header=False)
World of Warcraft's engine seems all right, and it uses Lua. :)
You must use
filter:{color_name:by_colour}
instead of
filter:by_colour
If you want to match with a single property of an object, then write that property instead of object, otherwise some other property will get match.
HttpParams is intended to be immutable. The set
and append
methods don't modify the existing instance. Instead they return new instances, with the changes applied.
let params = new HttpParams().set('aaa', 'A'); // now it has aaa
params = params.set('bbb', 'B'); // now it has both
This approach works well with method chaining:
const params = new HttpParams()
.set('one', '1')
.set('two', '2');
...though that might be awkward if you need to wrap any of them in conditions.
Your loop works because you're grabbing a reference to the returned new instance. The code you posted that doesn't work, doesn't. It just calls set() but doesn't grab the result.
let httpParams = new HttpParams().set('aaa', '111'); // now it has aaa
httpParams.set('bbb', '222'); // result has both but is discarded
Another usage of colon in JavaScript is to rename a variable, that is:
const person = {
nickNameThatIUseOnStackOverflow: "schlingel",
age: 30,
firstName: "John"
};
let { nickNameThatIUseOnStackOverflow: nick } = person; // I take nickNameThatIUseOnStackOverflow but want to refer it as "nick" from now on.
nick = "schling";
This is useful if you use a third party library that returns values having awkward / long variable names that you want to rename in your code.
Probably you might be interested in timer like this : H : M : S . Msec.
the code in Linux OS:
#include <iostream>
#include <unistd.h>
using namespace std;
void newline();
int main() {
int msec = 0;
int sec = 0;
int min = 0;
int hr = 0;
//cout << "Press any key to start:";
//char start = _gtech();
for (;;)
{
newline();
if(msec == 1000)
{
++sec;
msec = 0;
}
if(sec == 60)
{
++min;
sec = 0;
}
if(min == 60)
{
++hr;
min = 0;
}
cout << hr << " : " << min << " : " << sec << " . " << msec << endl;
++msec;
usleep(100000);
}
return 0;
}
void newline()
{
cout << "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
}
You could use macros to simulate the repeat-until syntax.
#define repeat do
#define until(exp) while(!(exp))
Currently (November 2009), I am testing with jdk6 update 17 the following configuration set of options (with Galileo -- eclipse 3.5.x, see below for 3.4 or above for Helios 3.6.x):
(of course, adapt the relative paths present in this eclipse.ini to the correct paths for your setup)
Note: for eclipse3.5, replace startup
and launcher.library
lines by:
-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-data
../../workspace
-showlocation
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
384m
-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-vm
../../../../program files/Java/jdk1.6.0_17/jre/bin/client/jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms128m
-Xmx384m
-Xss4m
-XX:PermSize=128m
-XX:MaxPermSize=384m
-XX:CompileThreshold=5
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-Dcom.sun.management.jmxremote
-Dorg.eclipse.equinox.p2.reconciler.dropins.directory=C:/jv/eclipse/mydropins
See also my original answer above for more information.
org.eclipse.equinox.p2.reconciler.dropins.directory
option.There was a bug with ignored breakpoints actually related to the JDK.
Do use JDK6u16 or more recent for launching eclipse (You can then define as many JDKs you want to compile within eclipse: it is not because you launch an eclipse with JDK6 that you will have to compile with that same JDK).
Note the usage of:
--launcher.XXMaxPermSize
384m
-vmargs
-XX:MaxPermSize=128m
As documented in the Eclipse Wiki,
Eclipse 3.3 supports a new argument to the launcher:
--launcher.XXMaxPermSize
.
If the VM being used is a Sun VM and there is not already a-XX:MaxPermSize=
VM argument, then the launcher will automatically add-XX:MaxPermSize=256m
to the list of VM arguments being used.
The 3.3 launcher is only capable of identifying Sun VMs on Windows.
As detailed in this entry:
Not all vms accept the
-XX:MaxPermSize
argument which is why it is passed in this manner. There may (or may not) exist problems with identifying sun vms.
Note: Eclipse 3.3.1 has a bug where the launcher cannot detect a Sun VM, and therefore does not use the correct PermGen size. It seems this may have been a known bug on Mac OS X for 3.3.0 as well.
If you are using either of these platform combination, add the-XX
flag to theeclipse.ini
as described above.Notes:
- the "
384m
" line translates to the "=384m
" part of the VM argument, if the VM is case sensitive on the "m
", then the so is this argument.- the "
--launcher.
" prefix, this specifies that the argument is consumed by the launcher itself and was added to launcher specific arguments to avoid name collisions with application arguments. (Other examples are--launcher.library
,--launcher.suppressErrors
)The
-vmargs -XX:MaxPermSize=384m
part is the argument passed directly to the VM, bypassing the launcher entirely and no check on the VM vendor is used.
Try to start the MySQL server:
mysql.server start
Simply change the default 50px navbar-height by including this to your variable overrides.
You can find this default navbar-height on line 365 and 360 on bootstrap's SASS and LESS variables files respectively.
File location, SASS: bootstrap/assets/stylesheets/bootstrap/_variables.scss
File location, LESS: bootstrap/less/variable.less
I ran into this problem. My case was similar to the LESS
issue posted by rcwxok.
In my case, I set the PAGER
environment variable to PAGER='less -RSF'
.
However, unlike the previous answers, I didn't want to remove the -F
option, because I explicitly put it there hoping to prevent showing the diff in less
if it's shorter than a screenful.
To get the desired result, instead of removing -F
, I added -X
: PAGER='less -RSFX'
. This both solved the git diff
issue and in addition it prevents showing short diffs with less
.
I have tried all the solutions and this one worked for me
let temp = base64String.components(separatedBy: ",")
let dataDecoded : Data = Data(base64Encoded: temp[1], options:
.ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
yourImage.image = decodedimage
EDIT: as of Java8 you'd better use Files
class:
Path resultingPath = Files.createDirectories('A/B');
I don't know if this ultimately fixes your problem but class File
has method mkdirs()
which fully creates the path specified by the file.
File f = new File("/A/B/");
f.mkdirs();
Update
Since the original answer, extname() has been added to the path
module, see Snowfish answer
Original answer:
I'm using this function to get a file extension, because I didn't find a way to do it in an easier way (but I think there is) :
function getExtension(filename) {
var ext = path.extname(filename||'').split('.');
return ext[ext.length - 1];
}
you must require 'path' to use it.
another method which does not use the path module :
function getExtension(filename) {
var i = filename.lastIndexOf('.');
return (i < 0) ? '' : filename.substr(i);
}
encodeURIComponent()
Converts the input into a URL-encoded string
encodeURI()
URL-encodes the input, but assumes a full URL is given, so returns a valid URL by not encoding the protocol (e.g. http://) and host name (e.g. www.stackoverflow.com).
decodeURIComponent()
and decodeURI()
are the opposite of the above
Can you provide an example of what did not work? As you likely know, the Wiring language is based on C/C++, however, not all of C++ is supported.
Whether you are allowed to create classes in the Wiring IDE, I'm not sure (my first Arduino is in the mail right now). I do know that if you wrote a C++ class, compiled it using AVR-GCC, then loaded it on your Arduino using AVRDUDE, it would work.
You can copy your div like this
$(".package").html($(".button").html())
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
I was attempting to find strings with numbers ONLY, no punctuation or anything else. I finally found an answer that would work here.
Using PATINDEX('%[^0-9]%', some_column) = 0 allowed me to filter out everything but actual number strings.
Kotlin's way -
fun Context.bitMapFromImgUrl(imageUrl: String, callBack: (bitMap: Bitmap) -> Unit) {
GlideApp.with(this)
.asBitmap()
.load(imageUrl)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
callBack(resource)
}
override fun onLoadCleared(placeholder: Drawable?) {
// this is called when imageView is cleared on lifecycle call or for
// some other reason.
// if you are referencing the bitmap somewhere else too other than this imageView
// clear it here as you can no longer have the bitmap
}
})
}
We just switched our site to bootstrap 3 and we have a bunch of forms...wasn't fun but once you get the hang it's not too bad.
Is this what you are looking for? Demo Here
<div class="form-group">
<label class="control-label col-sm-offset-2 col-sm-2" for="company">Company</label>
<div class="col-sm-6 col-md-4">
<select id="company" class="form-control">
<option>small</option>
<option>medium</option>
<option>large</option>
</select>
</div>
</div>
changing the Binding Type from wsHttpbinding to basichttp binding in the endpoint tag and from wsHttpbinding to mexhttpbinginding in metadata endpoint tag helped to overcome the error. Thank you...
It must be here, because accepted answer from 2012
In 2018 and modern browsers you can send a custom event from iframe to parent window.
iframe:
var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })
window.parent.document.dispatchEvent(event)
parent:
window.document.addEventListener('myCustomEvent', handleEvent, false)
function handleEvent(e) {
console.log(e.detail) // outputs: {foo: 'bar'}
}
PS: Of course, you can send events in opposite direction same way.
document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)
if dosen't work after
$ npm install lodash --save
$ npm install --save-dev @types/lodash
you try this and import lodash
typings install lodash --save
When you call Business.where(:user_id => current_user.id)
you will get an array. This Array may have no objects or one or many objects in it, but it won't be null. Thus the check == nil will never be true.
You can try the following:
if Business.where(:user_id => current_user.id).count == 0
So you check the number of elements in the array and compare them to zero.
or you can try:
if Business.find_by_user_id(current_user.id).nil?
this will return one or nil.
In python 3 you can easily convert a byte string into a list of integers (0..255) by
>>> list(b'y\xcc\xa6\xbb')
[121, 204, 166, 187]
In Scala, a List inherits from Seq, but implements Product; here is the proper definition of List :
sealed abstract class List[+A] extends AbstractSeq[A] with Product with ...
[Note: the actual definition is a tad bit more complex, in order to fit in with and make use of Scala's very powerful collection framework.]
oracleserviceorcl
service. (From services in Task Manager)ORACLE_SID
variable with orcl
value. (In environment variables)select owner, table_name, num_rows, sample_size, last_analyzed from all_tables;
This is the fastest way to retrieve the row counts but there are a few important caveats:
ESTIMATE_PERCENT => DBMS_STATS.AUTO_SAMPLE_SIZE
(the default), or in earlier versions with ESTIMATE_PERCENT => 100
. See this post for an explanation of how
the AUTO_SAMPLE_SIZE algorithm works in 11g.LAST_ANALYZED
, the current results may be different.<div>It's working fine.....</div>
div
{
height: calc(100vh - 8vw);
background: #000;
overflow:visible;
color: red;
}
Check here this css code right now support All browser without Opera
Live
For Groovy script in the Jenkinsfile using the $BUILD_NUMBER it works.
What about:
<input type="button" style="width:24px;" value="A"/>
Only from code:
namespace xxx.DsXxxTableAdapters {_x000D_
partial class ZzzTableAdapter_x000D_
{_x000D_
public void SetTimeout(int timeout)_x000D_
{_x000D_
if (this.Adapter.DeleteCommand != null) { this.Adapter.DeleteCommand.CommandTimeout = timeout; }_x000D_
if (this.Adapter.InsertCommand != null) { this.Adapter.InsertCommand.CommandTimeout = timeout; }_x000D_
if (this.Adapter.UpdateCommand != null) { this.Adapter.UpdateCommand.CommandTimeout = timeout; }_x000D_
if (this._commandCollection == null) { this.InitCommandCollection(); }_x000D_
if (this._commandCollection != null)_x000D_
{_x000D_
foreach (System.Data.SqlClient.SqlCommand item in this._commandCollection)_x000D_
{_x000D_
if (item != null)_x000D_
{ item.CommandTimeout = timeout; }_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
//...._x000D_
_x000D_
}
_x000D_
Try this:
<script>
document.addEventListener("touchstart", function(){}, true);
</script>
And in your CSS:
element:hover, element:active {
-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-user-select: none;
-webkit-touch-callout: none /*only to disable context menu on long press*/
}
With this code you don't need an extra .hover class!
And to add on to the already solved problem, I had installed Portable Scientific Python on my flash drive E: which on another computer changed to D:, I would get the error "The system cannot find the file specified". So I used parent directory to define the path, like this:
From this:
{
"cmd": ["E:/WPy64-3720/python-3.7.2.amd64/python.exe", "$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
To this:
{
"cmd": ["../../../../WPy64-3720/python-3.7.2.amd64/python.exe","$file"],
"file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
"selector": "source.python"
}
You can modify depending on where your python is installed your python.
I ran into this issue with a Grails install.
The problem was my JAVA_HOME was c:\sun\jdk\
and my PATH has %JAVA_HOME%bin
I changed it to: JAVA_HOME= "c:\sun\jdk" and PATH="%JAVA_HOME%\bin"
It worked after that.
you can use cross apply
:
select
a.x,
bb.y,
bb.z
from
a
cross apply
( select b.y, b.z
from b
where b.v = a.v
) bb
If there will be no row from b to mach row from a then cross apply
wont return row. If you need such a rows then use outer apply
If you need to find only one specific row for each of row from a, try:
cross apply
( select top 1 b.y, b.z
from b
where b.v = a.v
order by b.order
) bb
You could also use stringstream.
Something easy that would work on all select2 instances on the page.
$(document).on('focus', '.select2', function() {
$(this).siblings('select').select2('open');
});
UPDATE: The above code doesn't seem to work properly on IE11/Select2 4.0.3
PS: also added filter to select only single
select fields. Select with multiple
attribute doesn't need it and would probably break if applied.
var select2_open;
// open select2 dropdown on focus
$(document).on('focus', '.select2-selection--single', function(e) {
select2_open = $(this).parent().parent().siblings('select');
select2_open.select2('open');
});
// fix for ie11
if (/rv:11.0/i.test(navigator.userAgent)) {
$(document).on('blur', '.select2-search__field', function (e) {
select2_open.select2('close');
});
}
Using session
, I successfully passed a parameter (name
) from servlet #1 to servlet #2, using response.sendRedirect
in servlet #1. Servlet #1 code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
String name = request.getParameter("name");
String password = request.getParameter("password");
...
request.getSession().setAttribute("name", name);
response.sendRedirect("/todo.do");
In Servlet #2, you don't need to get name
back. It's already connected to the session. You could do String name = (String) request.getSession().getAttribute("name");
---but you don't need this.
If Servlet #2 calls a JSP, you can show name
this way on the JSP webpage:
<h1>Welcome ${name}</h1>
I figured out this try this it worked for me.
In visual studio 2017 community edition it creates a project at this path "C:\Users\mark\source\repos\mipmaps\mipmaps" This will create a access to file is denied issue
Now, you can fix that this way.
close your visual studio process. Then, find your project and copy the project folder But, first make a Sub-folder Named Projects inside of your visual studio 2017 folder in documents. Next, paste the project folder inside of your visual studio 2017 Project folder not the main visual studio 2017 folder it should go into the Sub-folder called Projects. Next, restart Visual studio 2017 Then, choose Open project Solution Then, find your project you pasted in your visual studio 2017 Projects folder Then clean the Project and rebuild it , It, should build and compile just fine. Hope, this Helped out anybody else. Not to sure why Microsoft thought building your projects in a path where it needs write permissions is beyond me.
You need to pass the whole point to location
var point = new Point(50, 100);
this.balancePanel.Location = point;
If you don't need to support IE8 then you can use the native Javascript Array.prototype.reduce()
method. You will need to convert your JQuery object into an array first:
var sum = $('.price').toArray().reduce(function(sum,element) {
if(isNaN(sum)) sum = 0;
return sum + Number(element.value);
}, 0);
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
This worked for me: conda install --force-reinstall pyqt qt
Based on this
Find last time of update on a table
SELECT
tbl.name
,ius.last_user_update
,ius.user_updates
,ius.last_user_seek
,ius.last_user_scan
,ius.last_user_lookup
,ius.user_seeks
,ius.user_scans
,ius.user_lookups
FROM
sys.dm_db_index_usage_stats ius INNER JOIN
sys.tables tbl ON (tbl.OBJECT_ID = ius.OBJECT_ID)
WHERE ius.database_id = DB_ID()
http://www.sqlserver-dba.com/2012/10/sql-server-find-last-time-of-update-on-a-table.html
Setting the User-Agent from everyone's favorite Dive Into Python.
The short story: You can use Request.add_header to do this.
You can also pass the headers as a dictionary when creating the Request itself, as the docs note:
headers should be a dictionary, and will be treated as if
add_header()
was called with each key and value as arguments. This is often used to “spoof” theUser-Agent
header, which is used by a browser to identify itself – some HTTP servers only allow requests coming from common browsers as opposed to scripts. For example, Mozilla Firefox may identify itself as"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11"
, whileurllib2
‘s default user agent string is"Python-urllib/2.6"
(on Python 2.6).
From MSDN, Math.Round(double a) returns:
The integer nearest a. If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned.
... and so 2.5, being halfway between 2 and 3, is rounded down to the even number (2). this is called Banker's Rounding (or round-to-even), and is a commonly-used rounding standard.
Same MSDN article:
The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.
You can specify a different rounding behavior by calling the overloads of Math.Round that take a MidpointRounding
mode.
Starting in Python 3.9
, you can use removeprefix
and removesuffix
:
'"" " " ""\\1" " "" ""'.removeprefix('"').removesuffix('"')
# '" " " ""\\1" " "" "'
Here's a Perl script which will edit the files in-place:
perl -i.bak -lpe 's/\s+/,/g' files*
Consecutive whitespace is converted to a single comma.
Each input file is moved to .bak
These command-line options are used:
-i.bak
edit in-place and make .bak copies
-p
loop around every line of the input file, automatically print the line
-l
removes newlines before processing, and adds them back in afterwards
-e
execute the perl code
For me, I used margin-left: auto; which is more responsive with horizontal resizing.
Use button
tag instead of input
and use pull-right
class.
pull-right
class totally messes up both of your buttons, but you can fix this by defining custom margin on the right side.
<button class="btn btn-primary pull-right btn-sm RbtnMargin" type="button">Save</button>
<button class="btn btn-primary pull-right btn-sm" type="button">Cancel</button>
Then use the following CSS for the class
.RbtnMargin { margin-left: 5px; }
You have a typo.
Change: headers.append('authentication', ${student.token});
To: headers.append('Authentication', student.token);
NOTE the Authentication is capitalized
Because textContent
is not supported in IE8 and older, here is a workaround:
var node = document.getElementById('test'),
var text = node.textContent || node.innerText;
alert(text);
innerText
does work in IE.
Try setting a Windows System Environment variable called _JAVA_OPTIONS
with the heap size you want. Java should be able to find it and act accordingly.
When you do a cmp a,b
, the flags are set as if you had calculated a - b
.
Then the jmp
-type instructions check those flags to see if the jump should be made.
In other words, the first block of code you have (with my comments added):
cmp al,dl ; set flags based on the comparison
jg label1 ; then jump based on the flags
would jump to label1
if and only if al
was greater than dl
.
You're probably better off thinking of it as al > dl
but the two choices you have there are mathematically equivalent:
al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0 (cancel the terms on the right hand side)
You need to be careful when using jg
inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.
See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JO | Jump if overflow | | OF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNO | Jump if not overflow | | OF = 0 |
+--------+------------------------------+-------------+--------------------+
| JS | Jump if sign | | SF = 1 |
+--------+------------------------------+-------------+--------------------+
| JNS | Jump if not sign | | SF = 0 |
+--------+------------------------------+-------------+--------------------+
| JE/ | Jump if equal | | ZF = 1 |
| JZ | Jump if zero | | |
+--------+------------------------------+-------------+--------------------+
| JNE/ | Jump if not equal | | ZF = 0 |
| JNZ | Jump if not zero | | |
+--------+------------------------------+-------------+--------------------+
| JP/ | Jump if parity | | PF = 1 |
| JPE | Jump if parity even | | |
+--------+------------------------------+-------------+--------------------+
| JNP/ | Jump if no parity | | PF = 0 |
| JPO | Jump if parity odd | | |
+--------+------------------------------+-------------+--------------------+
| JCXZ/ | Jump if CX is zero | | CX = 0 |
| JECXZ | Jump if ECX is zero | | ECX = 0 |
+--------+------------------------------+-------------+--------------------+
Then the unsigned ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JB/ | Jump if below | unsigned | CF = 1 |
| JNAE/ | Jump if not above or equal | | |
| JC | Jump if carry | | |
+--------+------------------------------+-------------+--------------------+
| JNB/ | Jump if not below | unsigned | CF = 0 |
| JAE/ | Jump if above or equal | | |
| JNC | Jump if not carry | | |
+--------+------------------------------+-------------+--------------------+
| JBE/ | Jump if below or equal | unsigned | CF = 1 or ZF = 1 |
| JNA | Jump if not above | | |
+--------+------------------------------+-------------+--------------------+
| JA/ | Jump if above | unsigned | CF = 0 and ZF = 0 |
| JNBE | Jump if not below or equal | | |
+--------+------------------------------+-------------+--------------------+
And, finally, the signed ones:
+--------+------------------------------+-------------+--------------------+
|Instr | Description | signed-ness | Flags |
+--------+------------------------------+-------------+--------------------+
| JL/ | Jump if less | signed | SF <> OF |
| JNGE | Jump if not greater or equal | | |
+--------+------------------------------+-------------+--------------------+
| JGE/ | Jump if greater or equal | signed | SF = OF |
| JNL | Jump if not less | | |
+--------+------------------------------+-------------+--------------------+
| JLE/ | Jump if less or equal | signed | ZF = 1 or SF <> OF |
| JNG | Jump if not greater | | |
+--------+------------------------------+-------------+--------------------+
| JG/ | Jump if greater | signed | ZF = 0 and SF = OF |
| JNLE | Jump if not less or equal | | |
+--------+------------------------------+-------------+--------------------+
Here are 2 from infochimps.com:
http://www.infochimps.com/datasets/wikipedia-articles-abstract-search
http://www.infochimps.com/datasets/wikipedia-articles-title-autocomplete
you can use the InvariantCulture
string priceSameInAllCultures = price.ToString(System.Globalization.CultureInfo.InvariantCulture);
another possibility would be to do something like that:
private int GetDecimals(decimal d, int i = 0)
{
decimal multiplied = (decimal)((double)d * Math.Pow(10, i));
if (Math.Round(multiplied) == multiplied)
return i;
return GetDecimals(d, i+1);
}
In our codebase; we typically declare enums in the class that they belong to.
So for your Fruit example, We would have a Fruit class, and inside that an Enum called Fruits.
Referencing it in the code looks like this: Fruit.Fruits.Apple, Fruit.Fruits.Pear
, etc.
Constants follow along the same line, where they either get defined in the class to which they're relevant (so something like Fruit.ORANGE_BUSHEL_SIZE
); or if they apply system-wide (i.e. an equivalent "null value" for ints) in a class named "ConstantManager" (or equivalent; like ConstantManager.NULL_INT
). (side note; all our constants are in upper case)
As always, your coding standards probably differ from mine; so YMMV.
Just do this
<button OnClick=" location.href='link.html' ">Visit Page Now</button>
Although, it's been a while since I've touched JavaScript - maybe location.href
is outdated? Anyways, that's how I would do it.
First, you should make sure that document.getElementsByName("username")[0] actually returns an object and not "undefined". You can simply check like
if (typeof document.getElementsByName("username")[0] != 'undefined')
Similarly for the other element password.
It's the other way round:
Vehicle[] car = new Vehicle[N];
This makes more sense, as the number of elements in the array isn't part of the type of car
, but it is part of the initialization of the array whose reference you're initially assigning to car
. You can then reassign it in another statement:
car = new Vehicle[10]; // Creates a new array
(Note that I've changed the type name to match Java naming conventions.)
For further information about arrays, see section 10 of the Java Language Specification.
You can define the label for each activity in your manifest file.
A normal definition of a activity looks like this:
<activity
android:name=".ui.myactivity"
android:label="@string/Title Text" />
Where title text should be replaced by the id of a string resource for this activity.
You can also set the title text from code if you want to set it dynamically.
setTitle(address.getCity());
with this line the title is set to the city of a specific adress in the oncreate method of my activity.
begin
dbms_output.put_line( 'hello' ||chr(13) || chr(10) || 'world' );
end;
It is also possible to int array to direct assign value.
like this
int[] numbers = sNumbers.Split(',').Select(Int32.Parse).ToArray();
Which SDKs? If you mean the SDK for Cocoa development, you can check in /Developer/SDKs/
to see which ones you have installed.
If you're looking for the Java SDK version, then open up /Applications/Utilities/Java Preferences
. The versions of Java that you have installed are listed there.
On Mac OS X 10.6, though, the only Java version is 1.6.
Be careful that this will create an "alternate reality" for people who have already fetch/pulled/cloned from the remote repository. But in fact, it's quite simple:
git reset HEAD^ # remove commit locally
git push origin +HEAD # force-push the new HEAD commit
If you want to still have it in your local repository and only remove it from the remote, then you can use:
git push origin +HEAD^:<name of your branch, most likely 'master'>
I think you might be better off using PHP's inbuilt filters - in this particular case:
It can return a true or false when supplied with the FILTER_VALIDATE_EMAIL
param.
These are the preferred methods:
var item = Items.SingleOrDefault(x => x.Id == 123);
Or
var item = Items.Single(x => x.Id == 123);
assuming you want to remove every object except df from environment:
rm(list = ls(pattern="[^df]"))
Differentiate between the two cases you named:
To indicate that the requested operation is not supported and most likely never will, throw an UnsupportedOperationException
.
To indicate the requested operation has not been implemented yet, choose between this:
Use the NotImplementedException
from apache commons-lang which was available in commons-lang2 and has been re-added to commons-lang3 in version 3.2.
Implement your own NotImplementedException
.
Throw an UnsupportedOperationException
with a message like "Not implemented, yet".
Simply use fs
module and something like this:
fs.appendFile('server.log', 'string to append', function (err) {
if (err) return console.log(err);
console.log('Appended!');
});
Try this:
import time
while True:
print("Hi ", end="\r")
time.sleep(1)
print("Bob", end="\r")
time.sleep(1)
It worked for me. The end="\r"
part is making it overwrite the previous line.
WARNING!
If you print out hi
, then print out hello
using \r
, you’ll get hillo
because the output wrote over the previous two letters. If you print out hi
with spaces (which don’t show up here), then it will output hi
. To fix this, print out spaces using \r
.
Try this
$('#testID').addClass('nameOfClass');
or
$('#testID').removeClass('nameOfClass');