Split on your separator at most once, and take the first piece:
sep = '...'
stripped = text.split(sep, 1)[0]
You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.
You have to make sure that "Dependency Management" is enabled. To do so, right click on the project name, go to the "Gradle" sub-menu and click on "Enable Dependency Management". Once you do that, Gradle should load all the dependencies for you.
Use MultiDataTrigger type
<Style TargetType="ListBoxItem">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=State}" Value="WA">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Path=Name}" Value="Portland" />
<Condition Binding="{Binding Path=State}" Value="OR" />
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Cyan" />
</MultiDataTrigger>
</Style.Triggers>
</Style>
I found my actual problem and it was not mentioned in any answer: some of my unit-tests were causing logging initialization code to be run multiple times within the same test suite, messing up the logging on the later tests.
You can try implicit wait:
WebDriver driver = new FirefoxDriver();
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
driver.Url = "http://somedomain/url_that_delays_loading";
IWebElement myDynamicElement = driver.FindElement(By.Id("someDynamicElement"));
Or You can try explicit wait one:
IWebDriver driver = new FirefoxDriver();
driver.Url = "http://somedomain/url_that_delays_loading";
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
{
return d.FindElement(By.Id("someDynamicElement"));
});
Explicit will check if element is present before some action. Implicit wait could be call in every place in the code. For example after some AJAX actions.
More you can find at SeleniumHQ page
A dirty trick I somtimes use, is hiding variables in the 'name' attribute (that I normally don't use for other purposes):
select onFocus=(this.name=this.value) onChange=someFunction(this.name,this.value)><option...
Somewhat unexpectedly, both the old and the new value is then submitted to someFunction(oldValue,newValue)
See ARITHMETIC EVALUATION in man bash
:
Constants with a leading 0 are interpreted as octal numbers.
You can remove the leading zero by parameter expansion:
hour=${hour#0}
or force base-10 interpretation:
$((10#$hour + 1))
If you happen to work in a Unix environment, the expand command is what you need:
The .css()
function doesn't queue behind running animations, it's instantaneous.
To match the behaviour that you're after, you'd need to do the following:
$(document).ready(function() {
$("button").mouseover(function() {
var p = $("p#44.test").css("background-color", "yellow");
p.hide(1500).show(1500);
p.queue(function() {
p.css("background-color", "red");
});
});
});
The .queue()
function waits for running animations to run out and then fires whatever's in the supplied function.
Can you import the driver (org.hsqldb.jdbcDriver) into one of your source files? (To test that the class is actually on your class path).
If you can't import it then you could try including hsqldb.jar in your build path.
Using Commons Collections:
EqualPredicate nameEqlPredicate = new EqualPredicate(3);
BeanPredicate beanPredicate = new BeanPredicate("age", nameEqlPredicate);
return CollectionUtils.filter(cats, beanPredicate);
a=input("Enter number:")
def isprime():
total=0
factors=(1,a)# The only factors of a number
pfactors=range(1,a+1) #considering all possible factors
if a==1 or a==0:# One and Zero are not prime numbers
print "%d is NOT prime"%a
elif a==2: # Two is the only even prime number
print "%d is prime"%a
elif a%2==0:#Any even number is not prime except two
print "%d is NOT prime"%a
else:#a number is prime if its multiples are 1 and itself
#The sum of the number that return zero moduli should be equal to the "only" factors
for number in pfactors:
if (a%number)==0:
total+=number
if total!=sum(factors):
print "%d is NOT prime"%a
else:
print "%d is prime"%a
isprime()
try it
n.pause();
n.currentTime = 0;
var nopromise = {
catch : new Function()
};
(n.play() || nopromise).catch(function(){}); ;
In Storyboard, select your ViewController and go to Atribute Inspector. At the very top, under Simulated Metrics you have Size and Orientation properties which are set to Inferred. Change them to desired values.
In order for an application to display properly on another screen size, you also have to setup constraints, as described by Can Poyrazoglu in the first post.
Faced same issues on MIUI phone resolved by making MIUI account and enable install by USB.
In Bootstrap +4.5 you can simply add bellow style to your code:
<style>
.custom-file-input ~ .custom-file-label::after {
content: "Your custom text ...";
}
</style>
and your input:
<div class="custom-file">
<input type="file" class="custom-file-input">
<label class="custom-file-label">Your custom placeholder ...</label>
</div>
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
Parse to your string to a decimal first.
I like to keep objects as objects and not do any crazy type-shifting. Here's my way
var post_vars = $('#my-form').serializeArray();
$.ajax({
url: '//site.com/script.php',
method: 'POST',
data: post_vars,
complete: function() {
$.ajax({
url: '//site.com/script2.php',
method: 'POST',
data: post_vars.concat({
name: 'EXTRA_VAR',
value: 'WOW THIS WORKS!'
})
});
}
});
if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!
Hope this helps.
It also has something to do with the version of JDK. If it does well in JDK6, maybe it will have the problem in JDK 7 described by you, because the implementation method in jdk 7 has been changed.
Look at this:
Description: The sorting algorithm used by java.util.Arrays.sort
and (indirectly) by java.util.Collections.sort
has been replaced. The new sort implementation may throw an IllegalArgumentException
if it detects a Comparable
that violates the Comparable
contract. The previous implementation silently ignored such a situation. If the previous behavior is desired, you can use the new system property, java.util.Arrays.useLegacyMergeSort
, to restore previous mergesort behaviour.
I don't know the exact reason. However, if you add the code before you use sort. It will be OK.
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
When using git rm, the removal will part of your next commit. So if you want to push the change you should use git rm
For json to xml use the following Jackson example:
final String str = "{\"name\":\"JSON\",\"integer\":1,\"double\":2.0,\"boolean\":true,\"nested\":{\"id\":42},\"array\":[1,2,3]}";
ObjectMapper jsonMapper = new ObjectMapper();
JsonNode node = jsonMapper.readValue(str, JsonNode.class);
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_1_1, true);
StringWriter w = new StringWriter();
xmlMapper.writeValue(w, node);
System.out.println(w.toString());
Prints:
<?xml version='1.1' encoding='UTF-8'?>
<ObjectNode>
<name>JSON</name>
<integer>1</integer>
<double>2.0</double>
<boolean>true</boolean>
<nested>
<id>42</id>
</nested>
<array>1</array>
<array>2</array>
<array>3</array>
</ObjectNode>
To convert it back (xml to json) take a look at this answer https://stackoverflow.com/a/62468955/1485527 .
With attribute selector we target input type text in CSS
input[type=text] {
background:gold;
font-size:15px;
}
i get /usr/local - no such file or directory. Though nvcc -V gives
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2016 NVIDIA Corporation
Built on Sun_Sep__4_22:14:01_CDT_2016
Cuda compilation tools, release 8.0, V8.0.44
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
when i write import StringIO it says there is no such module.
From What’s New In Python 3.0:
The
StringIO
andcStringIO
modules are gone. Instead, import theio
module and useio.StringIO
orio.BytesIO
for text and data respectively.
.
A possibly useful method of fixing some Python 2 code to also work in Python 3 (caveat emptor):
try:
from StringIO import StringIO ## for Python 2
except ImportError:
from io import StringIO ## for Python 3
Note: This example may be tangential to the main issue of the question and is included only as something to consider when generically addressing the missing
StringIO
module. For a more direct solution the messageTypeError: Can't convert 'bytes' object to str implicitly
, see this answer.
Locale.current.languageCode
returns me wrong code, so I use these extensions:
extension Locale {
static var preferredLanguageCode: String {
let defaultLanguage = "en"
let preferredLanguage = preferredLanguages.first ?? defaultLanguage
return Locale(identifier: preferredLanguage).languageCode ?? defaultLanguage
}
static var preferredLanguageCodes: [String] {
return Locale.preferredLanguages.compactMap({Locale(identifier: $0).languageCode})
}
}
if (true)
{
return View();
}
else
{
return View("another view name");
}
Method 1:\
add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables
Method 2: (if method 1 not work then)
simple open command prompt with "run as administrator"
Use this as your WHERE condition
WHERE CHARINDEX('Apples', column) = 0
Had the same issue on Ubuntu 14.10 with java-8-oracle installed.
Solved installing ca-certificates-java package:
sudo apt-get install ca-certificates-java
oh boy, this got resolved, I just had to name my Installed JRE appropriately. I had only the jdk installed and eclipse had taken the default jdk name, i renamed it to JavaSE-1.6 and voila it worked, though i had to redo everthing from the scratch.
First of all, a spinner does not support item click events. Calling this method will raise an exception.
You can use setOnItemSelectedListener:
Spinner s1;
s1 = (Spinner)findViewById(R.id.s1);
int selectionCurrent = s1.getSelectedItemPosition();
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
if (selectionCurrent != position){
// Your code here
}
selectionCurrent= position;
}
}
@Override
public void onNothingSelected(AdapterView<?> parentView) {
// Your code here
}
});
According to AWS documentation [https://aws.amazon.com/premiumsupport/knowledge-center/instance-store-vs-ebs/] instance store volumes is not persistent through instance stops, terminations, or hardware failures. Any AMI created from instance stored disk doesn't contain data present in instance store so all instances launched by this AMI will not have data stored in instance store. Instance store can be used as cache for applications running on instance, for all persistent data you should use EBS.
I found the Glide as better option than Picasso
.
I was using picasso to load around 32
images of size around 200-500KB
each and I was always getting OOM
. But the Glide
solved my all OOM
issues.
As per doc http://dev.mysql.com/doc/refman/5.0/en/server-status-variables.html#statvar_Connections
Connections
The number of connection attempts (successful or not) to the MySQL server.
You can try this,
ALTER TABLE table_name ADD column_name INT DEFAULT 0;
I didn't know about iterators, however here's what I was doing until today to remove elements from a list inside a loop:
List<String> names = ....
for (i=names.size()-1;i>=0;i--) {
// Do something
names.remove(i);
}
This is always working, and could be used in other languages or structs not supporting iterators.
Assuming you have some level of control over the protocol, I'm a big fan of sending heartbeats to verify that a connection is active. It's proven to be the most fail proof method and will often give you the quickest notification when a connection has been broken.
TCP keepalives will work, but what if the remote host is suddenly powered off? TCP can take a long time to timeout. On the other hand, if you have logic in your app that expects a heartbeat reply every x seconds, the first time you don't get them you know the connection no longer works, either by a network or a server issue on the remote side.
See Do I need to heartbeat to keep a TCP connection open? for more discussion.
you should try this
g++-4.4 -std=c++0x or g++-4.7 -std=c++0x
Mine was more of a mistake, what happened was loop click(i guess) basically by clicking on the login the parent was also clicked which ended up causing Maximum call stack size exceeded.
$('.clickhere').click(function(){
$('.login').click();
});
<li class="clickhere">
<a href="#" class="login">login</a>
</li>
The following command helped me (executing on bash before running mvn)
export MAVEN_OPTS=-Dhttps.protocols=TLSv1,TLSv1.1,TLSv1.2
Basically, tree conflicts arise if there is some restructure in the folder structure on the branch.
You need to delete the conflict folder and use svn clean
once.
Hope this solves your conflict.
It means that there is no initial context :)
But seriously folks, JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext). NoInitialContextException means "I want to find the telephone number for John Smith, but I have no phonebook to look in".
An InitialContext can be created in any number of ways. It can be done manually, for instance creating a connection to an LDAP server. It can also be set up by an application server inside which you run your application. In this case, the container (application server) already provides you with a "phonebook", through which you can look up anything the application server makes available. This is often configurable and a common way of moving this type of configuration from the application implementation to the container, where it can be shared across all applications in the server.
UPDATE: from the code snippet you post it looks like you are trying to run code stand-alone that is meant to be run in an application server. In this case, the code attempting to get a connection to a database from the "phonebook". This is one of the resources that is often configured in the application server container. So, rather than having to manage configuration and connections to the database in your code, you can configure it in your application server and simple ask for a connection (using JNDI) in your code.
From wikipedia:
Turing completeness, named after Alan Turing, is significant in that every plausible design for a computing device so far advanced can be emulated by a universal Turing machine — an observation that has become known as the Church-Turing thesis. Thus, a machine that can act as a universal Turing machine can, in principle, perform any calculation that any other programmable computer is capable of. However, this has nothing to do with the effort required to write a program for the machine, the time it may take for the machine to perform the calculation, or any abilities the machine may possess that are unrelated to computation.
While truly Turing-complete machines are very likely physically impossible, as they require unlimited storage, Turing completeness is often loosely attributed to physical machines or programming languages that would be universal if they had unlimited storage. All modern computers are Turing-complete in this sense.
I don't know how you can be more non-technical than that except by saying "turing complete means 'able to answer computable problem given enough time and space'".
import static java.util.Comparator.naturalOrder;
...
list.stream()
.map(User::getDate)
.max(naturalOrder())
.orElse(null) // replace with .orElseThrow() is the list cannot be empty
Implementation with Guzzle library:
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
$httpClient = new Client();
$response = $httpClient->post(
'https://postman-echo.com/post',
[
RequestOptions::BODY => 'POST raw request content',
RequestOptions::HEADERS => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
]
);
echo(
$response->getBody()->getContents()
);
PHP CURL extension:
$curlHandler = curl_init();
curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://postman-echo.com/post',
CURLOPT_RETURNTRANSFER => true,
/**
* Specify POST method
*/
CURLOPT_POST => true,
/**
* Specify request content
*/
CURLOPT_POSTFIELDS => 'POST raw request content',
]);
$response = curl_exec($curlHandler);
curl_close($curlHandler);
echo($response);
You can change the size of the plot by adding this before you create the figure.
plt.rcParams["figure.figsize"] = [16,9]
This little example shows how the $rootScope
emit a event that will be listen by a children scope in another controller.
(function(){
angular
.module('ExampleApp',[]);
angular
.module('ExampleApp')
.controller('ExampleController1', Controller1);
Controller1.$inject = ['$rootScope'];
function Controller1($rootScope) {
var vm = this,
message = 'Hi my children scope boy';
vm.sayHi = sayHi;
function sayHi(){
$rootScope.$broadcast('greeting', message);
}
}
angular
.module('ExampleApp')
.controller('ExampleController2', Controller2);
Controller2.$inject = ['$scope'];
function Controller2($scope) {
var vm = this;
$scope.$on('greeting', listenGreeting)
function listenGreeting($event, message){
alert(['Message received',message].join(' : '));
}
}
})();
http://codepen.io/gpincheiraa/pen/xOZwqa
The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope
and $rootScope
.
You can actually sort it:
sorted(l,reverse=True)
l = [1, 2, 3]
sort=sorted(l,reverse=True)
print(sort)
You get:
[3,2,1]
But still if want to get the max do:
print(sort[0])
You get:
3
if second max:
print(sort[1])
and so on...
In my experience, most often this error message means that you have put an accidental closing brace somewhere, leaving the rest of your statements outside the function.
Example:
function a() {
if (global_block) //syntax error is actually here - missing opening brace
return;
} //this unintentionally ends the function
if (global_somethingelse) {
//Chrome will show the error occurring here,
//but actually the error is in the previous statement
return;
}
//do something
}
You can use @@ for this purpose.
Like var email = firstName + '\@@' + domain;
Also try this for C-indenting indentation. Do :help =
for more information:
={
That will auto-indent the current code block you're in.
Or just:
==
to auto-indent the current line.
Not only heap memory. also increase perm size to resolve that exception in maven use these variables in environment variable.
variable name: MAVEN_OPTS
variable value: -Xmx512m -XX:MaxPermSize=256m
Example :
export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=500m"
var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];
$.each(arrofobject, function(index, val) {
console.log(val.category);
});
Peter Steinberger just tweeted about the private notification UIWindowFirstResponderDidChangeNotification
, which you can observe if you want to watch the firstResponder change.
The easiest way would be to set the value of the form element. If you're using jQuery (which I would highly recommend) you can do this easily with
$('#element-id').val('')
For all input elements in the form this may work (i've never tried it)
$('#form-id').children('input').val('')
Note that .children will only find input elements one level down. If you need to find grandchildren or such .find() should work.
There may be a better way however this should work for you.
As mentioned in a previous reply, this generally comes when compiling copy pasted code. If you have a bash shell, the following command generally works:
iconv -f utf-8 -t ascii//translit input.c > output.c
You might find it better to use a 3rd party program to enter the queries into Access such as WinSQL I think from memory WinSQL supports multiple queries via it's batch feature.
I ultimately found it easier to just write a program in perl to do bulk INSERTS into an Access via ODBC. You could use vbscript or any language that supports ODBC though.
You can then do anything you like and have your own complicated logic to handle the importing.
use Illuminate\Database\Eloquent\Builder;
$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
$query = $query->where('orders.customer_id', 'NULL')
});
$query = $query->get();
How to break out in java??
Ans: Best way: System.exit(0);
Java language provides three jump statemnts that allow you to interrupt the normal flow of program.
These include break , continue ,return ,labelled break statement for e.g
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
outerLoop://Label
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++)
{
for(int k=1;k<=j;k++)
{
System.out.print(k+"\t");
break outerLoop;
}
System.out.println();
}
System.out.println();
}
}
}
Output: 1
Now Note below Program:
import java.util.Scanner;
class demo
{
public static void main(String args[])
{
for(int i=1;i<=10;i++)
{
for(int j=1;j<=i;j++)
{
for(int k=1;k<=j;k++)
{
System.out.print(k+"\t");
break ;
}
}
System.out.println();
}
}
}
output:
1
11
111
1111
and so on upto
1111111111
Similarly you can use continue statement just replace break with continue in above example.
Things to Remember :
A case label cannot contain a runtime expressions involving variable or method calls
outerLoop:
Scanner s1=new Scanner(System.in);
int ans=s1.nextInt();
// Error s1 cannot be resolved
Reading your requirements the simplest way would be to display a mode-less form and use a standard System.Windows.Forms timer to update the progress on the mode-less form. No threads, no possible memory leaks.
As this only uses the one UI thread, you would also need to call Application.DoEvents() at certain points during your main processing to guarantee the progress bar is updated visually.
You can use CSS:
p.capitalize {text-transform:capitalize;}
Based on Kamal Reddy's comment:
document.getElementById("myP").style.textTransform = "capitalize";
It's not clear what you want, or whether you want this trick to work with different targets, or whether you've defined these targets elsewhere, or what version of Make you're using, but what the heck, I'll go out on a limb:
ifeq (yes, ${TEST})
CXXFLAGS := ${CXXFLAGS} -DDESKTOP_TEST
test:
$(info ************ TEST VERSION ************)
else
release:
$(info ************ RELEASE VERSIOIN **********)
endif
Now with react-router v5 you can use the useHistory hook like this:
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
read more at: https://reacttraining.com/react-router/web/api/Hooks/usehistory
You can do it in CSS, but there isn't much support in browsers other than modern versions of Chrome, Safari and Opera at the moment. Firefox currently only supports SVG masks. See the Caniuse results for more information.
CSS:
p {
color: red;
-webkit-mask-image: -webkit-gradient(linear, left top, left bottom,
from(rgba(0,0,0,1)), to(rgba(0,0,0,0)));
}
The trick is to specify a mask that is itself a gradient that ends as invisible (thru alpha value)
See a demo with a solid background, but you can change this to whatever you want.
Notice also that all the usual image properties are available for mask-image
p {_x000D_
color: red;_x000D_
font-size: 30px;_x000D_
-webkit-mask-image: linear-gradient(to left, rgba(0,0,0,1), rgba(0,0,0,0)), linear-gradient(to right, rgba(0,0,0,1), rgba(0,0,0,0));_x000D_
-webkit-mask-size: 100% 50%;_x000D_
-webkit-mask-repeat: no-repeat;_x000D_
-webkit-mask-position: left top, left bottom;_x000D_
}_x000D_
_x000D_
div {_x000D_
background-color: lightblue;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
Now, another approach is available, that is supported by Chrome, Firefox, Safari and Opera.
The idea is to use
mix-blend-mode: hard-light;
that gives transparency if the color is gray. Then, a grey overlay on the element creates the transparency
div {_x000D_
background-color: lightblue;_x000D_
}_x000D_
_x000D_
p {_x000D_
color: red;_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
width: 200px;_x000D_
mix-blend-mode: hard-light;_x000D_
}_x000D_
_x000D_
p::after {_x000D_
position: absolute;_x000D_
content: "";_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
height: 100%;_x000D_
width: 100%;_x000D_
background: linear-gradient(transparent, gray);_x000D_
pointer-events: none;_x000D_
}
_x000D_
<div><p>text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text </p></div>
_x000D_
That's because itoa
isn't a standard function. Try snprintf
instead.
char str[LEN];
snprintf(str, LEN, "%d", 42);
In VB.NET, you need to use the GetType
method to retrieve the type of an instance of an object, and the GetType()
operator to retrieve the type of another known type.
Once you have the two types, you can simply compare them using the Is
operator.
So your code should actually be written like this:
Sub FillCategories(ByVal Obj As Object)
Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
cmd.CommandType = CommandType.StoredProcedure
Obj.DataSource = cmd.ExecuteReader
If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then
End If
Obj.DataBind()
End Sub
You can also use the TypeOf
operator instead of the GetType
method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:
If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then
End If
Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.
I faced the same issue. Setting relative path of the parent in module projects solved the issue.
Use <relativePath>../Parent Project Name/pom.xml</relativePath>
Update: Well, it's been several years since I posted this! For my specific purpose of comparing HEAD to upstream, I now use @{u}
, which is a shortcut that refers to the HEAD of the upstream tracking branch. (See https://git-scm.com/docs/gitrevisions#gitrevisions-emltbranchnamegtupstreamemegemmasterupstreamememuem ).
Original answer: I've run across this problem as well. I often use multiple remotes in a single repository, and it's easy to forget which one your current branch is tracking against. And sometimes it's handy to know that, such as when you want to look at your local commits via git log remotename/branchname..HEAD
.
All this stuff is stored in git config variables, but you don't have to parse the git config output. If you invoke git config followed by the name of a variable, it will just print the value of that variable, no parsing required. With that in mind, here are some commands to get info about your current branch's tracking setup:
LOCAL_BRANCH=`git name-rev --name-only HEAD`
TRACKING_BRANCH=`git config branch.$LOCAL_BRANCH.merge`
TRACKING_REMOTE=`git config branch.$LOCAL_BRANCH.remote`
REMOTE_URL=`git config remote.$TRACKING_REMOTE.url`
In my case, since I'm only interested in finding out the name of my current remote, I do this:
git config branch.`git name-rev --name-only HEAD`.remote
You could extend the String object with your own function that does what you need (useful if there's ever missing functionality):
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], replace[i]);
}
return replaceString;
};
For global replace you could use regex:
String.prototype.replaceArray = function(find, replace) {
var replaceString = this;
var regex;
for (var i = 0; i < find.length; i++) {
regex = new RegExp(find[i], "g");
replaceString = replaceString.replace(regex, replace[i]);
}
return replaceString;
};
To use the function it'd be similar to your PHP example:
var textarea = $(this).val();
var find = ["<", ">", "\n"];
var replace = ["<", ">", "<br/>"];
textarea = textarea.replaceArray(find, replace);
import urllib2
import time
max_attempts = 80
attempts = 0
sleeptime = 10 #in seconds, no reason to continuously try if network is down
#while true: #Possibly Dangerous
while attempts < max_attempts:
time.sleep(sleeptime)
try:
response = urllib2.urlopen("http://example.com", timeout = 5)
content = response.read()
f = open( "local/index.html", 'w' )
f.write( content )
f.close()
break
except urllib2.URLError as e:
attempts += 1
print type(e)
Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.
So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.
cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit
But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.
@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit
Or if you'd like them to select the file from which to write in the batch you could do the following.
@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit
It's new features since the version 3.3.0 http://www.rabbitmq.com/release-notes/README-3.3.0.txt
server
------
...
25603 prevent access using the default guest/guest credentials except via
localhost.
If you want enable the guest user read this or this RabbitMQ 3.3.1 can not login with guest/guest
# remove guest from loopback_users in rabbitmq.config like this
[{rabbit, [{loopback_users, []}]}].
# It is danger for default user and default password for remote access
# better to change password
rabbitmqctl change_password guest NEWPASSWORD
If you want create a new user with admin grants:
rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"
Now you can access using test test.
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
With Eloquent its very easy to retrieve relational data. Checkout the following example with your scenario in Laravel 5.
We have three models:
1) Article (belongs to user and category)
2) Category (has many articles)
3) User (has many articles)
1) Article.php
<?php
namespace App\Models;
use Eloquent;
class Article extends Eloquent{
protected $table = 'articles';
public function user()
{
return $this->belongsTo('App\Models\User');
}
public function category()
{
return $this->belongsTo('App\Models\Category');
}
}
2) Category.php
<?php
namespace App\Models;
use Eloquent;
class Category extends Eloquent
{
protected $table = "categories";
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
3) User.php
<?php
namespace App\Models;
use Eloquent;
class User extends Eloquent
{
protected $table = 'users';
public function articles()
{
return $this->hasMany('App\Models\Article');
}
}
You need to understand your database relation and setup in models. User has many articles. Category has many articles. Articles belong to user and category. Once you setup the relationships in Laravel, it becomes easy to retrieve the related information.
For example, if you want to retrieve an article by using the user and category, you would need to write:
$article = \App\Models\Article::with(['user','category'])->first();
and you can use this like so:
//retrieve user name
$article->user->user_name
//retrieve category name
$article->category->category_name
In another case, you might need to retrieve all the articles within a category, or retrieve all of a specific user`s articles. You can write it like this:
$categories = \App\Models\Category::with('articles')->get();
$users = \App\Models\Category::with('users')->get();
You can learn more at http://laravel.com/docs/5.0/eloquent
There are a couple of different ways to approach the problem:
Each approach has its own quirks. You will need to setup SSH keys to enable password-less logins if you are wrapping system commands like "ssh", "scp" or "rsync." You can embed a password in a script using Paramiko or some other library, but you might find the lack of documentation frustrating, especially if you are not familiar with the basics of the SSH connection (eg - key exchanges, agents, etc). It probably goes without saying that SSH keys are almost always a better idea than passwords for this sort of stuff.
NOTE: its hard to beat rsync if you plan on transferring files via SSH, especially if the alternative is plain old scp.
I've used Paramiko with an eye towards replacing system calls but found myself drawn back to the wrapped commands due to their ease of use and immediate familiarity. You might be different. I gave Conch the once-over some time ago but it didn't appeal to me.
If opting for the system-call path, Python offers an array of options such as os.system or the commands/subprocess modules. I'd go with the subprocess module if using version 2.4+.
I am using Spring Boot to try and load a webpage, not test, and had this problem. My solution was a bit different than those above considering the slightly different circumstances. (although those answers helpled me understand.)
I simply had to change my Spring Boot starter dependency in Maven from:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
to:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Just changing the 'web' to 'thymeleaf' fixed the problem for me.
> library(plyr)
> as.matrix(ldply(a))
V1 V2 V3 V4 V5 V6
[1,] 1 1 2 3 4 5
[2,] 2 1 2 3 4 5
[3,] 3 1 2 3 4 5
[4,] 4 1 2 3 4 5
[5,] 5 1 2 3 4 5
[6,] 6 1 2 3 4 5
[7,] 7 1 2 3 4 5
[8,] 8 1 2 3 4 5
[9,] 9 1 2 3 4 5
[10,] 10 1 2 3 4 5
for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0)
starts with [
character).
Hope this helps.
I found that the accepted answer and the similar ones to it had some flaws. Mainly that it's repeatedly adding that mouseleave listener to the element.
I've combined their solution with some custom code to achieve the functionality in question without memory leaks or listener bloat.
var getPopoverTimeout = function ($el) {
return $el.data('timeout');
}
$element.popover({
trigger: "manual",
html: true,
content: ...,
title: ...,
container: $element
}).on("mouseenter", function () {
var $this = $(this);
if (!$this.find('.popover').length) {
$this.popover("show");
} else if (getPopoverTimeout($element)) {
clearTimeout(getPopoverTimeout($element));
}
}).on("mouseleave", function () {
var $this = $(this);
$element.data('timeout', setTimeout(function () {
if (!$(".popover:hover").length) {
$this.popover("hide")
}
}, 250));
});
Which provides a nice 'hover-intent' like solution so that it doesn't flash in and out.
The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject
You have not added the necessary jar file which will be having org.json.JSONObject
class to your classpath
.
You can Download it From Here
Another handy aspect of @Valid not mentioned above is that (ie: using Postman to test an endpoint) @Valid will format the output of an incorrect REST call into formatted JSON instead of a blob of barely readable text. This is very useful if you are creating a commercially consumable API for your users.
We can easily achieve this using flex
. no need for background-image
.
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
#image-wrapper{_x000D_
width:500px;_x000D_
height:500px;_x000D_
border:1px solid #333;_x000D_
display:flex;_x000D_
justify-content:center;_x000D_
align-items:center;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div id="image-wrapper">_x000D_
<img id="myImage" src="http://blog.w3c.br/wp-content/uploads/2013/03/css31-213x300.png">_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
How about the following:
DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue ? _objHotelPackageOrder.UpdatedDate.value : DateTime.Now;
This is how I do it if I need a form displayed for each item, and inputs for various properties. Really depends on what I'm trying to do though.
ViewModel looks like this:
public class MyViewModel
{
public List<Person> Persons{get;set;}
}
View(with BeginForm of course):
@model MyViewModel
@for( int i = 0; i < Model.Persons.Count(); ++i)
{
@Html.HiddenFor(m => m.Persons[i].PersonId)
@Html.EditorFor(m => m.Persons[i].FirstName)
@Html.EditorFor(m => m.Persons[i].LastName)
}
Action:
[HttpPost]public ViewResult(MyViewModel vm)
{
...
Note that on post back only properties which had inputs available will have values. I.e., if Person had a .SSN property, it would not be available in the post action because it wasn't a field in the form.
Note that the way MVC's model binding works, it will only look for consecutive ID's. So doing something like this where you conditionally hide an item will cause it to not bind any data after the 5th item, because once it encounters a gap in the IDs, it will stop binding. Even if there were 10 people, you would only get the first 4 on the postback:
@for( int i = 0; i < Model.Persons.Count(); ++i)
{
if(i != 4)//conditionally hide 5th item,
{ //but BUG occurs on postback, all items after 5th will not be bound to the the list
@Html.HiddenFor(m => m.Persons[i].PersonId)
@Html.EditorFor(m => m.Persons[i].FirstName)
@Html.EditorFor(m => m.Persons[i].LastName)
}
}
Actually instanceof check where an object belongs to some hierarchy or not. ex: Car object belongs to Vehical class. So "new Car() instance of Vehical" returns true. And "new Car().getClass().equals(Vehical.class)" return false, though Car object belongs to Vehical class but it's categorized as a separate type.
You can try this:
.classname{_x000D_
width:250px;_x000D_
overflow:hidden;_x000D_
text-overflow:ellipsis;_x000D_
}
_x000D_
In mysql server 8.0, on Windows, the location is C:\ProgramData\MySQL\MySQL Server 8.0\Data
This is in no way specific to std::unique_ptr
, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.
If you had a function that accepts std::unique_ptr
as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar()
.
void bar(std::unique_ptr<int> p)
{
// ...
}
int main()
{
unique_ptr<int> p = foo();
bar(p); // error, can't implicitly invoke move constructor on lvalue
bar(std::move(p)); // OK but don't use p afterwards
return 0;
}
Consider using std::multimap
as suggested by @Ulrich Eckhardt. Just that the code could be made even simpler.
Given
std::vector<int> a = {5, 2, 1, 4, 3}; // a: 5 2 1 4 3
To sort in the mean time of insertion
std::multimap<int, std::size_t> mm;
for (std::size_t i = 0; i != a.size(); ++i)
mm.insert({a[i], i});
To retrieve values and original indices
std::vector<int> b;
std::vector<std::size_t> c;
for (const auto & kv : mm) {
b.push_back(kv.first); // b: 1 2 3 4 5
c.push_back(kv.second); // c: 2 1 4 3 0
}
The reason to prefer a std::multimap
to a std::map
is to allow equal values in original vectors. Also please note that, unlike for std::map
, operator[]
is not defined for std::multimap
.
import datetime
d1 = datetime.date(2008,8,15)
d2 = datetime.date(2008,9,15)
diff = d2 - d1
for i in range(diff.days + 1):
print (d1 + datetime.timedelta(i)).isoformat()
You can also check whether div has specific children or not,
if($('#myDiv').has('select').length>0)
{
// Do something here.
console.log("you can log here");
}
I think your second option is the best bet. Generally in floating-point comparison you often only care that one value is within a certain tolerance of another value, controlled by the selection of epsilon.
The jsonlite package is easy to use and tries to convert json into data frames.
Example:
library(jsonlite)
# url with some information about project in Andalussia
url <- 'http://www.juntadeandalucia.es/export/drupaljda/ayudas.json'
# read url and convert to data.frame
document <- fromJSON(txt=url)
Easiest and power full way
read only radio inputs using getAttribute
document.addEventListener('input',(e)=>{
if(e.target.getAttribute('name')=="myRadios")
console.log(e.target.value)
})
_x000D_
<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
_x000D_
In a query you can just do something like:
SELECT ColumnA * ColumnB FROM table
or
SELECT ColumnA - ColumnB FROM table
You can also create computed columns in your table where you can permanently use your formula.
Actually, the simplest thing (in GNU sed, at least) is to use a different separator for the sed substitution (s
) command. So, instead of s/pattern/'$mypath'/
being expanded to s/pattern//my/path/
, which will of course confuse the s
command, use s!pattern!'$mypath'!
, which will be expanded to s!pattern!/my/path!
. I’ve used the bang (!
) character (or use anything you like) which avoids the usual, but-by-no-means-your-only-choice forward slash as the separator.
The jQueryUI provides a extension to animate
function that allows you to animate css class.
edit: Example here
There are also methods to add/remove/toggle class which you might also be interested in.
Age (full years) of the Person:
SELECT
TRUNC(months_between(sysdate, per.DATE_OF_BIRTH) / 12) AS "Age"
FROM PD_PERSONS per
Not necessary to use \restylefloat
and destroys other options, like caption placement. just use [H]
or [!h]
after \begin{table}
.
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
255 is used because it's the largest number of characters that can be counted with an 8-bit number. It maximizes the use of the 8-bit count, without frivolously requiring another whole byte to count the characters above 255.
When used this way, VarChar only uses the number of bytes + 1 to store your text, so you might as well set it to 255, unless you want a hard limit (like 50) on the number of characters in the field.
I came across another performance comparison(latest update 10 April 2014). It compares the following:
Here is a quick summary from the post:
Conclusion
Ninject is definitely the slowest container.
MEF, LinFu and Spring.NET are faster than Ninject, but still pretty slow. AutoFac, Catel and Windsor come next, followed by StructureMap, Unity and LightCore. A disadvantage of Spring.NET is, that can only be configured with XML.
SimpleInjector, Hiro, Funq, Munq and Dynamo offer the best performance, they are extremely fast. Give them a try!
Especially Simple Injector seems to be a good choice. It's very fast, has a good documentation and also supports advanced scenarios like interception and generic decorators.
You can also try using the Common Service Selector Library and hopefully try multiple options and see what works best for you.
Some informtion about Common Service Selector Library from the site:
The library provides an abstraction over IoC containers and service locators. Using the library allows an application to indirectly access the capabilities without relying on hard references. The hope is that using this library, third-party applications and frameworks can begin to leverage IoC/Service Location without tying themselves down to a specific implementation.
13.09.2011: Funq and Munq were added to the list of contestants. The charts were also updated, and Spring.NET was removed due to it's poor performance.
04.11.2011: "added Simple Injector, the performance is the best of all contestants".
Make sure the variable is on the top part of the block, and in case you compile it with -ansi-pedantic
, make sure it looks like this:
function() {
int i;
i = 0;
someCode();
}
Featured graphics guidelines:
http://android-developers.blogspot.cz/2011/10/android-market-featured-image.html
List of graphics assets for your application:
http://support.google.com/googleplay/android-developer/bin/answer.py?hl=en&answer=1078870
You could also check our blog post summarizing all graphical assets for both Android and iOS:
http://www.skoumal.net/en/how-to-prepare-graphical-design-for-mobile-app/
In C#, the common mutex used is the Monitor. The type is 'System.Threading.Monitor'. It may also be used implicitly via the 'lock(Object)' statement. One example of its use is when constructing a Singleton class.
private static readonly Object instanceLock = new Object();
private static MySingleton instance;
public static MySingleton Instance
{
lock(instanceLock)
{
if(instance == null)
{
instance = new MySingleton();
}
return instance;
}
}
The lock statement using the private lock object creates a critical section. Requiring each thread to wait until the previous is finished. The first thread will enter the section and initialize the instance. The second thread will wait, get into the section, and get the initialized instance.
Any sort of synchronization of a static member may use the lock statement similarly.
I like the following:
print 'Downloading File FooFile.txt [%d%%]\r'%i,
Demo:
import time
for i in range(100):
time.sleep(0.1)
print 'Downloading File FooFile.txt [%d%%]\r'%i,
print('Downloading File FooFile.txt [%d%%]\r'%i, end="")
Demo:
import time
for i in range(100):
time.sleep(0.1)
print('Downloading File FooFile.txt [%d%%]\r'%i, end="")
# On PyCharm Debugger console, \r needs to come before the text.
# Otherwise, the text may not appear at all, or appear inconsistently.
# tested on PyCharm 2019.3, Python 3.6
import time
print('Start.')
for i in range(100):
time.sleep(0.02)
print('\rDownloading File FooFile.txt [%d%%]'%i, end="")
print('\nDone.')
To UrlEncode without using System.Web:
String s = System.Net.WebUtility.UrlEncode(str);
//fix some different between WebUtility.UrlEncode and HttpUtility.UrlEncode
s = Regex.Replace(s, "(%[0-9A-F]{2})", c => c.Value.ToLowerInvariant());
more details: https://www.samnoble.co.uk/2014/05/21/beware-webutility-urlencode-vs-httputility-urlencode/
There's a CodeProject article for an ID3 reader. And a thread at kixtart.org that has more information for other properties. Basically, you need to call the GetDetailsOf()
method on the folder shell object for shell32.dll
.
You're using Comparators
incorrectly.
Collections.sort(movieItems, new Comparator<Movie>(){
public int compare (Movie m1, Movie m2){
return m1.getDate().compareTo(m2.getDate());
}
});
A keystore contains private keys, and the certificates with their corresponding public keys.
A truststore contains certificates from other parties that you expect to communicate with, or from Certificate Authorities that you trust to identify other parties.
For people using *nix (Linux, OS X, etc.), there's no reason to do it via a second export command, you can chain it as part of the invoking command:
NODE_ENV=development node server.js
Easier, no? :)
It looks like you're comparing strings incorrectly. To compare a string to another, use the std::string::compare
function.
Example
while ((wrong < MAX_WRONG) && (soFar.compare(THE_WORD) != 0))
Try this:
ng-if="details.Payment[0].Status != '6'".
Sorry about that, but I think you can use ng-show or ng-hide.
I can think of at least 2 different ways:
using Task Manager (Ctrl-Shift-Esc), select the process tab, look for a process name cscript.exe or wscript.exe and use End Process.
From the command line you could use taskkill /fi "imagename eq cscript.exe" (change to wscript.exe as needed)
Another way is using scripting and WMI. Here are some hints: look for the Win32_Process class and the Terminate method.
Since Enum
Type implements IConvertible
interface, a better implementation should be something like this:
public T GetEnumFromString<T>(string value) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
//...
}
This will still permit passing of value types implementing IConvertible
. The chances are rare though.
Pictures are worth a thousand Unix commands and options:
I draw this to my students each semester and they seem to grasp vi afterwards.
vi is a finite state machine with only three states.
Upon starting, vi goes into COMMAND mode, where you can type short, few character commands, blindly. You know what you are doing; this isn't for amateurs.
When you want to actually edit text, you should go to INSERT mode with some one-character command:
Now, answering the question: exiting.
You can exit vi from EX mode:
w
and x
accept a file name parameter. If you started vi with a filename, you need not give it here again.
At last, the most important: how can you reach EX mode?
EX mode is for long commands that you can see typing at the bottom line of the screen. From COMMAND mode, you push colon, :
, and a colon will appear at the bottom line, where you can type the above commands.
From INSERT mode, you need to push ESC, i.e. the Escape button, going to COMMAND mode, and then : to go to EX mode.
If you are unsure, push ESC and that will bring you to command mode.
So, the robust method is ESC-:-x-Enter which saves your file and quits.
Try this
DataSet ds = new DataSet("TimeRanges");
using(SqlConnection conn = new SqlConnection("ConnectionString"))
{
SqlCommand sqlComm = new SqlCommand("Procedure1", conn);
sqlComm.Parameters.AddWithValue("@Start", StartTime);
sqlComm.Parameters.AddWithValue("@Finish", FinishTime);
sqlComm.Parameters.AddWithValue("@TimeRange", TimeRange);
sqlComm.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = sqlComm;
da.Fill(ds);
}
You should probably re-write the script to return a value rather than output it. Instead of:
a=$( script.sh ) # Now a is a string, either "success" or "Failed"
case "$a" in
success) echo script succeeded;;
Failed) echo script failed;;
esac
you would be able to do:
if script.sh > /dev/null; then
echo script succeeded
else
echo script failed
fi
It is much simpler for other programs to work with you script if they do not have to parse the output. This is a simple change to make. Just exit 0
instead of printing success
, and exit 1
instead of printing Failed
. Of course, you can also print those values as well as exiting with a reasonable return value, so that wrapper scripts have flexibility in how they work with the script.
function myFunction(e) {
var x = e.clientX - e.currentTarget.offsetLeft ;
var y = e.clientY - e.currentTarget.offsetTop ;
}
this works ok!
A simple solution is to assign color for each class. This way, we can control how each color is for each class. For example:
arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 3, 4, 4]
labl = [0, 1, 1, 0, 0]
color= ['red' if l == 0 else 'green' for l in labl]
plt.scatter(arr1, arr2, color=color)
Ameritrade also offers an API, as long as you have an Ameritrade account: http://www.tdameritrade.com/tradingtools/partnertools/api_dev.html
Swift 3 Above code updated:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
if UIDevice.current.orientation.isLandscape {
print("Landscape")
} else {
print("Portrait")
}
}
While the selected answer is strictly correct, I believe I understand what the OP is trying to get at here as I had a similar issue.
I had a TimeSpan which I wished to display in a grid control (as just hh:mm) but the grid didn't appear to understand TimeSpan, only DateTime . The OP has a similar scenario where only the TimeSpan is the relevant part but didn't consider the necessity of adding the DateTime reference point.
So, as indicated above, I simply added DateTime.MinValue (though any date will do) which is subsequently ignored by the grid when it renders the timespan as a time portion of the resulting date.
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
You could also do
function insertAfter(node1, node2) {
node1.outerHTML += node2.outerHTML;
}
or
function insertAfter2(node1, node2) {
var wrap = document.createElement("div");
wrap.appendChild(node2.cloneNode(true));
var node2Html = wrap.innerHTML;
node1.insertAdjacentHTML('afterend', node2Html);
}
in openresty there is a function ngx.req.start_time.
From the docs:
Returns a floating-point number representing the timestamp (including milliseconds as the decimal part) when the current request was created.
Select * from table where date > 'Today's date(mm/dd/yyyy)'
You can also add time in the single quotes(00:00:00AM)
For example:
Select * from Receipts where Sales_date > '08/28/2014 11:59:59PM'
Have you ever tried Genymotion? I've read about it last week and it is great. They have several Android Images that you run (with their own software). The images are INCREDIBLY fast and they have Google Play installed on them. Check it out if it is the kind of thing that you need.
I have found a very easy way to change the size i.e. the annotation @Size(min = 1, max = 50) which is part of "import javax.validation.constraints" i.e. "import javax.validation.constraints.Size;"
@Size(min = 1, max = 50)
private String country;
when executing this is hibernate you get in pgAdmin III
CREATE TABLE address
(
.....
country character varying(50),
.....
)
rm -rf *
Don't do it! It's dangerous! MAKE SURE YOU'RE IN THE RIGHT DIRECTORY!
Specifically for Windows users: If you have untracked files and clearing/removing the cached files is not working. Try opening PowerShell and converting the .gitignore file to UTF-8 encoding:
$Myfile = Get-Content .\.gitignore`
$Myfile | Out-File -Encoding "UTF8" .gitignore
You need to only do this once to encode the .gitignore file for that directory, and since the file is then encoded correctly, whenever you edit the file in the future it should work. I believe this is due to a glitch with GitHub not being about to read non UTF-8 encoding for a .gitignore file. As far as I'm aware this issue has not yet been resolved for Windows. It's not too big of a deal, just a pain to debug when it's not working.
The below is based on Todd Owen's answer. That solution has the problem that if the replacements contain characters that have special meaning in regular expressions, you can get unexpected results. I also wanted to be able to optionally do a case-insensitive search. Here is what I came up with:
/**
* Performs simultaneous search/replace of multiple strings. Case Sensitive!
*/
public String replaceMultiple(String target, Map<String, String> replacements) {
return replaceMultiple(target, replacements, true);
}
/**
* Performs simultaneous search/replace of multiple strings.
*
* @param target string to perform replacements on.
* @param replacements map where key represents value to search for, and value represents replacem
* @param caseSensitive whether or not the search is case-sensitive.
* @return replaced string
*/
public String replaceMultiple(String target, Map<String, String> replacements, boolean caseSensitive) {
if(target == null || "".equals(target) || replacements == null || replacements.size() == 0)
return target;
//if we are doing case-insensitive replacements, we need to make the map case-insensitive--make a new map with all-lower-case keys
if(!caseSensitive) {
Map<String, String> altReplacements = new HashMap<String, String>(replacements.size());
for(String key : replacements.keySet())
altReplacements.put(key.toLowerCase(), replacements.get(key));
replacements = altReplacements;
}
StringBuilder patternString = new StringBuilder();
if(!caseSensitive)
patternString.append("(?i)");
patternString.append('(');
boolean first = true;
for(String key : replacements.keySet()) {
if(first)
first = false;
else
patternString.append('|');
patternString.append(Pattern.quote(key));
}
patternString.append(')');
Pattern pattern = Pattern.compile(patternString.toString());
Matcher matcher = pattern.matcher(target);
StringBuffer res = new StringBuffer();
while(matcher.find()) {
String match = matcher.group(1);
if(!caseSensitive)
match = match.toLowerCase();
matcher.appendReplacement(res, replacements.get(match));
}
matcher.appendTail(res);
return res.toString();
}
Here are my unit test cases:
@Test
public void replaceMultipleTest() {
assertNull(ExtStringUtils.replaceMultiple(null, null));
assertNull(ExtStringUtils.replaceMultiple(null, Collections.<String, String>emptyMap()));
assertEquals("", ExtStringUtils.replaceMultiple("", null));
assertEquals("", ExtStringUtils.replaceMultiple("", Collections.<String, String>emptyMap()));
assertEquals("folks, we are not sane anymore. with me, i promise you, we will burn in flames", ExtStringUtils.replaceMultiple("folks, we are not winning anymore. with me, i promise you, we will win big league", makeMap("win big league", "burn in flames", "winning", "sane")));
assertEquals("bcaacbbcaacb", ExtStringUtils.replaceMultiple("abccbaabccba", makeMap("a", "b", "b", "c", "c", "a")));
assertEquals("bcaCBAbcCCBb", ExtStringUtils.replaceMultiple("abcCBAabCCBa", makeMap("a", "b", "b", "c", "c", "a")));
assertEquals("bcaacbbcaacb", ExtStringUtils.replaceMultiple("abcCBAabCCBa", makeMap("a", "b", "b", "c", "c", "a"), false));
assertEquals("c colon backslash temp backslash star dot star ", ExtStringUtils.replaceMultiple("c:\\temp\\*.*", makeMap(".", " dot ", ":", " colon ", "\\", " backslash ", "*", " star "), false));
}
private Map<String, String> makeMap(String ... vals) {
Map<String, String> map = new HashMap<String, String>(vals.length / 2);
for(int i = 1; i < vals.length; i+= 2)
map.put(vals[i-1], vals[i]);
return map;
}
Most of the methods explained here did not solved the problem for me.
Finally, I fixed the problem by applying the following steps:
1. Close Visual Studio.
2. Delete all the contents in the bin folders of each project.
3. Open solution and rebuild.
Hope this helps.
Maybe not actual, but simple solution:
interface Bar{
x:number;
y?:string;
}
var baz:Bar = JSON.parse(jsonString);
alert(baz.y);
work for difficult dependencies too!!!
The html code you written is absolutely perfect
<ul class="nav navbar-nav list-inline">
<li class="list-inline-item">FB</li>
<li class="list-inline-item">G+</li>
<li class="list-inline-item">T</li>
</ul>
The reasons that could be possible is
1. Check out the CSS for class name "nav" or "navbar-nav" may be over writing it, try to remove and debug the class names in the ul element.
2. Check any of the child element(a tag or "social-icon" class) is using block level CSS style
3. Check out your using a HTML5 !DOCTYPE html
4. Place your bootstrap.css link at the last before closing your head tag
5. Change text-xs-center to text-center because xs is dropped in Bootstrap 4.
This One will work perfectly fine
<!-- Use this inside Head tag-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js"></script>
<!-- Use this inside Body tag-->
<div class="container">
<ul class="list-inline">
<li class="list-inline-item"><a class="social-icon text-center" target="_blank" href="#">FB</a></li>
<li class="list-inline-item"><a class="social-icon text-center" target="_blank" href="#">G+</a></li>
<li class="list-inline-item"><a class="social-icon text-center" target="_blank" href="#">T</a></li>
</ul>
</div>
When you are storing a DataFrame
object into a csv file using the to_csv
method, you probably wont be needing to store the preceding indices of each row of the DataFrame
object.
You can avoid that by passing a False
boolean value to index
parameter.
Somewhat like:
df.to_csv(file_name, encoding='utf-8', index=False)
So if your DataFrame object is something like:
Color Number
0 red 22
1 blue 10
The csv file will store:
Color,Number
red,22
blue,10
instead of (the case when the default value True
was passed)
,Color,Number
0,red,22
1,blue,10
I can suggest using the rsample package:
# choosing 75% of the data to be the training data
data_split <- initial_split(data, prop = .75)
# extracting training data and test data as two seperate dataframes
data_train <- training(data_split)
data_test <- testing(data_split)
For IE: window.close();
and self.close();
should work fine.
If you want just open the IE browser and type
javascript:self.close()
and hit enter, it should ask you for a prompt.
Note: this method doesn't work for Chrome or Firefox.
The answer, in a few words
In your example, itsProblem
is a local variable.
Your must use self
to set and get instance variables. You can set it in the __init__
method. Then your code would be:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
But if you want a true class variable, then use the class name directly:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)
But be careful with this one, as theExample.itsProblem
is automatically set to be equal to Example.itsProblem
, but is not the same variable at all and can be changed independently.
Some explanations
In Python, variables can be created dynamically. Therefore, you can do the following:
class Example(object):
pass
Example.itsProblem = "problem"
e = Example()
e.itsSecondProblem = "problem"
print Example.itsProblem == e.itsSecondProblem
prints
True
Therefore, that's exactly what you do with the previous examples.
Indeed, in Python we use self
as this
, but it's a bit more than that. self
is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self
or not.
Which means you can do:
class Example(object):
def __init__(self):
self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
or:
class Example(object):
def __init__(my_super_self):
my_super_self.itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
It's exactly the same. The first argument of ANY object method is the current object, we only call it self
as a convention. And you add just a variable to this object, the same way you would do it from outside.
Now, about the class variables.
When you do:
class Example(object):
itsProblem = "problem"
theExample = Example()
print(theExample.itsProblem)
You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?
Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.
As a conclusion, never use class variables to set default values to object variables. Use __init__
for that.
Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.
You can use Bundle to do the same in Android
Create the intent:
Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“stuff”, getrec);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
Now in your second activity retrieve your data from the bundle:
//Get the bundle
Bundle bundle = getIntent().getExtras();
//Extract the data…
String stuff = bundle.getString(“stuff”);
This does happened also when you are cloning a repo without selecting any working directory. just make sure you did cd
into your working directory and i believe it will work just fine.
The tabularx
package gives you
X
, all X
columns will grow to fill up the total width.For your example:
\usepackage{tabularx}
% ...
\begin{document}
% ...
\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF & simulation & jsp\\
\hline
\end{tabularx}
You can also use the following code :
package com.agileinfotech.bsviewer.ldap;
import java.util.Hashtable;
import java.util.ResourceBundle;
import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class LDAPLoginAuthentication {
public LDAPLoginAuthentication() {
// TODO Auto-generated constructor
}
ResourceBundle resBundle = ResourceBundle.getBundle("settings");
@SuppressWarnings("unchecked")
public String authenticateUser(String username, String password) {
String strUrl = "success";
Hashtable env = new Hashtable(11);
boolean b = false;
String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
env.put(Context.SECURITY_CREDENTIALS, password);
try {
// Create initial context
DirContext ctx = new InitialDirContext(env);
// Close the context when we're done
b = true;
ctx.close();
} catch (NamingException e) {
b = false;
} finally {
if (b) {
strUrl = "success";
} else {
strUrl = "failer";
}
}
return strUrl;
}
}
Use this query:
SELECT USER();
Or
SELECT CURRENT_USER;
Try This:
(SELECT p.LastName, p.FirstName, o.OrderNo
FROM Persons p
LEFT JOIN Orders o
ON o.OrderNo = p.P_id
)
UNION
(SELECT p.LastName, p.FirstName, o.OrderNo
FROM Persons p
RIGHT JOIN Orders o
ON o.OrderNo = p.P_id
);
+----------+-----------+---------+
| LastName | FirstName | OrderNo |
+----------+-----------+---------+
| Singh | Shashi | 1 |
| Yadav | Sunil | NULL |
| Singh | Satya | NULL |
| Jain | Ankit | NULL |
| NULL | NULL | 11 |
| NULL | NULL | 12 |
| NULL | NULL | 13 |
+----------+-----------+---------+
You need to add a Custom Action to the end of the 'ExecuteImmediate' sequence in the MSI, using the component name of the EXE or a batch (sc start) as the source. I don't think this can be done with Visual Studio, you may have to use a real MSI authoring tool for that.
For CentOS, RHEL, Fedora:
$ yum search php-xml
============================================================================================================ N/S matched: php-xml ============================================================================================================
php-xml.x86_64 : A module for PHP applications which use XML
php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php-xmlseclibs.noarch : PHP library for XML Security
php54-php-xml.x86_64 : A module for PHP applications which use XML
php54-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php55-php-xml.x86_64 : A module for PHP applications which use XML
php55-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php56-php-xml.x86_64 : A module for PHP applications which use XML
php56-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php70-php-xml.x86_64 : A module for PHP applications which use XML
php70-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php71-php-xml.x86_64 : A module for PHP applications which use XML
php71-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php72-php-xml.x86_64 : A module for PHP applications which use XML
php72-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
php73-php-xml.x86_64 : A module for PHP applications which use XML
php73-php-xmlrpc.x86_64 : A module for PHP applications which use the XML-RPC protocol
Then select the php-xml version matching your php version:
# php -v
PHP 7.2.11 (cli) (built: Oct 10 2018 10:00:29) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
# sudo yum install -y php72-php-xml.x86_64
df = data.frame(matrix("", ncol = 3, nrow = 10)
Maybe this helps:
a = [{ 'main_color': 'red', 'second_color':'blue'},
{ 'main_color': 'yellow', 'second_color':'green'},
{ 'main_color': 'yellow', 'second_color':'blue'}]
def in_dictlist((key, value), my_dictlist):
for this in my_dictlist:
if this[key] == value:
return this
return {}
print in_dictlist(('main_color','red'), a)
print in_dictlist(('main_color','pink'), a)
cd /d c:\
git clone C:\folder1 folder2
From the documentation for git clone
:
For local repositories, also supported by git natively, the following syntaxes may be used:
/path/to/repo.git/ file:///path/to/repo.git/
These two syntaxes are mostly equivalent, except the former implies --local option.
Select project ? Properties ? Project Facets ? Target Runtimes ? VMware Server.
It worked for me.
No.
The only API browsers give you for handling cookies is getting and setting them via key-value pairs. All browsers handle cookies by domain name only.
Accessing all cookies for current domain is done via document.cookie
.
I'm developing a scientific calculator that sports an Int button. I've found the following is a simple, reliable solution:
double dblInteger;
if( dblNumber < 0 )
dblInteger = Math.Ceiling(dblNumber);
else
dblInteger = Math.Floor(dblNumber);
Math.Round sometimes produces unexpected or undesirable results, and explicit conversion to integer (via cast or Convert.ToInt...) often produces wrong values for higher-precision numbers. The above method seems to always work.
You can also name your foreign key constraint by using:
CONSTRAINT your_name_here FOREIGN KEY (question_exam_id) REFERENCES EXAMS (exam_id)
Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors
None of the rest of the answers use:
com.google.android.gms.location.FusedLocationProviderClient
Which is the Fused Location Provider and the main entry point for interacting with the fused location provider by Google, and it is very hard to find a good example. This was released mid 2017 by Google.
Google Play services location APIs are preferred over the Android framework location APIs (android.location)
If you are currently using the Android framework location APIs, you are strongly encouraged to switch to the Google Play services location APIs as soon as possible.
For you to use the Google Location API, first add this to your build.gradle
compile 'com.google.android.gms:play-services:11.0.0'
Then you can use this class Wherebouts.java
:
import android.location.Location;
import android.os.Looper;
import android.util.Log;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
/**
* Uses Google Play API for obtaining device locations
* Created by alejandro.tkachuk
* [email protected]
* www.calculistik.com Mobile Development
*/
public class Wherebouts {
private static final Wherebouts instance = new Wherebouts();
private static final String TAG = Wherebouts.class.getSimpleName();
private FusedLocationProviderClient mFusedLocationClient;
private LocationCallback locationCallback;
private LocationRequest locationRequest;
private LocationSettingsRequest locationSettingsRequest;
private Workable<GPSPoint> workable;
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 1000;
private Wherebouts() {
this.locationRequest = new LocationRequest();
this.locationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
this.locationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
this.locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(this.locationRequest);
this.locationSettingsRequest = builder.build();
this.locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult); // why? this. is. retarded. Android.
Location currentLocation = locationResult.getLastLocation();
GPSPoint gpsPoint = new GPSPoint(currentLocation.getLatitude(), currentLocation.getLongitude());
Log.i(TAG, "Location Callback results: " + gpsPoint);
if (null != workable)
workable.work(gpsPoint);
}
};
this.mFusedLocationClient = LocationServices.getFusedLocationProviderClient(MainApplication.getAppContext());
this.mFusedLocationClient.requestLocationUpdates(this.locationRequest,
this.locationCallback, Looper.myLooper());
}
public static Wherebouts instance() {
return instance;
}
public void onChange(Workable<GPSPoint> workable) {
this.workable = workable;
}
public LocationSettingsRequest getLocationSettingsRequest() {
return this.locationSettingsRequest;
}
public void stop() {
Log.i(TAG, "stop() Stopping location tracking");
this.mFusedLocationClient.removeLocationUpdates(this.locationCallback);
}
}
From your Activity, you can use it like this, by passing a Workable
object. A Workable object is nothing more than a custom Callback alike object.
Wherebouts.instance().onChange(workable);
By using a callback like Workable, you will write UI related code in your Activity and leave the hustle of working with GPS to a helper class, like Wherebouts.
new Workable<GPSPoint>() {
@Override
public void work(GPSPoint gpsPoint) {
// draw something in the UI with this new data
}
};
Of course you would need to ask for the corresponding permissions to the Android OS for your App to use. You can read the following documentation for more info about that or do some research.
I've solved this error by this way.
$ch = curl_init ();
curl_setopt ( $ch, CURLOPT_URL, 'http://www.someurl/' );
curl_setopt ( $ch, CURLOPT_TIMEOUT, 30);
ob_start();
$response = curl_exec ( $ch );
$data = ob_get_clean();
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200 ) success;
Error still occurs, but I can handle response data in variable.
This program in java returns "true" if number is a power of 2 and returns "false" if its not a power of 2
// To check if the given number is power of 2
import java.util.Scanner;
public class PowerOfTwo {
int n;
void solve() {
while(true) {
// To eleminate the odd numbers
if((n%2)!= 0){
System.out.println("false");
break;
}
// Tracing the number back till 2
n = n/2;
// 2/2 gives one so condition should be 1
if(n == 1) {
System.out.println("true");
break;
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
PowerOfTwo obj = new PowerOfTwo();
obj.n = in.nextInt();
obj.solve();
}
}
OUTPUT :
34
false
16
true
Ref and event bus both has issues when your control render is affected by v-if
. So, I decided to go with a simpler method.
The idea is using an array as a queue to send methods that needs to be called to the child component. Once the component got mounted, it will process this queue. It watches the queue to execute new methods.
(Borrowing some code from Desmond Lua's answer)
Parent component code:
import ChildComponent from './components/ChildComponent'
new Vue({
el: '#app',
data: {
item: {},
childMethodsQueue: [],
},
template: `
<div>
<ChildComponent :item="item" :methods-queue="childMethodsQueue" />
<button type="submit" @click.prevent="submit">Post</button>
</div>
`,
methods: {
submit() {
this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}})
}
},
components: { ChildComponent },
})
This is code for ChildComponent
<template>
...
</template>
<script>
export default {
name: 'ChildComponent',
props: {
methodsQueue: { type: Array },
},
watch: {
methodsQueue: function () {
this.processMethodsQueue()
},
},
mounted() {
this.processMethodsQueue()
},
methods: {
save() {
console.log("Child saved...")
},
processMethodsQueue() {
if (!this.methodsQueue) return
let len = this.methodsQueue.length
for (let i = 0; i < len; i++) {
let method = this.methodsQueue.shift()
this[method.name](method.params)
}
},
},
}
</script>
And there is a lot of room for improvement like moving processMethodsQueue
to a mixin...
SELECT REPLACE(REPLACE
((SELECT TOP (100) PERCENT country_name + ', ' AS CountryName
FROM country_name
ORDER BY country_name FOR XML PATH('')),
'&<CountryName>', ''), '&<CountryName>', '') AS CountryNames
based on @fabien-snauwaert's answer but simplified if you do not need the original key
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_values( $array ) as $index=>$value ) {
// display the current index + value
echo $index . ':' . $value;
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}
Use an example of instructions for making a breakfast
If you have experience cooking, you'd execute those instructions asynchronously. you'd start warming the pan for eggs, then start the bacon. You'd put the bread in the toaster, then start the eggs. At each step of the process, you'd start a task, then turn your attention to tasks that are ready for your attention.
Cooking breakfast is a good example of asynchronous work that isn't parallel. One person (or thread) can handle all these tasks. Continuing the breakfast analogy, one person can make breakfast asynchronously by starting the next task before the first completes. The cooking progresses whether or not someone is watching it. As soon as you start warming the pan for the eggs, you can begin frying the bacon. Once the bacon starts, you can put the bread into the toaster.
For a parallel algorithm, you'd need multiple cooks (or threads). One would make the eggs, one the bacon, and so on. Each one would be focused on just that one task. Each cook (or thread) would be blocked synchronously waiting for bacon to be ready to flip, or the toast to pop.
Reference from Asynchronous programming concepts
If you want a query to use currently selected database. simply copy paste this query. (No modification required)
SELECT table_name ,
round(((data_length + index_length) / 1024 / 1024), 2) as SIZE_MB
FROM information_schema.TABLES
WHERE table_schema = DATABASE() ORDER BY SIZE_MB DESC;
I would like to correct the @Neal answer which was pretty good for integers, but the number 1 would return a length of 0 in the previous case.
function Longueur(numberlen)
{
var length = 0, i; //define `i` with `var` as not to clutter the global scope
numberlen = parseInt(numberlen);
for(i = numberlen; i >= 1; i)
{
++length;
i = Math.floor(i/10);
}
return length;
}
Hope this helps somebody: I've been using the registry-based enumeration in my scripts (as suggested by some of the answers above), but have found that it does not properly enumerate 64-bit software when run on Windows 10 x64 via SCCM (which uses a 32-bit client). Found something like this to be the most straightforward solution in my particular case:
Function Get-Programs($Bits) {
$Result = @()
$Output = (reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall /reg:$Bits /s)
Foreach ($Line in $Output) {
If ($Line -match '^\s+DisplayName\s+REG_SZ\s+(.+?)$') {
$Result += New-Object PSObject -Property @{
DisplayName = $matches[1];
Bits = "$($Bits)-bit";
}
}
}
$Result
}
$Software = Get-Programs 32
$Software += Get-Programs 64
Realize this is a little too Perl-ish in a bad way, but all other alternatives I've seen involved insanity with wrapper scripts and similar clever-clever solutions, and this seems a little more human.
P.S. Trying really hard to refrain from dumping a ton of salt on Microsoft here for making an absolutely trivial thing next to impossible. I.e., enumerating all MS Office versions in use on a network is a task to make a grown man weep.
I believe this works:
def cartesian_product(L):
if L:
return {(a,) + b for a in L[0]
for b in cartesian_product(L[1:])}
else:
return {()}
I used "docker system prune -a" it cleaned all files under volumes and overlay2
[root@jasontest volumes]# docker system prune -a
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all images without at least one container associated to them
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Images:
untagged: ubuntu:12.04
untagged: ubuntu@sha256:18305429afa14ea462f810146ba44d4363ae76e4c8dfc38288cf73aa07485005
deleted: sha256:5b117edd0b767986092e9f721ba2364951b0a271f53f1f41aff9dd1861c2d4fe
deleted: sha256:8c7f3d7534c80107e3a4155989c3be30b431624c61973d142822b12b0001ece8
deleted: sha256:969d5a4e73ab4e4b89222136eeef2b09e711653b38266ef99d4e7a1f6ea984f4
deleted: sha256:871522beabc173098da87018264cf3e63481628c5080bd728b90f268793d9840
deleted: sha256:f13e8e542cae571644e2f4af25668fadfe094c0854176a725ebf4fdec7dae981
deleted: sha256:58bcc73dcf4050a4955916a0dcb7e5f9c331bf547d31e22052f1b5fa16cf63f8
untagged: osixia/openldap:1.2.1
untagged: osixia/openldap@sha256:6ceb347feb37d421fcabd80f73e3dc6578022d59220cab717172ea69c38582ec
deleted: sha256:a562f6fd60c7ef2adbea30d6271af8058c859804b2f36c270055344739c06d64
deleted: sha256:90efa8a88d923fb1723bea8f1082d4741b588f7fbcf3359f38e8583efa53827d
deleted: sha256:8d77930b93c88d2cdfdab0880f3f0b6b8be191c23b04c61fa1a6960cbeef3fe6
deleted: sha256:dd9f76264bf3efd36f11c6231a0e1801c80d6b4ca698cd6fa2ff66dbd44c3683
deleted: sha256:00efc4fb5e8a8e3ce0cb0047e4c697646c88b68388221a6bd7aa697529267554
deleted: sha256:e64e6259fd63679a3b9ac25728f250c3afe49dbe457a1a80550b7f1ccf68458a
deleted: sha256:da7d34d626d2758a01afe816a9434e85dffbafbd96eb04b62ec69029dae9665d
deleted: sha256:b132dace06fa7e22346de5ca1ae0c2bf9acfb49fe9dbec4290a127b80380fe5a
deleted: sha256:d626a8ad97a1f9c1f2c4db3814751ada64f60aed927764a3f994fcd88363b659
untagged: centos:centos7
untagged: centos@sha256:2671f7a3eea36ce43609e9fe7435ade83094291055f1c96d9d1d1d7c0b986a5d
deleted: sha256:ff426288ea903fcf8d91aca97460c613348f7a27195606b45f19ae91776ca23d
deleted: sha256:e15afa4858b655f8a5da4c4a41e05b908229f6fab8543434db79207478511ff7
Total reclaimed space: 533.3MB
[root@jasontest volumes]# ls -alth
total 32K
-rw------- 1 root root 32K May 23 21:14 metadata.db
drwx------ 2 root root 4.0K May 23 21:14 .
drwx--x--x 14 root root 4.0K May 21 20:26 ..
Without calculating height. Strict CSS and HTML. <span/>
only for Chrome, because the chrome isn't able change text direction for <th/>
.
th _x000D_
{_x000D_
vertical-align: bottom;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
th span _x000D_
{_x000D_
-ms-writing-mode: tb-rl;_x000D_
-webkit-writing-mode: vertical-rl;_x000D_
writing-mode: vertical-rl;_x000D_
transform: rotate(180deg);_x000D_
white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<th><span>Rotated text by 90 deg.</span></th>_x000D_
</tr>_x000D_
</table>
_x000D_
for me ,with JDK11 and IntelliJ 2016.3 , I kept getting the same message so I decided to uninstall JDK11 and installed JDK8 instead and it immediately worked!
I was getting this problem when using IBM RSA 9.6.1 when building a brand new development machine. The problem for me ended up being because of HTTPS on the Global Maven repository. My solution was to create a Maven settings.xml that forced it to use HTTP.
The key to me was that the central repository was empty when I exploded it under Maven Repositories -- > Global Repositories
Using the following settings file worked for me:
<settings>
<activeProfiles>
<!--make the profile active all the time -->
<activeProfile>insecurecentral</activeProfile>
</activeProfiles>
<profiles>
<profile>
<id>insecurecentral</id>
<!--Override the repository (and pluginRepository) "central" from the Maven Super POM -->
<repositories>
<repository>
<id>central</id>
<url>http://repo.maven.apache.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://repo.maven.apache.org/maven2</url>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
</settings>
There's a better solution if you don't really need the memory address but rather some means of uniquely identifying a managed object:
using System.Runtime.CompilerServices;
public static class Extensions
{
private static readonly ConditionalWeakTable<object, RefId> _ids = new ConditionalWeakTable<object, RefId>();
public static Guid GetRefId<T>(this T obj) where T: class
{
if (obj == null)
return default(Guid);
return _ids.GetOrCreateValue(obj).Id;
}
private class RefId
{
public Guid Id { get; } = Guid.NewGuid();
}
}
This is thread safe and uses weak references internally, so you won't have memory leaks.
You can use any key generation means that you like. I'm using Guid.NewGuid()
here because it's simple and thread safe.
I went ahead and created a Nuget package Overby.Extensions.Attachments that contains some extension methods for attaching objects to other objects. There's an extension called GetReferenceId()
that effectively does what the code in this answer shows.
Just do that: getTabAt(index of your tab)
ActionBar actionBar = getSupportActionBar();
actionBar.selectTab(actionBar.getTabAt(0));
Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.
If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).
This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.
https://support.microsoft.com/en-us/kb/938397
For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:
http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe
I hesitate to add yet another answer here as there are already quite a few, but a few points need to be made that have either not been made or not been made clearly.
First: Do not always use NVARCHAR
. That is a very dangerous, and often costly, attitude / approach. And it is no better to say "Never use cursors" since they are sometimes the most efficient means of solving a particular problem, and the common work-around of doing a WHILE
loop will almost always be slower than a properly done Cursor.
The only time you should use the term "always" is when advising to "always do what is best for the situation". Granted that is often difficult to determine, especially when trying to balance short-term gains in development time (manager: "we need this feature -- that you didn't know about until just now -- a week ago!") with long-term maintenance costs (manager who initially pressured team to complete a 3-month project in a 3-week sprint: "why are we having these performance problems? How could we have possibly done X which has no flexibility? We can't afford a sprint or two to fix this. What can we get done in a week so we can get back to our priority items? And we definitely need to spend more time in design so this doesn't keep happening!").
Second: @gbn's answer touches on some very important points to consider when making certain data modeling decisions when the path isn't 100% clear. But there is even more to consider:
Wasting space has a huge cascade effect on the entire system. I wrote an article going into explicit detail on this topic: Disk Is Cheap! ORLY? (free registration required; sorry I don't control that policy).
Third: While some answers are incorrectly focusing on the "this is a small app" aspect, and some are correctly suggesting to "use what is appropriate", none of the answers have provided real guidance to the O.P. An important detail mentioned in the Question is that this is a web page for their school. Great! So we can suggest that:
NVARCHAR
since, over time, it is only getting more likely that names from other cultures will be showing up in those places.VARCHAR
with the appropriate Code Page (which is determined from the Collation of the field).INT
/ TINYINT
since ISO codes are fixed length, human readable, and well, standard :) use CHAR(2)
for two letter codes and CHAR(3)
if using 3 letter codes. And consider using a binary Collation such as Latin1_General_100_BIN2
.VARCHAR
since it is an international standard to never use any letter outside of A-Z. And yes, still use VARCHAR
even if only storing US zip codes and not INT since zip codes are not numbers, they are strings, and some of them have a leading "0". And consider using a binary Collation such as Latin1_General_100_BIN2
.NVARCHAR
since both of those can now contain Unicode characters.Fourth: Now that you have NVARCHAR
data taking up twice as much space than it needs to for data that fits nicely into VARCHAR
("fits nicely" = doesn't turn into "?") and somehow, as if by magic, the application did grow and now there are millions of records in at least one of these fields where most rows are standard ASCII but some contain Unicode characters so you have to keep NVARCHAR
, consider the following:
If you are using SQL Server 2008 - 2016 RTM and are on Enterprise Edition, OR if using SQL Server 2016 SP1 (which made Data Compression available in all editions) or newer, then you can enable Data Compression. Data Compression can (but won't "always") compress Unicode data in NCHAR
and NVARCHAR
fields. The determining factors are:
NCHAR(1 - 4000)
and NVARCHAR(1 - 4000)
use the Standard Compression Scheme for Unicode, but only starting in SQL Server 2008 R2, AND only for IN ROW data, not OVERFLOW! This appears to be better than the regular ROW / PAGE compression algorithm.NVARCHAR(MAX)
and XML
(and I guess also VARBINARY(MAX)
, TEXT
, and NTEXT
) data that is IN ROW (not off row in LOB or OVERFLOW pages) can at least be PAGE compressed, but not ROW compressed. Of course, PAGE compression depends on size of the in-row value: I tested with VARCHAR(MAX) and saw that 6000 character/byte rows would not compress, but 4000 character/byte rows did.If using SQL Server 2005, or 2008 - 2016 RTM and not on Enterprise Edition, you can have two fields: one VARCHAR
and one NVARCHAR
. For example, let's say you are storing URLs which are mostly all base ASCII characters (values 0 - 127) and hence fit into VARCHAR
, but sometimes have Unicode characters. Your schema can include the following 3 fields:
...
URLa VARCHAR(2048) NULL,
URLu NVARCHAR(2048) NULL,
URL AS (ISNULL(CONVERT(NVARCHAR([URLa])), [URLu])),
CONSTRAINT [CK_TableName_OneUrlMax] CHECK (
([URLa] IS NOT NULL OR [URLu] IS NOT NULL)
AND ([URLa] IS NULL OR [URLu] IS NULL))
);
In this model you only SELECT from the [URL]
computed column. For inserting and updating, you determine which field to use by seeing if converting alters the incoming value, which has to be of NVARCHAR
type:
INSERT INTO TableName (..., URLa, URLu)
VALUES (...,
IIF (CONVERT(VARCHAR(2048), @URL) = @URL, @URL, NULL),
IIF (CONVERT(VARCHAR(2048), @URL) <> @URL, NULL, @URL)
);
You can GZIP incoming values into VARBINARY(MAX)
and then unzip on the way out:
COMPRESS
and DECOMPRESS
functions, which are also GZip.If using SQL Server 2017 or newer, you can look into making the table a Clustered Columnstore Index.
While this is not a viable option yet, SQL Server 2019 introduces native support for UTF-8 in VARCHAR
/ CHAR
datatypes. There are currently too many bugs with it for it to be used, but if they are fixed, then this is an option for some scenarios. Please see my post, "Native UTF-8 Support in SQL Server 2019: Savior or False Prophet?", for a detailed analysis of this new feature.
This worked for me:
from django.utils.encoding import smart_str
content = smart_str(content)
Whenever changes are made in dockerfile or compose or requirements , re-Run it using docker-compose up --build
. So that images get rebuild and refreshed
New Function and apply() together works also
var a=new Function('alert(1);')
a.apply(null)
Use dropna:
dat.dropna()
You can pass param how
to drop if all labels are nan or any of the labels are nan
dat.dropna(how='any') #to drop if any value in the row has a nan
dat.dropna(how='all') #to drop if all values in the row are nan
Hope that answers your question!
Edit 1:
In case you want to drop rows containing nan
values only from particular column(s), as suggested by J. Doe in his answer below, you can use the following:
dat.dropna(subset=[col_list]) # col_list is a list of column names to consider for nan values.
These guys have an API that will give the results. It's also free to use.
Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.
JACKSON Library
One option would be to use Jackson library. First import the latest version (now is):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.0</version>
</dependency>
Then, you can implement the correct answer as follows:
import com.fasterxml.jackson.databind.ObjectMapper;
public final class JSONUtils {
private JSONUtils(){}
public static boolean isJSONValid(String jsonInString ) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonInString);
return true;
} catch (IOException e) {
return false;
}
}
}
Google GSON option
Another option is to use Google Gson. Import the dependency:
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.5</version>
</dependency>
Again, you can implement the proposed solution as:
import com.google.gson.Gson;
public final class JSONUtils {
private static final Gson gson = new Gson();
private JSONUtils(){}
public static boolean isJSONValid(String jsonInString) {
try {
gson.fromJson(jsonInString, Object.class);
return true;
} catch(com.google.gson.JsonSyntaxException ex) {
return false;
}
}
}
A simple test follows here:
//A valid JSON String to parse.
String validJsonString = "{ \"developers\": [{ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
// Invalid String with a missing parenthesis at the beginning.
String invalidJsonString = "\"developers\": [ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
"{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";
boolean firstStringValid = JSONUtils.isJSONValid(validJsonString); //true
boolean secondStringValid = JSONUtils.isJSONValid(invalidJsonString); //false
Please, observe that there could be a "minor" issue due to trailing commas that will be fixed in release 3.0.0
.
You're able to do database finds using LIKE with this syntax:
Model::where('column', 'LIKE', '%value%')->get();
The class which implements KeyListener
interface becomes our custom key event listener. This listener can not directly listen the key events. It can only listen the key events through intermediate objects such as JFrame
. So
Make one Key listener class as
class MyListener implements KeyListener{
// override all the methods of KeyListener interface.
}
Now our class MyKeyListener
is ready to listen the key events. But it can not directly do so.
Create any object like JFrame
object through which MyListener
can listen the key events. for that you need to add MyListener
object to the JFrame
object.
JFrame f=new JFrame();
f.addKeyListener(new MyKeyListener);
There's not really a good way to do this, usually you see an extra item in the enum, i.e.
enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};
So then you can do:
int fuz[FOOBAR_NR_ITEMS];
Still not very nice though.
But of course you do realize that just the number of items in an enum is not safe, given e.g.
enum foobar {foo, bar = 5, baz, quz = 20};
the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.
edit: as requested, made the special entry stick out more.
Use index=False
.
df.to_csv('your.csv', index=False)
For me it's work with that code (with jQuery):
var int = null,
fired = false;
var longclickFilm = function($t) {
$body.css('background', 'red');
},
clickFilm = function($t) {
$t = $t.clone(false, false);
var $to = $('footer > div:first');
$to.find('.empty').remove();
$t.appendTo($to);
},
touchStartFilm = function(event) {
event.preventDefault();
fired = false;
int = setTimeout(function($t) {
longclickFilm($t);
fired = true;
}, 2000, $(this)); // 2 sec for long click ?
return false;
},
touchEndFilm = function(event) {
event.preventDefault();
clearTimeout(int);
if (fired) return false;
else clickFilm($(this));
return false;
};
$('ul#thelist .thumbBox')
.live('mousedown touchstart', touchStartFilm)
.live('mouseup touchend touchcancel', touchEndFilm);
Use std::printf and c_str() example:
std::printf("Follow this command: %s", myString.c_str());
The title of your question is:
How to join a slice of strings into a single string?
but in fact, reg
is not a slice, but a length-three array. [...]string
is just syntactic sugar for (in this case) [3]string
.
To get an actual slice, you should write:
reg := []string {"a","b","c"}
(Try it out: https://play.golang.org/p/vqU5VtDilJ.)
Incidentally, if you ever really do need to join an array of strings into a single string, you can get a slice from the array by adding [:]
, like so:
fmt.Println(strings.Join(reg[:], ","))
(Try it out: https://play.golang.org/p/zy8KyC8OTuJ.)
You can net set it to view height
html, body
{
height: 100vh;
}
You can also just add the authorization header yourself.
Just make the name "Authorization" and the value "Basic BASE64({USERNAME:PASSWORD})"
String username = "abc";
String password = "123";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
Switched the encoding from UTF-8 to ISO 8859-1 per What encoding should I use for HTTP Basic Authentication? and Jeroen's comment.
If you ever run in a situation where you need to get the next char of the word using __next__()
, remember to create a string_iterator
and iterate over it and not the original string (it does not have the __next__() method)
In this example, when I find a char = [
I keep looking into the next word while I don't find ]
, so I need to use __next__
here a for loop over the string wouldn't help
myString = "'string' 4 '['RP0', 'LC0']' '[3, 4]' '[3, '4']'"
processedInput = ""
word_iterator = myString.__iter__()
for idx, char in enumerate(word_iterator):
if char == "'":
continue
processedInput+=char
if char == '[':
next_char=word_iterator.__next__()
while(next_char != "]"):
processedInput+=next_char
next_char=word_iterator.__next__()
else:
processedInput+=next_char
Try passing it directly to the ng-click function:
<div class="col-lg-1 text-center">
<span class="glyphicon glyphicon-trash" data="{{event.id}}"
ng-click="deleteEvent(event.id)"></span>
</div>
Then it should be available in your handler:
$scope.deleteEvent=function(idPassedFromNgClick){
console.log(idPassedFromNgClick);
}
Here's an example
I had the same issue and the reason behind this issue is that the dll file of reference project is being used by some other process. In my case, I was debugging an application and application was attached with visual studio debugger. When I was re-building another application which is using same project, then I was getting this error. After de-attaching, I was able to build second application successfully.
PyPy has had Python 3 support for a while, but according to this HackerNoon post by Anthony Shaw from April 2nd, 2018, PyPy3 is still several times slower than PyPy (Python 2).
For many scientific calculations, particularly matrix calculations, numpy is a better choice (see FAQ: Should I install numpy or numpypy?).
Pypy does not support gmpy2. You can instead make use of gmpy_cffi though I haven't tested its speed and the project had one release in 2014.
For Project Euler problems, I make frequent use of PyPy, and for simple numerical calculations often from __future__ import division
is sufficient for my purposes, but Python 3 support is still being worked on as of 2018, with your best bet being on 64-bit Linux. Windows PyPy3.5 v6.0, the latest as of December 2018, is in beta.
I think this article explains well:
Running Commands on a Remote Linux / UNIX Host
Google is your best friend ;-)
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png
file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.
Use these:
webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);
It sounds like you have no web server running at all anywhere.
Have you tried enabling IIS and using it to display a basic html file first?
Programs & Features -> Turn Windows Features On/Off -> Internet Information Servcies
Then, place your html file in C:\inetpub\wwwroot\index.html and browse to http://localhost.
Once this works, try to get WAMP/php working. Be careful of port conflicts.