Late answer but:
I see you do a GET - should be a POST ?
I fixed this problem with sql command line:
connect system/<password>
alter system set processes=300 scope=spfile;
alter system set sessions=300 scope=spfile;
Restart database.
Which app server are you using? Each one puts its logging config in a different place, though most nowadays use Commons-Logging as a wrapper around either Log4J or java.util.logging.
Using Tomcat as an example, this document explains your options for configuring logging using either option. In either case you need to find or create a config file that defines the log level for each package and each place the logging system will output log info (typically console, file, or db).
In the case of log4j this would be the log4j.properties file, and if you follow the directions in the link above your file will start out looking like:
log4j.rootLogger=DEBUG, R
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=${catalina.home}/logs/tomcat.log
log4j.appender.R.MaxFileSize=10MB
log4j.appender.R.MaxBackupIndex=10
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%p %t %c - %m%n
Simplest would be to change the line:
log4j.rootLogger=DEBUG, R
To something like:
log4j.rootLogger=WARN, R
But if you still want your own DEBUG level output from your own classes add a line that says:
log4j.category.com.mypackage=DEBUG
Reading up a bit on Log4J and Commons-Logging will help you understand all this.
Check the XML. It is not a valid xml.
Prolog is the first line with xml version info. It ok not to include it in your xml.
This error is thrown when the parser reads an invalid tag at the start of the document. Normally where the prolog resides.
e.g.
You can find some resources related to developing web services client using Apache axis2 here.
http://today.java.net/pub/a/today/2006/12/13/invoking-web-services-using-apache-axis2.html
Below posts gives good explanations about developing web services using Apache axis2.
http://www.ibm.com/developerworks/opensource/library/ws-webaxis1/
Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)
$timeFirst = strtotime('2011-05-12 18:20:20');
$timeSecond = strtotime('2011-05-13 18:20:20');
$differenceInSeconds = $timeSecond - $timeFirst;
You will then be able to use the seconds to find minutes, hours, days, etc.
After replacing the character, you need to be asign to the variable.
var tt = "88,9827";
tt = tt.replace(/,/g, '.')
alert(tt)
In the alert box it will shows 88.9827
This was my solution after a lot of struggling to reduce the rating bar in small size without even ugly padding
<RatingBar
android:id="@+id/listitemrating"
style="@android:attr/ratingBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleX=".5"
android:scaleY=".5"
android:transformPivotX="0dp"
android:transformPivotY="0dp"
android:isIndicator="true"
android:max="5" />
The ID of a form input element has nothing to do with the data contained within the element. IDs are for hooking the element with JavaScript and CSS. The name attribute, however, is used in the HTTP request sent by your browser to the server as a variable name associated with the data contained in the value attribute.
For instance:
<form>
<input type="text" name="user" value="bob">
<input type="password" name="password" value="abcd1234">
</form>
When the form is submitted, the form data will be included in the HTTP header like this:
If you add an ID attribute, it will not change anything in the HTTP header. It will just make it easier to hook it with CSS and JavaScript.
I have not used the classes from the Java NIO package, but it seems they might be of some help here. Specifically, java.nio.channels.Channels and java.nio.channels.InterruptibleChannel.
Here's a specific problem I ran into when downloading a project from the internet.
To complete a bit more previous great answers, you need to be aware that forms leverage observables to detect and handle value changes. It's something really important and powerful. Both Mark and dfsq described this aspect in their answers.
Observables allow not only to use the subscribe
method (something similar to the then
method of promises in Angular 1). You can go further if needed to implement some processing chains for updated data in forms.
I mean you can specify at this level the debounce time with the debounceTime
method. This allows you to wait for an amount of time before handling the change and correctly handle several inputs:
this.form.valueChanges
.debounceTime(500)
.subscribe(data => console.log('form changes', data));
You can also directly plug the processing you want to trigger (some asynchronous one for example) when values are updated. For example, if you want to handle a text value to filter a list based on an AJAX request, you can leverage the switchMap
method:
this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
You even go further by linking the returned observable directly to a property of your component:
this.list = this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
and display it using the async
pipe:
<ul>
<li *ngFor="#elt of (list | async)">{{elt.name}}</li>
</ul>
Just to say that you need to think the way to handle forms differently in Angular2 (a much more powerful way ;-)).
Hope it helps you, Thierry
Shift-tab outdents again :)
Here's where the standard shortcut keys are covered:
http://wiki.eclipse.org/User_Interface_Guidelines#Standard_Accelerators
You'll find many of the more esoteric ones here:
http://wiki.eclipse.org/FAQ_What_editor_keyboard_shortcuts_are_available%3F
You can create text columns with CSS Multiple Columns property. You don't need any table or multiple divs.
HTML
<div class="column">
<!-- paragraph text comes here -->
</div>
CSS
.column {
column-count: 2;
column-gap: 40px;
}
Read more about CSS Multiple Columns at https://www.w3schools.com/css/css3_multiple_columns.asp
Try this:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
}
);
For doing everything else you can use something like this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$(".ClassNameOfShouldBeHiddenElements").hide();
}
);
For hidding any other elements based on their IDs, use this one:
$('input[name=Comanda]')
.click(
function ()
{
$(this).hide();
$("#FirstElement").hide();
$("#SecondElement").hide();
$("#ThirdElement").hide();
}
);
XML version for @Asher Aslan cool effect.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<gradient
android:angle="180"
android:startColor="#00000000"
android:centerColor="#FFFF0000"
android:endColor="#00000000"/>
</shape>
Name for that shape as: list_driver.xml under drawable folder
<ListView
android:id="@+id/category_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="@drawable/list_driver"
android:dividerHeight="5sp" />
It is an "INEQUALITY" operator. Get a list of comparison operators in VBA
Ezward has already provided a good answer, but I noticed that one of the comments asks how it is used. For people like me who stumble across this question, I thought it would be useful to have a link to the official documentation on getters and setters on the Typescript website as that explains it well, will hopefully always stay up-to-date as changes are made, and shows example usage:
http://www.typescriptlang.org/docs/handbook/classes.html
In particular, for those not familiar with it, note that you don't incorporate the word 'get' into a call to a getter (and similarly for setters):
var myBar = myFoo.getBar(); // wrong
var myBar = myFoo.get('bar'); // wrong
You should simply do this:
var myBar = myFoo.bar; // correct (get)
myFoo.bar = true; // correct (set) (false is correct too obviously!)
given a class like:
class foo {
private _bar:boolean = false;
get bar():boolean {
return this._bar;
}
set bar(theBar:boolean) {
this._bar = theBar;
}
}
then the 'bar' getter for the private '_bar' property will be called.
Use the login
utility to create a login shell. Assume that the user you want to log in has the username Alice and that zsh is installed in /opt/local/bin/zsh
(e.g., a more recent version installed via MacPorts). In iTerm 2, go to Preferences, Profiles, select the profile that you want to set up, and enter in Command:
login -pfq Alice /opt/local/bin/zsh
See man login
for more details on the options.
If you're using .NET 3.5 SP1+ the better way to do this is to take a look at the
System.DirectoryServices.AccountManagement namespace.
It has methods to find people and you can pretty much pass in any username format you want and then returns back most of the basic information you would need. If you need help on loading the more complex objects and properties check out the source code for http://umanage.codeplex.com its got it all.
Brent
Based on comments, and due to the fact that @Thinkerer (the OP - original poster) created a plunker for this case, I decided to append another answer with more details.
The first and important change:
// instead of this
$urlRouterProvider.otherwise('/tab/post');
// we have to use this
$urlRouterProvider.otherwise('/tab/posts');
because the states definition is:
.state('tab', {
url: "/tab",
abstract: true,
templateUrl: 'tabs.html'
})
.state('tab.posts', {
url: '/posts',
views: {
'tab-posts': {
templateUrl: 'tab-posts.html',
controller: 'PostsCtrl'
}
}
})
and we need their concatenated url '/tab'
+ '/posts'
. That's the url we want to use as a otherwise
The rest of the application is really close to the result we need...
E.g. we stil have to place the content into same view targetgood, just these were changed:
.state('tab.newpost', {
url: '/newpost',
views: {
// 'tab-newpost': {
'tab-posts': {
templateUrl: 'tab-newpost.html',
controller: 'NavCtrl'
}
}
because .state('tab.newpost'
would be replacing the .state('tab.posts'
we have to place it into the same anchor:
<ion-nav-view name="tab-posts"></ion-nav-view>
Finally some adjustments in controllers:
$scope.create = function() {
$state.go('tab.newpost');
};
$scope.close = function() {
$state.go('tab.posts');
};
As I already said in my previous answer and comments ... the $state.go()
is the only right way how to use ionic
or ui-router
Check that all here
Final note - I made running just navigation between tab.posts
... tab.newpost
... the rest would be similar
Using dplyr
and tidyr
:
library(dplyr)
library(tidyr)
df <- as_data_frame(mat) %>% # convert the matrix to a data frame
gather(name, val, C_0:C_1) %>% # convert the data frame from wide to long
select(name, time, val) # reorder the columns
df
# A tibble: 6 x 3
name time val
<chr> <dbl> <dbl>
1 C_0 0.0 0.1
2 C_0 0.5 0.2
3 C_0 1.0 0.3
4 C_1 0.0 0.3
5 C_1 0.5 0.4
6 C_1 1.0 0.5
params
is for GET-style URL parameters, data
is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.
Your raw post contains JSON data though. requests
can handle JSON encoding for you, and it'll set the correct Content-Type
header too; all you need to do is pass in the Python object to be encoded as JSON into the json
keyword argument.
You could split out the URL parameters as well:
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
then post your data with:
import requests
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, json=data)
The json
keyword is new in requests
version 2.4.2; if you still have to use an older version, encode the JSON manually using the json
module and post the encoded result as the data
key; you will have to explicitly set the Content-Type header in that case:
import requests
import json
headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'
data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}
requests.post(url, params=params, data=json.dumps(data), headers=headers)
What do you mean costs too much? Too much what?
SELECT MAX(Balance) AS MaxBalance, CustomerID FROM CUSTOMERS GROUP BY CustomerID
If your table is properly indexed (Balance) and there has got to be an index on the PK than I am not sure what you mean about costs too much or seems unreliable? There is nothing unreliable about an aggregate that you are using and telling it to do. In this case, MAX()
does exactly what you tell it to do - there's nothing magical about it.
Take a look at MAX()
and if you want to filter it use the HAVING
clause.
It doesn't set the default value because your model isn't bound to the id or name properties, it's bound to each version
object. Try setting the versionID
to one of the objects and it should work, ie $scope.item.versionID = $scope.versions[2];
If you want to set by the id property then you need to add the select as
syntax:
ng-options="version.id as version.name for version in versions"
I believe that using a combination of interfaces and base classes could work for you. It will enforce behavioral requirements at compile time (rq_ post "below" refers to a post above, which is not this one).
The interface sets the behavioral API that isn't met by the base class. You will not be able to set base class methods to call on methods defined in the interface (because you will not be able to implement that interface in the base class without having to define those behaviors). Maybe someone can come up with a safe trick to allow calling of the interface methods in the parent.
You have to remember to extend and implement in the class you will instantiate. It satisfies concerns about defining runtime-fail code. You also won't even be able to call the methods that would puke if you haven't implemented the interface (such as if you try to instantiate the Animal class). I tried having the interface extend the BaseAnimal below, but it hid the constructor and the 'name' field of BaseAnimal from Snake. If I had been able to do that, the use of a module and exports could have prevented accidental direct instantiation of the BaseAnimal class.
Paste this in here to see if it works for you: http://www.typescriptlang.org/Playground/
// The behavioral interface also needs to extend base for substitutability
interface AbstractAnimal extends BaseAnimal {
// encapsulates animal behaviors that must be implemented
makeSound(input : string): string;
}
class BaseAnimal {
constructor(public name) { }
move(meters) {
alert(this.name + " moved " + meters + "m.");
}
}
// If concrete class doesn't extend both, it cannot use super methods.
class Snake extends BaseAnimal implements AbstractAnimal {
constructor(name) { super(name); }
makeSound(input : string): string {
var utterance = "sssss"+input;
alert(utterance);
return utterance;
}
move() {
alert("Slithering...");
super.move(5);
}
}
var longMover = new Snake("windy man");
longMover.makeSound("...am I nothing?");
longMover.move();
var fulture = new BaseAnimal("bob fossil");
// compile error on makeSound() because it is not defined.
// fulture.makeSound("you know, like a...")
fulture.move(1);
I came across FristvanCampen's answer as linked below. He says abstract classes are an anti-pattern, and suggests that one instantiate base 'abstract' classes using an injected instance of an implementing class. This is fair, but there are counter arguments made. Read for yourself: https://typescript.codeplex.com/discussions/449920
Part 2: I had another case where I wanted an abstract class, but I was prevented from using my solution above, because the defined methods in the "abstract class" needed to refer to the methods defined in the matching interface. So, I tool FristvanCampen's advice, sort of. I have the incomplete "abstract" class, with method implementations. I have the interface with the unimplemented methods; this interface extends the "abstract" class. I then have a class that extends the first and implements the second (it must extend both because the super constructor is inaccessible otherwise). See the (non-runnable) sample below:
export class OntologyConceptFilter extends FilterWidget.FilterWidget<ConceptGraph.Node, ConceptGraph.Link> implements FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link> {
subMenuTitle = "Ontologies Rendered"; // overload or overshadow?
constructor(
public conceptGraph: ConceptGraph.ConceptGraph,
graphView: PathToRoot.ConceptPathsToRoot,
implementation: FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link>
){
super(graphView);
this.implementation = this;
}
}
and
export class FilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> {
public implementation: IFilterWidget<N, L>
filterContainer: JQuery;
public subMenuTitle : string; // Given value in children
constructor(
public graphView: GraphView.GraphView<N, L>
){
}
doStuff(node: N){
this.implementation.generateStuff(thing);
}
}
export interface IFilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> extends FilterWidget<N, L> {
generateStuff(node: N): string;
}
Following leppie's answer, why not make MetaData
an interface:
public interface IMetaData { }
public class Metadata<DataType> : IMetaData where DataType : struct
{
private DataType mDataType;
}
The first syntax is redundant - the WITH CHECK
is default for new constraints, and the constraint is turned on by default as well.
This syntax is generated by the SQL management studio when generating sql scripts -- I'm assuming it's some sort of extra redundancy, possibly to ensure the constraint is enabled even if the default constraint behavior for a table is changed.
Open the command prompt in Windows or terminal in Linux and Mac.Type
node -v
If node is install it will show its version.For eg.,
v6.9.5
Else download it from nodejs.org
No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string )
(see section 1.2), and your example doesn't use "=" that way.
Here's my little class that can reprint blocks of text. It properly clears the previous text so you can overwrite your old text with shorter new text without creating a mess.
import re, sys
class Reprinter:
def __init__(self):
self.text = ''
def moveup(self, lines):
for _ in range(lines):
sys.stdout.write("\x1b[A")
def reprint(self, text):
# Clear previous text by overwritig non-spaces with spaces
self.moveup(self.text.count("\n"))
sys.stdout.write(re.sub(r"[^\s]", " ", self.text))
# Print new text
lines = min(self.text.count("\n"), text.count("\n"))
self.moveup(lines)
sys.stdout.write(text)
self.text = text
reprinter = Reprinter()
reprinter.reprint("Foobar\nBazbar")
reprinter.reprint("Foo\nbar")
Another option:
def map = ['a':1, 'b':2, 'c':3]
map.each{
println it.key +" "+ it.value
}
Instead of counting up, you can also count down:
nrToProcess = len(list)
for s in list:
s.doStuff()
nrToProcess -= 1
if nrToProcess==0: # this is the last one
s.doSpecialStuff()
You can use the @Qualifier annotation
From here
Fine-tuning annotation-based autowiring with qualifiers
Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:
class Main {
private Country country;
@Autowired
@Qualifier("country")
public void setCountry(Country country) {
this.country = country;
}
}
This will use the UK add an id to USA bean and use that if you want the USA.
Using Java 8 and a HashMap without any library for counting all the different chars:
private static void countChars(String string) {
HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();
string.chars().forEach(letter -> hm.put(letter, (hm.containsKey(letter) ? hm.get(letter) : 0) + 1));
hm.forEach((c, i) -> System.out.println(((char)c.intValue()) + ":" + i));
}
There are workarounds but no clean/short/sweet way to do it with streams and to be honest, you would probably be better off with:
int idx = 0;
for (Param p : params) query.bind(idx++, p);
Or the older style:
for (int idx = 0; idx < params.size(); idx++) query.bind(idx, params.get(idx));
ActionListener gets fired first, with an option to modify the response, before Action gets called and determines the location of the next page.
If you have multiple buttons on the same page which should go to the same place but do slightly different things, you can use the same Action for each button, but use a different ActionListener to handle slightly different functionality.
Here is a link that describes the relationship:
If your system is using dpkg and apt (debian, ubuntu, etc), try running the following commands in that order (be careful with the sudo rm
commands):
sudo apt-get -f install
sudo dpkg -P phpmyadmin
sudo rm -vf /etc/apache2/conf.d/phpmyadmin.conf
sudo rm -vfR /usr/share/phpmyadmin
sudo service apache2 restart
Create a text node and append it to the button element:
var t = document.createTextNode("test content");
b.appendChild(t);
For your last question, why ? I'll try to explain with what I know
A brief explanation of those three status codes in layman's terms.
If caching is enabled in the server
For some files browser is deciding to request from server and for some it's deciding to read from stored (cached) files. Why is this ? Every files has an expiry date, so
If a file is not expired then the browser will use from cache (200 cache).
If file is expired, browser requests server for a file. Server check file in both places (browser and server). If same file found, server refuses the request. As per protocol browser uses existing file.
look at this nginx configuration
location / {
add_header Cache-Control must-revalidate;
expires 60;
etag on;
...
}
Here the expiry is set to 60 seconds, so all static files are cached for 60 seconds. So if u request a file again within 60 seconds browser will read from memory (200 memory). If u request after 60 seconds browser will request server (304).
I assumed that the file is not changed after 60 seconds, in that case you would get 200 (ie, updated file will be fetched from server).
So, if the servers are configured with different expiring and caching headers (policies), the status may differ.
In your case you are using cdn, the main purpose of cdn is high availability and fast delivery. Therefore they use multiple servers. Even though it seems like files are in same directory, cdn might use multiple servers to provide u content, if those servers have different configurations. Then these status can change. Hope it helps.
If working on EJB client library:
You need to mention the argument for getting the initial context.
InitialContext ctx = new InitialContext();
If you do not, it will look in the project folder for properties file. Also you can include the properties credentials or values in your class file itself as follows:
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
props.put(Context.PROVIDER_URL, "jnp://localhost:1099");
InitialContext ctx = new InitialContext(props);
URL_PKG_PREFIXES: Constant that holds the name of the environment property for specifying the list of package prefixes to use when loading in URL context factories.
The EJB client library is the primary library to invoke remote EJB components.
This library can be used through the InitialContext. To invoke EJB components the library creates an EJB client context via a URL context factory. The only necessary configuration is to parse the value org.jboss.ejb.client.naming for the java.naming.factory.url.pkgs property to instantiate an InitialContext.
You may want to check your NPM proxy settings and perhaps remove it.
npm config get proxy
npm config rm proxy
npm config rm https-proxy
One might expect a fresh install of NodeJS+NPM would not have a proxy configured. Strangely enough, mine did come with a proxy defined, pointing to an IP and port 3128. Removing the proxy did the trick.
Make sure the PNGs are fully opaque before creating the video
e.g. with imagemagick, give them a black background:
convert 0.png -background black -flatten +matte 0_opaque.png
From my tests, no bitrate or codec is sufficient to make the video look good if you feed ffmpeg PNGs with transparency
You can access the inactive tags array with (assuming $myArray contains the array)
$myArray['inactiveTags'];
Your question doesn't seem to go beyond accessing the contents of the inactiveTags key so I can only speculate with what your final goal is.
The first key:value pair in the inactiveTags array is
array ('195' => array(
'id' => 195,
'tag' => 'auto')
)
To access the tag value, you would use
$myArray['inactiveTags'][195]['tag']; // auto
If you want to loop through each inactiveTags element, I would suggest:
foreach($myArray['inactiveTags'] as $value) {
print $value['id'];
print $value['tag'];
}
This will print all the id and tag values for each inactiveTag
Edit:: For others to see, here is a var_dump of the array provided in the question since it has not readible
array 'languages' => array 76 => array 'id' => string '76' (length=2) 'tag' => string 'Deutsch' (length=7) 'targets' => array 81 => array 'id' => string '81' (length=2) 'tag' => string 'Deutschland' (length=11) 'tags' => array 7866 => array 'id' => string '7866' (length=4) 'tag' => string 'automobile' (length=10) 17800 => array 'id' => string '17800' (length=5) 'tag' => string 'seat leon' (length=9) 17801 => array 'id' => string '17801' (length=5) 'tag' => string 'seat leon cupra' (length=15) 'inactiveTags' => array 195 => array 'id' => string '195' (length=3) 'tag' => string 'auto' (length=4) 17804 => array 'id' => string '17804' (length=5) 'tag' => string 'coupès' (length=6) 17805 => array 'id' => string '17805' (length=5) 'tag' => string 'fahrdynamik' (length=11) 901 => array 'id' => string '901' (length=3) 'tag' => string 'fahrzeuge' (length=9) 17802 => array 'id' => string '17802' (length=5) 'tag' => string 'günstige neuwagen' (length=17) 1991 => array 'id' => string '1991' (length=4) 'tag' => string 'motorsport' (length=10) 2154 => array 'id' => string '2154' (length=4) 'tag' => string 'neuwagen' (length=8) 10660 => array 'id' => string '10660' (length=5) 'tag' => string 'seat' (length=4) 17803 => array 'id' => string '17803' (length=5) 'tag' => string 'sportliche ausstrahlung' (length=23) 74 => array 'id' => string '74' (length=2) 'tag' => string 'web 2.0' (length=7) 'categories' => array 16082 => array 'id' => string '16082' (length=5) 'tag' => string 'Auto & Motorrad' (length=15) 51 => array 'id' => string '51' (length=2) 'tag' => string 'Blogosphäre' (length=11) 66 => array 'id' => string '66' (length=2) 'tag' => string 'Neues & Trends' (length=14) 68 => array 'id' => string '68' (length=2) 'tag' => string 'Privat' (length=6)
If you are using Debian style virtual host configuration (sites-available/sites-enabled), one way to set a Default VirtualHost is to include the specific configuration file first in httpd.conf or apache.conf (or what ever is your main configuration file).
# To set default VirtualHost, include it before anything else.
IncludeOptional sites-enabled/my.site.com.conf
# Load config files in the "/etc/httpd/conf.d" directory, if any.
IncludeOptional conf.d/*.conf
# Load virtual host config files from "/etc/httpd/sites-enabled/".
IncludeOptional sites-enabled/*.conf
If you just want the old file in your working copy:
svn up -r 147 myfile.py
If you want to rollback, see this "How to return to an older version of our code in subversion?".
UPDATE 9/3/2014
The Microsoft URL above is no longer valid, someone thou took the time to save it to GitHubGist and the link is as follows https://gist.github.com/wadewegner/1677788
There two alternate ways to set accept header, which are as below:
1) setRequestHeader('Accept','application/json; charset=utf-8');
2) $.ajax({
dataType: ($.browser.msie) ? "text" : "json",
accepts: {
text: "application/json"
}
});
From the composer site (it's clear enough)
require#
Lists packages required by this package. The package will not be installed unless those requirements can be met.
require-dev (root-only)#
Lists packages required for developing this package, or running tests, etc. The dev requirements of the root package are installed by default. Both install or update support the --no-dev option that prevents dev dependencies from being installed.
Using require-dev in Composer you can declare the dependencies you need for development/testing the project but don't need in production. When you upload the project to your production server (using git) require-dev
part would be ignored.
Also check this answer posted by the author and this post as well.
It is perfectly fine if you want to go with the display: table-cell
solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;
. flex
is something which has a decent support.
.wrap {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
border: 1px solid #aaa;_x000D_
margin: 10px;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
<span>Align me to the bottom</span>_x000D_
</div>
_x000D_
In the above example, we first set the parent element to display: flex;
and later, we use align-self
to flex-end
. This helps you push the item to the end of the flex
parent.
flex
)If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell;
with vertical-align: bottom;
is enough
div {_x000D_
display: table-cell;_x000D_
vertical-align: bottom;_x000D_
border: 1px solid #f00;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
You're trying to concatenate a string and an integer, which is incorrect.
Change print(numlist.pop(2)+" has been removed")
to any of these:
Explicit int
to str
conversion:
print(str(numlist.pop(2)) + " has been removed")
Use ,
instead of +
:
print(numlist.pop(2), "has been removed")
String formatting:
print("{} has been removed".format(numlist.pop(2)))
Great question... I wish there was an answer, but this is the closest you can get with CSS these days. No ellipsis, but still pretty usable.
overflow: hidden;
line-height: 1.2em;
height: 3.6em; // 3 lines * line-height
Shortest - 18 chars (not confuse +=
(mention by OP) with =
more details here)
test.innerHTML=str
var str = '<p>Just some <span>text</span> here</p>';_x000D_
_x000D_
test.innerHTML=str
_x000D_
<div id="test"></div>
_x000D_
If your activity extends AppCompatActivity
you need to override the onSupportNavigateUp()
method like so:
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
...
}
@Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
@Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
Handle your logic in your onBackPressed()
method and just call that method in onSupportNavigateUp()
so the back button on the phone and the arrow on the toolbar do the same thing.
It's not fading to "black transparent" or "white transparent". It's just showing whatever color is "behind" the image, which is not the image's background color - that color is completely hidden by the image.
If you want to fade to black(ish), you'll need a black container around the image. Something like:
.ctr {
margin: 0;
padding: 0;
background-color: black;
display: inline-block;
}
and
<div class="ctr"><img ... /></div>
When you are using any of the code provided by other users and if you want to display the message on your window and not on the alert
or console.log
, Then make sure you use javascript and not jquery.
Not everyone want to use alert
or console.log
alert('jquery is working');
console.log('jquery is working');
The code below will fail to display the message
Because we are using jquery inside the else
(how the hell the message displays on your screen if you do not have jquery)
if ('undefined' == typeof window.jQuery) {
$('#selector').appendTo('jquery is NOT working');
} else {
$('#selector').appendTo('jquery is working');
}
Use JavaScript instead
if ('undefined' == typeof window.jQuery) {
document.getElementById('selector').innerHTML = "jquery is NOT working";
} else {
document.getElementById('selector').innerHTML = "jquery is working";
}
Perhaps you can use something like Gaussian Mixture Models. Here's a Python package for doing GMMs (just did a Google search) http://www.ar.media.kyoto-u.ac.jp/members/david/softwares/em/
Don't declare the variable in the userform. Declare it as Public
in the module.
Public pass As String
In the Userform
Private Sub CommandButton1_Click()
pass = UserForm1.TextBox1
Unload UserForm1
End Sub
In the Module
Public pass As String
Public Sub Login()
'
'~~> Rest of the code
'
UserForm1.Show
driver.findElementByName("PASSWORD").SendKeys pass
'
'~~> Rest of the code
'
End Sub
You might want to also add an additional check just before calling the driver.find...
line?
If Len(Trim(pass)) <> 0 Then
This will ensure that a blank string is not passed.
No need for a StringBuilder
:
string path = @"c:\hereIAm.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Here");
sw.WriteLine("I");
sw.WriteLine("am.");
}
}
But of course you can use the StringBuilder
to create all lines and write them to the file at once.
sw.Write(stringBuilder.ToString());
StreamWriter.Write
Method (String) (.NET Framework 1.1)
var oldString = "stackoverflow";
var str=oldString.replace(/stackover/g,"NO");
$scope.newString= str;
It works for me. Use an intermediate variable.
Here is what finally worked.
`@echo off
set path=%path%;C:\Program Files\Java\jdk1.7.0_71\bin;
set classpath=C:\Program Files\Java\jdk1.7.0_71\lib;
cd <packageDirectoryName>
javac .\trainingPackage\HelloWorld.java
cd ..
java trainingPackage.HelloWorld
REM (Make sure you are on the parent directory of the PackageName and not inside the Packagedirectory when executing java).`
You may not like it, but personally I find
if (x.HasValue && x.Value)
the most readable. It makes it clear you are working with a nullable type and it makes it clear you are first checking whether the nullable type has a value before acting on it conditionally.
If you take your version and replace the variable with x also it reads:
if (x ?? false)
Is that as clear? Is it obvious x is a nullable type? I'll let you decide.
Well, one of the main ideas behind jQuery is to separate JavaScript from the nasty HTML code. The first method is the way to go.
Using zip function we can get both element and index.
countries = ['Pakistan','India','China','Russia','USA']
for index, element zip(range(0,countries),countries):
print('Index : ',index)
print(' Element : ', element,'\n')
output : Index : 0 Element : Pakistan ...
See also :
struct timeval contains two components, the second and the microsecond. A timestamp with microsecond precision is represented as seconds since the epoch stored in the tv_sec field and the fractional microseconds in tv_usec. Thus you cannot just ignore tv_sec and expect sensible results.
If you use Linux or *BSD, you can use timersub() to subtract two struct timeval values, which might be what you want.
A CustomValidator would also work here:
<asp:CustomValidator runat="server"
ID="valDateRange"
ControlToValidate="txtDatecompleted"
onservervalidate="valDateRange_ServerValidate"
ErrorMessage="enter valid date" />
Code-behind:
protected void valDateRange_ServerValidate(object source, ServerValidateEventArgs args)
{
DateTime minDate = DateTime.Parse("1000/12/28");
DateTime maxDate = DateTime.Parse("9999/12/28");
DateTime dt;
args.IsValid = (DateTime.TryParse(args.Value, out dt)
&& dt <= maxDate
&& dt >= minDate);
}
string result = Encoding.UTF8.GetString((stream as MemoryStream).ToArray());
There is the easy way
HTML:
<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]" />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>
JQUERY:
$("#submit").on("click",function(){
if (($("input[name*='test']:checked").length)<=0) {
alert("You must check at least 1 box");
}
return true;
});
For this you not need any plugin. Enjoy;)
Kendo grid is good as well as Wijmo. I know Kendo comes with Angular bindings for their datasource and I think Wijmo has an Angular plugin. Neither are free though.
exit
is a helper for the interactive shell - sys.exit
is intended for use in programs.
The
site
module (which is imported automatically during startup, except if the-S
command-line option is given) adds several constants to the built-in namespace (e.g.exit
). They are useful for the interactive interpreter shell and should not be used in programs.
Technically, they do mostly the same: raising SystemExit
. sys.exit
does so in sysmodule.c:
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
PyObject *exit_code = 0;
if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
return NULL;
/* Raise SystemExit so callers may catch it or clean up. */
PyErr_SetObject(PyExc_SystemExit, exit_code);
return NULL;
}
While exit
is defined in site.py and _sitebuiltins.py, respectively.
class Quitter(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return 'Use %s() or %s to exit' % (self.name, eof)
def __call__(self, code=None):
# Shells like IDLE catch the SystemExit, but listen when their
# stdin wrapper is closed.
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = Quitter('quit')
__builtin__.exit = Quitter('exit')
Note that there is a third exit option, namely os._exit, which exits without calling cleanup handlers, flushing stdio buffers, etc. (and which should normally only be used in the child process after a fork()
).
Have you tried this?
$("#notification").fadeOut(300, function(){
$(this).remove();
});
That is, using the current this context to target the element in the inner function and not the id. I use this pattern all the time - it should work.
I had this issue until I removed the project in question from the server's deployments (in JBoss Dev Studio, right-click the server and "Remove" the project in the Servers view), then did the following:
After this, just restart the server (in debug or run mode) by selecting the server, NOT the project itself.
This seemed to flush any previous settings/states/memory/whatever that was causing the issue, and I no longer got the error.
Convert the text view to an image, and the scale the image within the boundaries.
Here's an example on how to convert a view to an Image: Converting a view to Bitmap without displaying it in Android?
The problem is, your text will not be selectable, but it should do the trick. I haven't tried it, so I'm not sure how it would look (because of the scaling).
Here is a quite good but old comparison http://wiki.computerwoche.de/doku.php/programmierung/gui-builder_fuer_eclipse Window Builder Pro is now free at Google Web Toolkit
Try running this code, it "just works":
from sklearn import cross_validation, datasets
iris = datasets.load_iris()
X = iris.data[:,:2]
y = iris.target
x_train, x_test, y_train, y_test = cross_validation.train_test_split(X,y,train_size=.8, stratify=y)
y_test
array([0, 0, 0, 0, 2, 2, 1, 0, 1, 2, 2, 0, 0, 1, 0, 1, 1, 2, 1, 2, 0, 2, 2,
1, 2, 1, 1, 0, 2, 1])
The answers here are kind of all over the map, and try to accomplish several different things. I'll just point you to the answer I recently gave that discusses the forced rounding UP -- i.e., no rounding toward zero at all. The answers in here cover different types of rounding, and ana's answer for example is for forced rounding up.
To be clear, the original question was how to "round normally" -- so, "for value > 0.5, round up. And for value < 0.5, round down".
The answer that I link to there discusses forced rounding up, which you sometimes also want to do. Whereas Excel's normal ROUND uses round-half-up, its ROUNDUP uses round-away-from-zero. So here are two functions that imitate ROUNDUP in VBA, the second of which only rounds to a whole number.
Function RoundUpVBA(InputDbl As Double, Digits As Integer) As Double
If InputDbl >= O Then
If InputDbl = Round(InputDbl, Digits) Then RoundUpVBA = InputDbl Else RoundUpVBA = Round(InputDbl + 0.5 / (10 ^ Digits), Digits)
Else
If InputDbl = Round(InputDbl, Digits) Then RoundUpVBA = InputDbl Else RoundUpVBA = Round(InputDbl - 0.5 / (10 ^ Digits), Digits)
End If
End Function
Or:
Function RoundUpToWhole(InputDbl As Double) As Integer
Dim TruncatedDbl As Double
TruncatedDbl = Fix(InputDbl)
If TruncatedDbl <> InputDbl Then
If TruncatedDbl >= 0 Then RoundUpToWhole = TruncatedDbl + 1 Else RoundUpToWhole = TruncatedDbl - 1
Else
RoundUpToWhole = TruncatedDbl
End If
End Function
Some of the answers above cover similar territory, but these here are self-contained. I also discuss in my other answer some one-liner quick-and-dirty ways to round up.
Another possible solution, in case the column has not only strings but numbers too, is to use astype(str).str.lower()
or to_string(na_rep='')
because otherwise, given that a number is not a string, when lowered it will return NaN
, therefore:
import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan,2],columns=['x'])
xSecureLower = df['x'].to_string(na_rep='').lower()
xLower = df['x'].str.lower()
then we have:
>>> xSecureLower
0 one
1 two
2
3 2
Name: x, dtype: object
and not
>>> xLower
0 one
1 two
2 NaN
3 NaN
Name: x, dtype: object
edit:
if you don't want to lose the NaNs, then using map will be better, (from @wojciech-walczak, and @cs95 comment) it will look something like this
xSecureLower = df['x'].map(lambda x: x.lower() if isinstance(x,str) else x)
For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this:
myFnName = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn = getattr(app,myFnName)
For those of you editing the ./.git/config
[remote "external"]
url = ssh://[email protected]:11720/aaa/bbb/ccc
fetch = +refs/heads/*:refs/remotes/external/*
It means that es3.c
does not define a main
function, and you are attempting to create an executable out of it. An executable needs to have an entry point, thereby the linker complains.
To compile only to an object file, use the -c
option:
gcc es3.c -c
gcc es3.o main.c -o es3
The above compiles es3.c
to an object file, then compiles a file main.c
that would contain the main
function, and the linker merges es3.o
and main.o
into an executable called es3
.
perhaps not the most elegant way to solve this
select Activity,
SUM(Amount) as "Total_Amount",
2009 AS INCOME_YEAR
from Activities, Incomes
where Activities.UnitName = ? AND
Incomes.ActivityId = Activities.ActivityID
GROUP BY Activity
ORDER BY Activity;
UNION
select Activity,
SUM(Amount) as "Total_Amount",
2008 AS INCOME_YEAR
from Activities, Incomes2008
where Activities.UnitName = ? AND
Incomes2008.ActivityId = Activities.ActivityID
GROUP BY Activity
ORDER BY Activity;
Try this:- SELECT Case WHEN COLUMNNAME=0 THEN 'sex'
ELSE WHEN COLUMNNAME=1 THEN 'Female' END AS YOURGRIDCOLUMNNAME FROM YOURTABLENAME
in your query for only true or false column
Well, I opened terminal in my Mac and type: "echo $JAVA_HOME" then I got the directory, went there and found src.zip
I know this is old and there are so many answers, some are really convoluted, can be quick and inline:
<asp:Button runat="server" ID="btnUserDelete" Text="Delete" CssClass="GreenLightButton" OnClick="BtnUserDelete_Click" OnClientClick="return confirm('Are you sure you want to delete this user?');" meta:resourcekey="BtnUserDeleteResource1" />
To my knowledge, there is sadly no CSS filter to colorise an element (perhaps with the use of some SVG filter magic, but I'm somewhat unfamiliar with that) and even if that wasn't the case, filters are basically only supported by webkit browsers.
With that said, you could still work around this and use a canvas
to modify your image. Basically, you can draw an image element onto a canvas and then loop through the pixels, modifying the respective RGBA values to the colour you want.
However, canvases do come with some restrictions. Most importantly, you have to make sure that the image src comes from the same domain as the page. Otherwise the browser won't allow you to read or modify the pixel data of the canvas.
Here's a JSFiddle changing the colour of the JSFiddle logo.
//Base64 source, but any local source will work_x000D_
var src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAgCAYAAACGhPFEAAAABGdBTUEAALGPC/xhBQAABzhJREFUWAnNWAtwXFUZ/v9zs4GUJJu+k7tb5DFAGWO1aal1sJUiY3FQQaWidqgPLAMqYzd9CB073VodhCa7KziiFgWhzvAYQCiCD5yK4gOTDnZK2ymdZoruppu0afbu0pBs7p7f7yy96W662aw2QO/Mzj2P//Gd/5z/+89dprfzubnTN332Re+xiKawllxWucm+9O4eCi9xT8ctn45yKd3AXX1BPsu3XIiuY+K5kDmrUA7jORb5m2baLm7uscNrJr9eOF9Je8JAz9ySnFHlq9nEpG6CYx+RdJDQDtKymxT1iWZLFDUy0/kkfDUxzYVzV0hvHZLs946Gph+uBLCRmRDQdjTVwmw9DZCNMPi4KzqWbPX/sxwIu71vlrKq10HnZizwTSFZngj5f1NOx5s7bdB2LHWDEusBOD487LrX9qyd8qpnvJL3zGjqAh+pR4W4RVhu715Vv2U8PTWeQLn5YHvms4qsR4TpH/ImLfhfARvbPaGGrrjTtwjH5hFFfHcgkv5SOZ9mbvxIgwGaZl+8ULGcJ8zOsJa9R1r9B2d8v2eGb1KNieqBhLNz8ekyAoV3VAX985+FvSXEenF8lf9lA7DUUxa0HUl/RTG1EfOUQmUwwCtggDewiHmc1R+Ir/MfKJz/f9tTwn31Nf7qVxlHLR6qXwg7cHXqU/p4hPdUB6Lp55TiXwDYTsrpG12dbdY5t0WLrCSRSVjIItG0dqIAG2jHwlPTmvQdsL3Ajjg3nAq3zIgdS98ZiGV0MJZeWVJs2WNWIJK5hcLh0osuqVTxIAdi6X3w/0LFGoa+AtFMzo5kflix0gQLBiLOZmAYro84RcfSc3NKpFAcliM9eYDdjZ7QO/1mRc+CTapqFX+4lO9TQEPoUpz//anQ5FQphXdizB1QXXk/moOl/JUC7aLMDpQSHj02PdxbG9xybM60u47UjZ4bq290Zm451ky3HSi6kxTKJ9fXHQVvZJm1XTjutYsozw53T1L+2ufBGPMTe/c30M/mD3uChW+c+6tQttthuBnbqMBLKGbydI54/eFQ3b5CWa/dGMl8xFJ0D/rvg1Pjdxil+2XK5b6ZWD15lyfnvYOxTBYs9TrY5NbuUENRUo5EGtGyVUNtBwBfDjA/IDtTkiNRsdYD8O+NcVN2KUfXo3UnukvA6Z3I+mWeY++NpNoAwDvAv1Uiss7oiNBmYD+XraoO0NvnPVnvrbUsA4CcYusPgajzY2/cvN+KtOFl/6w/IWrvdTV/Ktla92KhkNcOxpwPCqm/IgLbEvteW1m4E2/d8iY9AZOXQ/7WxKq6nxq9YNT5OLF6DmAfTHT13EL3XjTk2csXk4bqX2OXWiQ73Jz49tS4N5d/oxoHLr14EzPfAf1IIlS/2oznIx1omLURhL5Qa1oxFuC8EeHb8U6I88bXCwGbuZ61jb2Jgz1XYUHb0b0vEHNWmHE9lNsjWrcmnMhNhYDNnCkmNJSFHFdzte82M1b04HgC6HrYbAPw1pFdNOc4GE334wz9qkihRAdK/0HBub/E1MkhJBiq6V8gq7Htm05OjN2C/z/jCP1xbAlCwcnsAsbdkGHF/trPIcoNrtbjFRNmoama6EgZ42SimRG5FjLHWakNwWjmirLyZpLpKH7TysghZ00OUHNTxFmK2yDNQSKlx7u0Q0GQeLtQdy4rY5zMzqVb/ccoJ/OQMEmoPWW3988to4NY8DxYf6WMDCW6ktuRvFqxmqewgguhdLCcwsic0DMA8lE7kvrYyFhBw446X2B/nRNo739/YnX9azKUXYCg9CtlvdAUyywuEB1p4gh9AzbPZc0mF8Z+sINgn0MIwiVgKcAG6rGlT86AMdqw2n8ppR63o+mveQXCFAxzX2BWD0P6pcT+g3uNlmEDV3JX4iOh1xICdWU2gGXOMXN5HfRhK4IoPxlfXQfmKf+Ajh1I+MEeHMcKzqvoxoZsHsoOXgP+fEkxbw1e2JhB0h2q9tc4OL/fAVdsdd3jnyhklmRo8qGBQXchIvMMKPW7Pt85/SM66CNmDw1mh75cHu6JWZFZxNLNSJTPIM5PuJquKEt3o6zmqyJZH4LTC7CIfTonO5Jr/B2jxIq6jW3OZVYVX4edDSD6e1BAXqwgl/I2miKp+ZayOkT0CjaJww21/2bhznio7uoiL2dQB8HdhoV++ri4AdUdtgfw789mRHspzulXzyCcI1BMVQXgL5LodnP7zFfE+N9/9yOUyedxTn/SFHWWj0ifAY1ANHUleOJRlPqdCUmbO85J1jjxUfkUkgVCsg1/uGw0n/fvFm67LT2NLTLfi98Cke8dpMGl3r9QxVRnPuPrWzaIUmsAtgas0okd6ETh7AYt5d7+BeCbhfKVcQ6CtwgJjjoiP3fdgVbcbY57/otBnxidfndvo6/67BtxUf4kztJsbMg0CJaU9QxN2FskhePQBWr7La6wvzRFarTtyoBgB4hm5M//aAMT2+/Vlfzp81/vywLMWSBN1QAAAABJRU5ErkJggg==";_x000D_
var canvas = document.getElementById("theCanvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image;_x000D_
_x000D_
//wait for the image to load_x000D_
img.onload = function() {_x000D_
//Draw the original image so that you can fetch the colour data_x000D_
ctx.drawImage(img,0,0);_x000D_
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);_x000D_
_x000D_
/*_x000D_
imgData.data is a one-dimensional array which contains _x000D_
the respective RGBA values for every pixel _x000D_
in the selected region of the context _x000D_
(note i+=4 in the loop)_x000D_
*/_x000D_
_x000D_
for (var i = 0; i < imgData.data.length; i+=4) {_x000D_
imgData.data[i] = 255; //Red, 0-255_x000D_
imgData.data[i+1] = 255; //Green, 0-255_x000D_
imgData.data[i+2] = 255; //Blue, 0-255_x000D_
/* _x000D_
imgData.data[i+3] contains the alpha value_x000D_
which we are going to ignore and leave_x000D_
alone with its original value_x000D_
*/_x000D_
}_x000D_
ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the original image_x000D_
ctx.putImageData(imgData, 0, 0); //paint the new colorised image_x000D_
}_x000D_
_x000D_
//Load the image!_x000D_
img.src = src;
_x000D_
body {_x000D_
background: green;_x000D_
}
_x000D_
<canvas id="theCanvas"></canvas>
_x000D_
This is how I did it, I hope it brings a new perspective how this works on Swift.
In this example below I will get the any string between []
var sample = "this is an [hello] amazing [world]"
var regex = NSRegularExpression(pattern: "\\[.+?\\]"
, options: NSRegularExpressionOptions.CaseInsensitive
, error: nil)
var matches = regex?.matchesInString(sample, options: nil
, range: NSMakeRange(0, countElements(sample))) as Array<NSTextCheckingResult>
for match in matches {
let r = (sample as NSString).substringWithRange(match.range)//cast to NSString is required to match range format.
println("found= \(r)")
}
I didn't see an answer that's clean and suitable for production-ready software, so here it goes:
/*
* Get current error_reporting value,
* so that we don't lose preferences set in php.ini and .htaccess
* and accidently reenable message types disabled in those.
*
* If you want to disable e.g. E_STRICT on a global level,
* use php.ini (or .htaccess for folder-level)
*/
$old_error_reporting = error_reporting();
/*
* Disable E_STRICT on top of current error_reporting.
*
* Note: do NOT use ^ for disabling error message types,
* as ^ will re-ENABLE the message type if it happens to be disabled already!
*/
error_reporting($old_error_reporting & ~E_STRICT);
// code that should not emit E_STRICT messages goes here
/*
* Optional, depending on if/what code comes after.
* Restore old settings.
*/
error_reporting($old_error_reporting);
Similarly to Jakob's answer, you can use HTML tags. Just a note that the color
attribute of font
(<font color=...>
) is deprecated in HTML5. The following syntax would be HTML5-compliant:
This <span style="color:red">word</span> is not black.
Same caution that Jakob made probably still applies:
Be aware that this will not survive a conversion of the notebook to latex.
The solution by Daniel Fanjul looked promissing. I was able to find that blob file and extracted it ("git fsck --full --no-dangling", "git cat-file -t {hash}", "git show {hash} > file.tmp") but when I tried to update pack file with "git hash-object -w file.tmp", it displayed correct hash BUT the error remained.
So I decided to try different approach. I could simply delete local repository and download everything from remote but some branches in local repository were 8 commits ahead and I did not want to lose those changes. Since that tiny, 6kb mp3 file, I decided to delete it completely. I tried many ways but the best was from here: https://itextpdf.com/en/blog/technical-notes/how-completely-remove-file-git-repository
I got the file name by running this command "git rev-list --objects --all | grep {hash}". Then I did a backup (strongly recommend to do so because I failed 3 times) and then run the command:
"java -jar bfg.jar --delete-files {filename} --no-blob-protection ."
You can get bfg.jar file from here https://rtyley.github.io/bfg-repo-cleaner/ so according to documentation I should run this command next:
"git reflog expire --expire=now --all && git gc --prune=now --aggressive"
When I did so, I got errors on last step. So I recovered everything from backup and this time, after removing file, I checkout to the branch (which was causing that error), then check out back to main and only after run the command one after each other:
"git reflog expire --expire=now --all" "git gc --prune=now --aggressive"
Then I added my file back to its location and comit. However, since many local commits were changed, I was not able to push anything to server. So I backup everything on server (in case I screw it), check out to the branch which was affected and run the command "git push --force".
What I understood from this case? GIT is great but so senstive... I should have an option to simply disregard one f... 6kb file I know what I am doing. I have no clude why "git hash-object -w" did not work either =( Lessons learnt, push all commits, do not wait, do backup of repository time to time. Also I know how to remove files from repository, if I ever need =)
I hope this saves someone's time
You need to set the password for root@localhost
to be blank. There are two ways:
The MySQL SET PASSWORD
command:
SET PASSWORD FOR root@localhost=PASSWORD('');
Using the command-line mysqladmin
tool:
mysqladmin -u root -pCURRENTPASSWORD password ''
I just use:
$('body').animate({ 'scrollTop': '-=-'+<yourValueScroll>+'px' }, 2000);
_x000D_
Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup)
.
So, for example, I have:
private string DoSomethingToMyString(string input)
{
// blah
}
Instead of explicitly stating the variable to be used like this:
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
}
I can just omit the name of the var:
public List<string> GetStringStuff()
{
return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
}
Are the users able to convert the apk file of my application back to the actual code?
yes.
People can use various tools to:
FDex2
to dump out dex
file
dex2jar
to convert to jar
jadx
to conver to java
source codeIf they do - is there any way to prevent this?
yes. Several (can combined) ways to prevent (certain degree) this:
ProGuard
More details can refer my Chinese tutorial: ??????????
try this
.switch {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
width: 60px;_x000D_
height: 34px;_x000D_
}_x000D_
_x000D_
.switch input {display:none;}_x000D_
_x000D_
.slider {_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
top: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
bottom: 0;_x000D_
background-color: #ccc;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
.slider:before {_x000D_
position: absolute;_x000D_
content: "";_x000D_
height: 26px;_x000D_
width: 26px;_x000D_
left: 4px;_x000D_
bottom: 4px;_x000D_
background-color: white;_x000D_
-webkit-transition: .4s;_x000D_
transition: .4s;_x000D_
}_x000D_
_x000D_
input:checked + .slider {_x000D_
background-color: #2196F3;_x000D_
}_x000D_
_x000D_
input:focus + .slider {_x000D_
box-shadow: 0 0 1px #2196F3;_x000D_
}_x000D_
_x000D_
input:checked + .slider:before {_x000D_
-webkit-transform: translateX(26px);_x000D_
-ms-transform: translateX(26px);_x000D_
transform: translateX(26px);_x000D_
}_x000D_
_x000D_
/* Rounded sliders */_x000D_
.slider.round {_x000D_
border-radius: 34px;_x000D_
}_x000D_
_x000D_
.slider.round:before {_x000D_
border-radius: 50%;_x000D_
}
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<h2>Toggle Switch</h2>_x000D_
_x000D_
<label class="switch">_x000D_
<input type="checkbox">_x000D_
<div class="slider"></div>_x000D_
</label>_x000D_
_x000D_
<label class="switch">_x000D_
<input type="checkbox" checked>_x000D_
<div class="slider"></div>_x000D_
</label><br><br>_x000D_
_x000D_
<label class="switch">_x000D_
<input type="checkbox">_x000D_
<div class="slider round"></div>_x000D_
</label>_x000D_
_x000D_
<label class="switch">_x000D_
<input type="checkbox" checked>_x000D_
<div class="slider round"></div>_x000D_
</label>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
For Converting a List into Pandas Core Data Frame, we need to use DataFrame Method from pandas Package.
There are Different Ways to Perform the Above Operation.
import pandas as pd
Data = pd.DataFrame(Column_Data)
Data.columns = ['Column_Name']
So, for the above mentioned issue, the code snippet is
import pandas as pd
Content = ['Thanks You',
'Its fine no problem',
'Are you sure']
Data = pd.DataFrame({'Text': Content})
I know this question is a little old, but it still comes up first in a lot of Google searches. I wanted to add in a solution that doesn't involve editing the style sheet (in my case, I didn't have access):
<ol type="A">_x000D_
<li style="font-weight: bold;">_x000D_
<p><span style="font-weight: normal;">Text</span></p>_x000D_
</li>_x000D_
<li style="font-weight: bold;">_x000D_
<p><span style="font-weight: normal;">More text</span></p>_x000D_
</li>_x000D_
</ol>
_x000D_
Java doesn't pass objects, it passes references (pointers) to objects. So yes, l2 and l1 are two pointers to the same object.
You have to make an explicit copy if you need two different list with the same contents.
On MaxOSX there may be perlcc. Type man perlcc. On my system (10.6.8) it's in /usr/bin. YMMV
See http://search.cpan.org/~nwclark/perl-5.8.9/utils/perlcc.PL
I had the same problem, and it turned out I hadn't installed the library.
this link was super usefull.
The biggest issue being missed by most solutions here is that an element's width is often changed by CSS based on where it is scoped in html.
If I was to determine offsetWidth of an element by appending a clone of it to body when it has styles that only apply in its current scope I would get the wrong width.
for example:
//css
.module-container .my-elem{ border: 60px solid black; }
now when I try to determine my-elem's width in context of body it will be out by 120px. You could clone the module container instead, but your JS shouldn't have to know these details.
I haven't tested it but essentially Soul_Master's solution appears to be the only one that could work properly. But unfortunately looking at the implementation it will likely be costly to use and bad for performance (as most of the solutions presented here are as well.)
If at all possible then use visibility: hidden instead. This will still render the element, allowing you to calculate width without all the fuss.
node-sass
node module uses darwin
binary file which is dependent on the version of node. This issue occurs when the binary file is not downloaded or wrong binary file is downloaded.
Reinstall node modules will download expected binary of node-sass:-
For Mac users:
rm -rf node_modules
npm cache clean --force
npm i
npm rebuild node-sass --force
For Windows users:
rmdir node_modules
npm cache clean --force
npm i
npm rebuild node-sass --force
but for some users, you need to check your node version's compatibility with node-sass version. Make it compatible using below table and run above commands again to fix this issue.
If issue is still not fixed, check node-sass supported environment's list:- https://github.com/sass/node-sass/releases/
Make a list of tuples with your data and then create a DataFrame with it:
d = []
for p in game.players.passing():
d.append((p, p.team, p.passer_rating()))
pd.DataFrame(d, columns=('Player', 'Team', 'Passer Rating'))
A list of tuples should have less overhead than a list dictionaries. I tested this below, but please remember to prioritize ease of code understanding over performance in most cases.
Testing functions:
def with_tuples(loop_size=1e5):
res = []
for x in range(int(loop_size)):
res.append((x-1, x, x+1))
return pd.DataFrame(res, columns=("a", "b", "c"))
def with_dict(loop_size=1e5):
res = []
for x in range(int(loop_size)):
res.append({"a":x-1, "b":x, "c":x+1})
return pd.DataFrame(res)
Results:
%timeit -n 10 with_tuples()
# 10 loops, best of 3: 55.2 ms per loop
%timeit -n 10 with_dict()
# 10 loops, best of 3: 130 ms per loop
What you have to do is to set the MinimumHeight property of the row. Not only the Height property. That's the key. Put the code bellow in the CellPainting event of the datagridview
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
foreach(DataGridViewRow x in dataGridView1.Rows)
{
x.MinimumHeight = 50;
}
}
To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this
points to vue component):
setQuery(query){
let obj = Object.assign({}, this.$route.query);
Object.keys(query).forEach(key => {
let value = query[key];
if(value){
obj[key] = value
} else {
delete obj[key]
}
})
this.$router.replace({
...this.$router.currentRoute,
query: obj
})
},
removeQuery(queryNameArray){
let obj = {}
queryNameArray.forEach(key => {
obj[key] = null
})
this.setQuery(obj)
},
To loop through JSON Object : In Angluar's (6.0.0+), now they provide the pipe keyvalue
:
<div *ngFor="let item of object| keyvalue">
{{ item.key }} - {{ item.value }}
</div>
To just display JSON
{{ object | json }}
let MAX : UInt32 = 9
let MIN : UInt32 = 1
func randomNumber()
{
var random_number = Int(arc4random_uniform(MAX) + MIN)
print ("random = ", random_number);
}
Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR
set these variables:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
export PATH=$JAVA_HOME/bin:$PATH
Run your app and fun :)
(Minor update: put variable value in quote)
If you simply want some output, you want to use $(info)
by itself. You can do that anywhere in a Makefile, and it will show when that line is evaluated:
$(info VAR="$(VAR)")
Will output VAR="<value of VAR>"
whenever make processes that line. This behavior is very position dependent, so you must make sure that the $(info)
expansion happens AFTER everything that could modify $(VAR)
has already happened!
A more generic option is to create a special rule for printing the value of a variable. Generally speaking, rules are executed after variables are assigned, so this will show you the value that is actually being used. (Though, it is possible for a rule to change a variable.) Good formatting will help clarify what a variable is set to, and the $(flavor)
function will tell you what kind of a variable something is. So in this rule:
print-% : ; $(info $* is a $(flavor $*) variable set to [$($*)]) @true
$*
expands to the stem that the %
pattern matched in the rule.$($*)
expands to the value of the variable whose name is given by by $*
.[
and ]
clearly delineate the variable expansion.
You could also use "
and "
or similar.$(flavor $*)
tells you what kind of variable it is. NOTE: $(flavor)
takes a variable name, and not its expansion.
So if you say make print-LDFLAGS
, you get $(flavor LDFLAGS)
,
which is what you want.$(info text)
provides output.
Make prints text
on its stdout as a side-effect of the expansion.
The expansion of $(info)
though is empty.
You can think of it like @echo
,
but importantly it doesn't use the shell,
so you don't have to worry about shell quoting rules.@true
is there just to provide a command for the rule.
Without that,
make will also output print-blah is up to date
. I feel @true
makes it more clear that it's meant to be a no-op.Running it, you get
$ make print-LDFLAGS
LDFLAGS is a recursive variable set to [-L/Users/...]
I find this alternative more convenient:
Profile
Zombies
As soon as a zombie is detected you then get a neat "Zombie Stack" that shows you when the object in question was allocated and where it was retained or released:
Event Type RefCt Responsible Caller
Malloc 1 -[MyViewController loadData:]
Retain 2 -[MyDataManager initWithBaseURL:]
Release 1 -[MyDataManager initWithBaseURL:]
Release 0 -[MyViewController loadData:]
Zombie -1 -[MyService prepareURLReuqest]
Advantages compared to using the diagnostic tab of the Xcode Schemes:
If you forget to uncheck the option in the diagnostic tab there no objects will be released from memory.
You get a more detailed stack that shows you in what methods your corrupt object was allocated / released or retained.
Use mysqli_fetch_row()
. Try this,
$query = "SELECT ssfullname, ssemail FROM userss WHERE user_id = ".$user_id;
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_row($result);
$ssfullname = $row['ssfullname'];
$ssemail = $row['ssemail'];
For me, I had encountered this error when invoking a webservice call, make sure that the site has a valid ssl, i.e the logo on the side of the url is checked, otherwise need to add the certificate to trusted key store in your machine
While most of the techniques stated here are correct, bash 4.2 supports an actual test for the presence of a variable (man bash), rather than testing the value of the variable.
[[ -v foo ]]; echo $?
# 1
foo=bar
[[ -v foo ]]; echo $?
# 0
foo=""
[[ -v foo ]]; echo $?
# 0
Notably, this approach will not cause an error when used to check for an unset variable in set -u
/ set -o nounset
mode, unlike many other approaches, such as using [ -z
.
Add the -v
option to your grep
command to invert the results.
1)
total = 0;
for i=1:size(A,1)
for j=1:size(A,2)
total = total + A(i,j);
end
end
2)
total = sum(A(:));
As the OP references Number of commits on branch in git I want to add that the given answers there also work with any other branch, at least since git version 2.17.1 (and seemingly more reliably than the answer by Peter van der Does):
working correctly:
git checkout current-development-branch
git rev-list --no-merges --count master..
62
git checkout -b testbranch_2
git rev-list --no-merges --count current-development-branch..
0
The last command gives zero commits as expected since I just created the branch. The command before gives me the real number of commits on my development-branch minus the merge-commit(s)
not working correctly:
git checkout current-development-branch
git rev-list --no-merges --count HEAD
361
git checkout -b testbranch_1
git rev-list --no-merges --count HEAD
361
In both cases I get the number of all commits in the development branch and master from which the branches (indirectly) descend.
OK, what you can try is
Cntrl+H (Find and Replace), leave Find What blank and change Replace With to NULL.
That should replace all blank cells in the USED range with NULL
As an addition and observation to the other useful answers, it's worth noticing that actually doing [:10]
as slicing will return the first 10 elements of the list, not the last 10...
To get the last 10 you should do [-10:]
instead (see here). This will help you avoid using order_by('-id')
with the -
to reverse the elements.
I have an answer for you Yes, It is possible.
Go to
SQL Server Management Studio > select Database > click on attach
Then select and add .mdf and .ldf file. Click on OK.
This might work for you
public void save(String fileName) throws FileNotFoundException {
FileOutputStream fout= new FileOutputStream (fileName);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(clubs);
fout.close();
}
To read back you can have
public void read(String fileName) throws FileNotFoundException {
FileInputStream fin= new FileInputStream (fileName);
ObjectInputStream ois = new ObjectInputStream(fin);
clubs= (ArrayList<Clubs>)ois.readObject();
fin.close();
}
HTML
<input type="button">
CSS
input[type=button]{
background:transparent;
border:0;
}
What about
import operator
auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))
In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by
order_by(*fields)
By default, results returned by a QuerySet
are ordered by the ordering tuple given by the ordering
option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by
method.
Example:
ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]
The result above will be ordered by score
descending, then by last_name
ascending. The negative sign in front of "-score"
indicates descending order. Ascending order is implied.
You should really use a set based solution involving two queries (basic insert):
INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT id, column1, column2 FROM TableA
UPDATE TableA SET column1 = column2 * column3
And for your transform:
INSERT INTO TableB (Id2Column, Column33, Column44)
SELECT
id,
column1 * column4 * 100,
(column2 / column12)
FROM TableA
UPDATE TableA SET column1 = column2 * column3
Now if your transform is more complicated than that and involved multiple tables, post another question with the details.
While you can set the locale exporting an env variable, you will have to do that every time you start a session. Setting a locale this way will solve the problem permanently:
sudo apt-get install locales
sudo locale-gen en_US.UTF-8
sudo echo "LANG=en_US.UTF-8" > /etc/default/locale
Here, if you want to control it through HTML: do like below Option 1:
<meta http-equiv="expires" content="Sun, 01 Jan 2014 00:00:00 GMT"/>
<meta http-equiv="pragma" content="no-cache" />
And if you want to control it through PHP: do it like below Option 2:
header('Expires: Sun, 01 Jan 2014 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
AND Option 2 IS ALWAYS BETTER in order to avoid proxy based caching issue.
http://handbrake.fr is a nice high level tool with a lot of useful presets for mp4 for iPod, PS3, ... with both GUI and CLI interfaces for Linux, Windows and Mac OS X.
It comes with its own dependencies as a single statically linked fat binary so you have all the x264 / aac codecs included.
$ HandBrakeCLI -Z Universal -i myinputfile.mov -o myoutputfile.mp4
To list all the available presets:
$ HandBrakeCLI -z
With a wider view of what you're actually trying to do and the context in which you're doing it, I'm sure we could give you a better answer than the literal answer to your question.
But here's a literal answer:
If you're assigning these functions to some property somewhere, you can wrap the original function and put your replacement on the property instead:
// Original code in main.js
var theProperty = init;
function init(){
doSomething();
}
// Extending it by replacing and wrapping, in extended.js
theProperty = (function(old) {
function extendsInit() {
old();
doSomething();
}
return extendsInit;
})(theProperty);
If your functions aren't already on an object, you'd probably want to put them there to facilitate the above. For instance:
// In main.js
var MyLibrary = {
init: function init() {
}
};
// In extended.js
(function() {
var oldInit = MyLibrary.init;
MyLibrary.init = extendedInit;
function extendedInit() {
oldInit.call(MyLibrary); // Use #call in case `init` uses `this`
doSomething();
}
})();
But there are better ways to do that. Like for instance, providing a means of registering init
functions.
// In main.js
var MyLibrary = (function() {
var initFunctions = [];
return {
init: function init() {
var fns = initFunctions;
initFunctions = undefined;
for (var index = 0; index < fns.length; ++index) {
try { fns[index](); } catch (e) { }
}
},
addInitFunction: function addInitFunction(fn) {
if (initFunctions) {
// Init hasn't run yet, remember it
initFunctions.push(fn);
} else {
// `init` has already run, call it almost immediately
// but *asynchronously* (so the caller never sees the
// call synchronously)
setTimeout(fn, 0);
}
}
};
})();
Here in 2020 (or really any time after ~2016), that can be written a bit more compactly:
// In main.js
const MyLibrary = (() => {
let initFunctions = [];
return {
init() {
const fns = initFunctions;
initFunctions = undefined;
for (const fn of fns) {
try { fn(); } catch (e) { }
}
},
addInitFunction(fn) {
if (initFunctions) {
// Init hasn't run yet, remember it
initFunctions.push(fn);
} else {
// `init` has already run, call it almost immediately
// but *asynchronously* (so the caller never sees the
// call synchronously)
setTimeout(fn, 0);
// Or: `Promise.resolve().then(() => fn());`
// (Not `.then(fn)` just to avoid passing it an argument)
}
}
};
})();
In the early days...like before the 90s...the processors weren't able to do multi tasks that efficiently...coz a single processor could handle just a single task...so when we used to say that my antivirus,microsoft word,vlc,etc. softwares are all running at the same time...that isn't actually true. When I said a processor could handle a single process at a time...I meant it. It actually would process a single task...then it used to pause that task...take another task...complete it if its a short one or again pause it and add it to the queue...then the next. But this 'pause' that I mentioned was so small (appx. 1ns) that you didn't understand that the task has been paused. Eg. On vlc while listening to music there are other apps running simultaneously but as I told you...one program at a time...so the vlc is actually pausing in between for ns so you dont underatand it but the music is actually stopping in between.
But this was about the old processors...
Now-a- days processors ie 3rd gen pcs have multi cored processors. Now the 'cores' can be compared to a 1st or 2nd gen processors itself...embedded onto a single chip, a single processor. So now we understood what are cores ie they are mini processors which combine to become a processor. And each core can handle a single process at a time or multi threads as designed for the OS. And they folloq the same steps as I mentioned above about the single processor.
Eg. A i7 6gen processor has 8 cores...ie 8 mini processors in 1 i7...ie its speed is 8x times the old processors. And this is how multi tasking can be done.
There could be hundreds of cores in a single processor Eg. Intel i128.
I hope I explaned this well.
This question already has a great answer, but I ran into the same error, in a different scenario: displaying a List
in an EditorTemplate.
I have a model like this:
public class Foo
{
public string FooName { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string BarName { get; set; }
}
And this is my main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.EditorFor(m => m.Bars)
And this is my Bar EditorTemplate (Bar.cshtml)
@model List<Bar>
<div class="some-style">
@foreach (var item in Model)
{
<label>@item.BarName</label>
}
</div>
And I got this error:
The model item passed into the dictionary is of type 'Bar', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Bar]
The reason for this error is that EditorFor
already iterates the List
for you, so if you pass a collection to it, it would display the editor template once for each item in the collection.
This is how I fixed this problem:
Brought the styles outside of the editor template, and into the main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
<div class="some-style">
@Html.EditorFor(m => m.Bars)
</div>
And changed the EditorTemplate (Bar.cshtml) to this:
@model Bar
<label>@Model.BarName</label>
The above answers are applicable to most situations, but if you are in a docker container environment and your container is limited by CpusetCpus
, then you can't actually get the real cpu cores through the above method.
In this case, you need do this to get the real cpu cores:
cat /proc/stat | grep cpu | grep -E 'cpu[0-9]+' | wc -l
If Facing the same issue as mine i.e. not on the virtual environment and wants requirements.txt for a specific project or from the selected folder(includes children) and pipreqs is not supporting.
You can use :
import os
import sys
from fuzzywuzzy import fuzz
import subprocess
path = "C:/Users/Username/Desktop/DjangoProjects/restAPItest"
files = os.listdir(path)
pyfiles = []
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.py'):
pyfiles.append(os.path.join(root, file))
stopWords = ['from', 'import',',','.']
importables = []
for file in pyfiles:
with open(file) as f:
content = f.readlines()
for line in content:
if "import" in line:
for sw in stopWords:
line = ' '.join(line.split(sw))
importables.append(line.strip().split(' ')[0])
importables = set(importables)
subprocess.call(f"pip freeze > {path}/requirements.txt", shell=True)
with open(path+'/requirements.txt') as req:
modules = req.readlines()
modules = {m.split('=')[0].lower() : m for m in modules}
notList = [''.join(i.split('_')) for i in sys.builtin_module_names]+['os']
new_requirements = []
for req_module in importables:
try :
new_requirements.append(modules[req_module])
except KeyError:
for k,v in modules.items():
if len(req_module)>1 and req_module not in notList:
if fuzz.partial_ratio(req_module,k) > 90:
new_requirements.append(modules[k])
new_requirements = [i for i in set(new_requirements)]
new_requirements
with open(path+'/requirements.txt','w') as req:
req.write(''.join(new_requirements))
P.S: It may have a few additional libraries as it checks on fuzzylogic.
ioctl(<socketfd>, SIOCGIFCONF, (struct ifconf)&buffer);
Read /usr/include/linux/if.h
for information on the ifconf
and ifreq
structures. This should give you the IP address of each interface on the system. Also read /usr/include/linux/sockios.h
for additional ioctls.
A better idea,
if you want to put the error message just beneath the text field, you can do like this
.row.spacer20top
.col-sm-6.form-group
= f.label :first_name, "*Your First Name:"
= f.text_field :first_name, :required => true, class: "form-control"
= f.error_message_for(:first_name)
What is error_message_for
?
--> Well, this is a beautiful hack to do some cool stuff
# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
def error_message_for(field_name)
if self.object.errors[field_name].present?
model_name = self.object.class.name.downcase
id_of_element = "error_#{model_name}_#{field_name}"
target_elem_id = "#{model_name}_#{field_name}"
class_name = 'signup-error alert alert-danger'
error_declaration_class = 'has-signup-error'
"<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
"#{self.object.errors[field_name].join(', ')}"\
"</div>"\
"<!-- Later JavaScript to add class to the parent element -->"\
"<script>"\
"document.onreadystatechange = function(){"\
"$('##{id_of_element}').parent()"\
".addClass('#{error_declaration_class}');"\
"}"\
"</script>".html_safe
end
rescue
nil
end
end
Markup Generated after error
<div id="error_user_email" for="user_email" class="signup-error alert alert-danger">has already been taken</div>
<script>document.onreadystatechange = function(){$('#error_user_email').parent().addClass('has-signup-error');}</script>
Corresponding SCSS
.has-signup-error{
.signup-error{
background: transparent;
color: $brand-danger;
border: none;
}
input, select{
background-color: $bg-danger;
border-color: $brand-danger;
color: $gray-base;
font-weight: 500;
}
&.checkbox{
label{
&:before{
background-color: $bg-danger;
border-color: $brand-danger;
}
}
}
Note: Bootstrap variables used here
You can try to use the following code instead:
$pro= model_name::where('col_name', '=', 'value')->get();
For me, it was @Lucky's answer, and specifically, the line
AutowiredFakaSource fakeDataSource = ctx.getBean(AutowiredFakaSource.class);
that fixed my problem. I have an ApplicationContext-based app running from the command-line, and judging by a number of the comments on SO, Spring wires up these differently to MVC-based apps.
I have tried to use the above robot there is a need to add a delay :( also you cannot debug or do something else because you lose the focus :(
//open upload window upload.click();
//put path to your image in a clipboard
StringSelection ss = new StringSelection(file.getAbsoluteFile());
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
//imitate mouse events like ENTER, CTRL+C, CTRL+V
Robot robot = new Robot();
robot.delay(250);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(50);
robot.keyRelease(KeyEvent.VK_ENTER);
With explode function of php
$array=explode(" ",$str);
This is a quick example for you http://codepad.org/Pbg4n76i
Actually, I found a somewhat quirky way to do this. Add the protocol to your web.config, but inside a location element. Specify the webservice location as the path attribute, like so:
<location path="YourWebservice.asmx">
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</location>
If any of your markn
columns are "AllowNull" then you will need to do a little extra to insure the correct result is returned, this is because 1 NULL value will result in a NULL total.
This is what i would consider to be the correct answer.
SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks`
IFNULL will return the 2nd parameter if the 1st is NULL. COALESCE could be used but i prefer to only use it if it is required. See What is the difference bewteen ifnull and coalesce in mysql?
SUM-ing the entire calculation is tidier than SUM-ing each column individually.
SELECT `student`, SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks`
FROM student_scorecard
GROUP BY `student`
If you log the
var options = {
key: fs.readFileSync('./key.pem', 'utf8'),
cert: fs.readFileSync('./csr.pem', 'utf8')
};
You might notice there are invalid characters due to improper encoding.
If your label is in table, padding may cause it to expand. To avoid this you may use margin:
div label {
display: block;
text-align: left;
margin-bottom: -0.2%;
}
I know this is an old questions but none of the solutions seemed like a good practice hence I am putting how I have solved this issue:
Tried solving this issue by using Homebrew but it was also installing node in /usr/local directory
which would again cause EACCES
error.
Had to use a version manager like nvm for more informations see the official npm guide.
For various operating system.
nvm installs node and it's modules in the user's HOME FOLDER thereby solving EACCES
issues.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
drpCategory.DataSource = CategoryHelper.Categories;
drpCategory.DataTextField = "Name";
drpCategory.DataValueField = "Id";
drpCategory.DataBind();
}
}
This has happened to me multiple times. I have used Amazon Linux AMI 2013.09.2 and Ubuntu Server 12.04.3 LTS which are both on the free tier.
Every time I have launched an instance I have permission denied show up. I haven't verified this but my theory is that the server is not completely set up before I try to ssh into it. After a few tries with permission denied, I wait a few minutes and then I am able to connect. If you are having this problem I suggest waiting five minutes and trying again.
Since you want to know how it works, I'll explain it step-by-step.
First you want to bind a function as the image's click handler:
$('#someImage').click(function () {
// Code to do scrolling happens here
});
That will apply the click handler to an image with id="someImage"
. If you want to do this to all images, replace '#someImage'
with 'img'
.
Now for the actual scrolling code:
Get the image offsets (relative to the document):
var offset = $(this).offset(); // Contains .top and .left
Subtract 20 from top
and left
:
offset.left -= 20;
offset.top -= 20;
Now animate the scroll-top and scroll-left CSS properties of <body>
and <html>
:
$('html, body').animate({
scrollTop: offset.top,
scrollLeft: offset.left
});
During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.
You can make your constructor private
or internal
if you want, just so long as it's parameterless.
Assuming the URL syntax will always be http://www.youtube.com/watch?v= ...
String v = "http://www.youtube.com/watch?v=_RCIP6OrQrE".substring(31);
or disregarding the prefix syntax:
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
String v = url.substring(url.indexOf("v=") + 2);
The short answer for lazy people like me:
type Overrided = Omit<YourInterface, 'overrideField'> & { overrideField: <type> };
SET SESSION group_concat_max_len = 1000000;
is a temporary, session-scope, setting. It only applies to the current session You should use it like this.
SET SESSION group_concat_max_len = 1000000;
select group_concat(column) from table group by column
You can do this even in sharing hosting, but when you use an other session, you need to repeat the SET SESSION
command.
For me, the following also worked in Jenkins 2 (2.73.3)
Replace
def pa = new ParametersAction([new StringParameterValue("FOO", foo)])
build.addAction(pa)
with
def pa = new ParametersAction([new StringParameterValue("FOO", foo)], ["FOO"])
build.addAction(pa)
ParametersAction seems to have a second constructor which allows to pass in "additionalSafeParameters" https://github.com/jenkinsci/jenkins/blob/master/core/src/main/java/hudson/model/ParametersAction.java
JSX:
<select value={ this.state.foo } onChange={this.handleFooChange}>
<option value="A">A</option>
<option value="B">B</option>
</select>
TypeScript:
private handleFooChange = (event: React.FormEvent<HTMLSelectElement>) => {
const element = event.target as HTMLSelectElement;
this.setState({ foo: element.value });
}
Another method, starting with the method:
double i = (10 * 0.69);
Console.Write(ToStringFull(i)); // Output 6.89999999999999946709294817
Console.Write(ToStringFull(-6.9) // Output -6.90000000000000035527136788
Console.Write(ToStringFull(i - 6.9)); // Output -0.00000000000000088817841970012523233890533
public static string ToStringFull(double value)
{
if (value == 0.0) return "0.0";
if (double.IsNaN(value)) return "NaN";
if (double.IsNegativeInfinity(value)) return "-Inf";
if (double.IsPositiveInfinity(value)) return "+Inf";
long bits = BitConverter.DoubleToInt64Bits(value);
BigInteger mantissa = (bits & 0xfffffffffffffL) | 0x10000000000000L;
int exp = (int)((bits >> 52) & 0x7ffL) - 1023;
string sign = (value < 0) ? "-" : "";
if (54 > exp)
{
double offset = (exp / 3.321928094887362358); //...or =Math.Log10(Math.Abs(value))
BigInteger temp = mantissa * BigInteger.Pow(10, 26 - (int)offset) >> (52 - exp);
string numberText = temp.ToString();
int digitsNeeded = (int)((numberText[0] - '5') / 10.0 - offset);
if (exp < 0)
return sign + "0." + new string('0', digitsNeeded) + numberText;
else
return sign + numberText.Insert(1 - digitsNeeded, ".");
}
return sign + (mantissa >> (52 - exp)).ToString();
}
To solve this problem I used the BigInteger tools. Large values are simple as they just require left shifting the mantissa by the exponent. For small values we cannot just directly right shift as that would lose the precision bits. We must first give it some extra size by multiplying it by a 10^n and then do the right shifts. After that, we move over the decimal n places to the left. More text/code here.
With jQuery UI just do this!
$( "#draggable" ).draggable({
start: function() {
},
drag: function() {
},
stop: function() {
}
});
If you want to fake a $_GET (or a $_POST) when including a file, you can use it like you would use any other var, like that:
$_GET['key'] = 'any get value you want';
include('your_other_file.php');
In MySql,the following query shall show the total number of open connections:
show status like 'Threads_connected';
If you are intending on passing those integers to a function or method, consider this example:
sum(int(x) for x in numbers)
This construction is intentionally remarkably similar to list comprehensions mentioned by adamk. Without the square brackets, it's called a generator expression, and is a very memory-efficient way of passing a list of arguments to a method. A good discussion is available here: Generator Expressions vs. List Comprehension
One pitfall I ran into was a parent element having the 'overflow' attribute set to 'auto'. This negates child div elements with the page-break-inside attribute in the print version. Otherwise, page-break-inside: avoid
works fine on Chrome for me.
ALTER TABLE [table_name] ALTER COLUMN [column_name] varchar(150)
internal members are accessible within the assembly (only accessible in the same project)
private members are accessible within the same class
There are 2 projects in a solution (Project1, Project2) and Project1 has a reference to Project2.
Not with an iterator.
For org.json.JSONArray
, you can do:
for (int i = 0; i < arr.length(); i++) {
arr.getJSONObject(i);
}
For javax.json.JsonArray
, you can do:
for (int i = 0; i < arr.size(); i++) {
arr.getJsonObject(i);
}
What is currentWorksheet
? It works if you use the built-in ActiveSheet
.
dataStartRow=1
dataStartCol=1
dataEndRow=4
dataEndCol=4
Set currentWorksheet=ActiveSheet
dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, dataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
For start Activity 2 from Activity 1 and get result, you could use startActivityForResult and implement onActivityResult in Activity 1 and use setResult in Activity2.
Intent intent = new Intent(this, Activity2.class);
intent.putExtra(NUMERO1, numero1);
intent.putExtra(NUMERO2, numero2);
//startActivity(intent);
startActivityForResult(intent, MI_REQUEST_CODE);
Apple recommends for stylistic purposes.If you write this code:
@property (nonatomic,assign) BOOL working;
Then you can not use [object isWorking].
It will show an error. But if you use below code means
@property (assign,getter=isWorking) BOOL working;
So you can use [object isWorking] .
You should also be able to do:
apt install sudo
sudo -i -u tomcat
Then you should be the tomcat user. It's not clear which Linux distribution you're using, but this works with Ubuntu 18.04 LTS, for example.
you can make use of the below code for sorting in descending order and storing to a dictionary:
listname = []
for key, value in sorted(dictionaryName.iteritems(), key=lambda (k,v): (v,k),reverse=True):
diction= {"value":value, "key":key}
listname.append(diction)
This can also happen if you've recently upgraded Ant. I was using Ant 1.8.4 on a project, and upgraded Ant to 1.9.4, and started to get this error when building a fat jar using Ant.
The solution for me was to downgrade back to Ant 1.8.4 for the command line and Eclipse using the process detailed here
Take a look at my implementation. It's safe from null lists.
IList<string> all= new List<string>();
if (letterForm.SecretaryPhone!=null)// first list may be null
all=all.Concat(letterForm.SecretaryPhone).ToList();
if (letterForm.EmployeePhone != null)// second list may be null
all= all.Concat(letterForm.EmployeePhone).ToList();
if (letterForm.DepartmentManagerName != null) // this is not list (its just string variable) so wrap it inside list then concat it
all = all.Concat(new []{letterForm.DepartmentManagerPhone}).ToList();
In page header, add
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-sacle=1, maximum-scale=1, user-scalable=no">
In page stylesheet, add
html, body {
overflow-x: hidden;
overflow-y: hidden;
}
It is both html and body!
Are you passing the DISPLAY parameter to your Jenkins job?
I assume you are trying to execute the tests in headless mode, too. So setup some x service (i.e. Xvfb) and pass the DISPLAY number to your job. Worked for me.
If you want to pass global variables into new scripts, you can create a python file that is only meant for holding global variables (e.g. globals.py). When you import this file at the top of the child script, it should have access to all of those variables.
If you are writing to these variables, then that is a different story. That involves concurrency and locking the variables, which I'm not going to get into unless you want.
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
The jar was compiled to be 1.6
compliant. That is why you get this error. Two resolutions:
1) Use Java 1.6
OR
2) Recompile the jar to be compliant for your environment 1.7
Use the left
function:
QString yourString = "This is a string";
QString leftSide = yourString.left(5);
qDebug() << leftSide; // output "This "
Also have a look at mid()
if you want more control.
int segundo = 0;
DateTime dt = new DateTime();
private void timer1_Tick(object sender, EventArgs e){
segundo++;
label1.Text = dt.AddSeconds(segundo).ToString("HH:mm:ss");
}
Looks like it could be throwing the error on the empty data row, have you tried to just make sure itemDate isn't empty before you run the CDate() function? I think this might be your problem.
I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.
I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.
Use the below simple query to get random data from a table.
SELECT user_firstname ,
COUNT(DISTINCT usr_fk_id) cnt
FROM userdetails
GROUP BY usr_fk_id
ORDER BY cnt ASC
LIMIT 10
I have got this error only when debugging the ASP .Net Application.
I also had Session["mysession"]
kind of variables added into my Watch of Visual Studio.
the issue was solved Once, I have removed the Session Variables from watch.
Reading and printing the content of a text file (.txt)
in Python3
Consider this as the content of text file with the name world.txt
:
Hello World! This is an example of Content of the Text file we are about to read and print
using python!
First we will open this file by doing this:
file= open("world.txt", 'r')
Now we will get the content of file in a variable using .read()
like this:
content_of_file= file.read()
Finally we will just print the content_of_file
variable using print
command.
print(content_of_file)
Output:
Hello World! This is an example of Content of the Text file we are about to read and print using python!
You can use XDocument.Parse(string)
instead of Load(string)
.
For me I got this error because I was trying to read a file which required HTTP auth, with a username and password. Hope that helps others. Might be another corner case.
You can also use Ghostscript to merge different PDFs. You can even use it to merge a mix of PDFs, PostScript (PS) and EPS into one single output PDF file:
gs \
-o merged.pdf \
-sDEVICE=pdfwrite \
-dPDFSETTINGS=/prepress \
input_1.pdf \
input_2.pdf \
input_3.eps \
input_4.ps \
input_5.pdf
However, I agree with other answers: for your use case of merging PDF file types only, pdftk
may be the best (and certainly fastest) option.
Update:
If processing time is not the main concern, but if the main concern is file size (or a fine-grained control over certain features of the output file), then the Ghostscript way certainly offers more power to you. To highlight a few of the differences:
For the record, and excluding the time that it takes:
<?php
echo "<hr>First:<br>";
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";
echo memory_get_peak_usage() . "<br>\n";
echo "<hr>Unset:<br>";
unset($x);
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";
echo memory_get_peak_usage() . "<br>\n";
echo "<hr>Null:<br>";
$x=null;
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";
echo memory_get_peak_usage() . "<br>\n";
echo "<hr>function:<br>";
function test() {
$x = str_repeat('x', 80000);
}
echo memory_get_usage() . "<br>\n";
echo memory_get_peak_usage() . "<br>\n";
echo "<hr>Reasign:<br>";
$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";
echo memory_get_peak_usage() . "<br>\n";
It returns
First:
438296
438352
Unset:
438296
438352
Null:
438296
438352
function:
438296
438352
Reasign:
438296
520216 <-- double usage.
Conclusion, both null and unset free memory as expected (not only at the end of the execution). Also, reassigning a variable holds the value twice at some point (520216 versus 438352)
$("input[@name='<%=test2.ClientID%>']:checked");
use this and here ClientID fetch random id created by .net.
Split uses regex, and the pipe char |
has special meaning in regex, so you need to escape it. There are a few ways to do this, but here's the simplest:
String[] tokens = line.split("\\|\\|");
for Swift 3.0 add image on leftside of textField
textField.leftView = UIImageView(image: "small-calendar")
textField.leftView?.frame = CGRect(x: 0, y: 5, width: 20 , height:20)
textField.leftViewMode = .always
If the types of the parameters are all the same (varchar2
for example), you can have a package like this which will do the following:
CREATE OR REPLACE PACKAGE testuser.test_pkg IS
TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);
END test_pkg;
CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS
PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
BEGIN
FOR i IN p_parm.first .. p_parm.last
LOOP
dbms_output.put_line(p_parm(i));
END LOOP;
END;
END test_pkg;
Then, to call it you'd need to set up the array and pass it:
DECLARE
l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
l_array(0) := 'hello';
l_array(1) := 'there';
testuser.test_pkg.your_proc(l_array);
END;
/
I may have missed something here, but why can't you just declare your string with the desired size? For example, in my VBA code I often use something like:
Dim AString As String * 1024
which provides for a 1k string. Obviously, you can use whatever declaration you like within the larger limits of Excel and available memory etc.
This may be a little inefficient in some cases, and you will probably wish to use Trim(AString) like constructs to obviate any superfluous trailing blanks. Still, it easily exceeds 256 chars.
With the introduction of lambda expression in Java 8 you can now have anonymous methods.
Say I have a class Alpha
and I want to filter Alpha
s on a specific condition. To do this you can use a Predicate<Alpha>
. This is a functional interface which has a method test
that accepts an Alpha
and returns a boolean
.
Assuming that the filter method has this signature:
List<Alpha> filter(Predicate<Alpha> filterPredicate)
With the old anonymous class solution you would need to something like:
filter(new Predicate<Alpha>() {
boolean test(Alpha alpha) {
return alpha.centauri > 1;
}
});
With the Java 8 lambdas you can do:
filter(alpha -> alpha.centauri > 1);
For more detailed information see the Lambda Expressions tutorial
I am using pandas.
import pandas as pd
x = pd.Series([1,2,3,4,5])
x.to_excel('temp.xlsx')
y = list(pd.read_excel('temp.xlsx')[0])
print(y)
Use this if you are anyway importing pandas for other computations.
Try this, works for me: ls -d /a/b/c/*
I built this little function to automatically format anything into a nice currency format.
function formatDollars($dollars)
{
return "$".number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)),2);
}
Edit
It was pointed out that this does not show negative values. I broke it into two lines so it's easier to edit the formatting. Wrap it in parenthesis if it's a negative value:
function formatDollars($dollars)
{
$formatted = "$" . number_format(sprintf('%0.2f', preg_replace("/[^0-9.]/", "", $dollars)), 2);
return $dollars < 0 ? "({$formatted})" : "{$formatted}";
}
Building upon the already compact solution from @Dan, here's a self-contained function version of it. Variable names are reduced to single letters for those who just want it to be as compact as possible at the expense of context.
const ns = {};
ns.sizeof = function(v) {
let f = ns.sizeof, //this needs to match the name of the function itself, since arguments.callee.name is defunct
o = {
"undefined": () => 0,
"boolean": () => 4,
"number": () => 8,
"string": i => 2 * i.length,
"object": i => !i ? 0 : Object
.keys(i)
.reduce((t, k) => f(k) + f(i[k]) + t, 0)
};
return o[typeof v](v);
};
ns.undef;
ns.bool = true;
ns.num = 1;
ns.string = "Hello";
ns.obj = {
first_name: 'Brendan',
last_name: 'Eich',
born: new Date(1961, 6, 4),
contributions: ['Netscape', 'JavaScript', 'Brave', 'BAT'],
politically_safe: false
};
console.log(ns.sizeof(ns.undef));
console.log(ns.sizeof(ns.bool));
console.log(ns.sizeof(ns.num));
console.log(ns.sizeof(ns.string));
console.log(ns.sizeof(ns.obj));
console.log(ns.sizeof(ns.obj.contributions));
_x000D_
Using Array#select
will give you an array of elements that meet the criteria. But if you're looking for a way of getting the element out of the array that meets your criteria, Enumerable#detect
would be a better way to go:
array = [1,2,3]
found = array.select {|e| e == 3} #=> [3]
found = array.detect {|e| e == 3} #=> 3
Otherwise you'd have to do something awkward like:
found = array.select {|e| e == 3}.first
One of the best example where we use mutable is, in deep copy. in copy constructor we send const &obj
as argument. So the new object created will be of constant type. If we want to change (mostly we won't change, in rare case we may change) the members in this newly created const object we need to declare it as mutable
.
mutable
storage class can be used only on non static non const data member of a class. Mutable data member of a class can be modified even if it's part of an object which is declared as const.
class Test
{
public:
Test(): x(1), y(1) {};
mutable int x;
int y;
};
int main()
{
const Test object;
object.x = 123;
//object.y = 123;
/*
* The above line if uncommented, will create compilation error.
*/
cout<< "X:"<< object.x << ", Y:" << object.y;
return 0;
}
Output:-
X:123, Y:1
In the above example, we are able to change the value of member variable x
though it's part of an object which is declared as const. This is because the variable x
is declared as mutable. But if you try to modify the value of member variable y
, compiler will throw an error.
Assuming that you are using the m2e plugin in Eclipse, you'll need to specify the source
and target
versions as 1.6 for maven-compiler-plugin
. m2e uses these values to determine the project's Java compiler level. A snippet of the POM is shown below:
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
Alternatively, you can specify the maven.compiler.source
and maven.compiler.target
properties with values of 1.6, that happen to be the equivalent:
<properties>
<maven.compiler.target>1.6</maven.compiler.target>
<maven.compiler.source>1.6</maven.compiler.source>
</properties>
Cordova Apps
:We need to place the google-services.json
file in app root
(I believe; when working with Cordova apps, we are not to get into other folders/files such as Gradle, Java files, platforms, etc; instead only work with them VIA the config.xml
and www
folder) and refer it in the config.xml
like so:
<platform name="android">
<!-- Add this line -->
<resource-file src="google-services.json" target="app/google-services.json" />
</platform>
Firebase App packagename
is same as the id
attribute in <widget id="<packagename>" ... >
are same.For ex:
<!-- config.xml of Cordova App -->
<widget id="com.appFactory.torchapp" ...>
<!--google-serivces.json from generated from Firebase console.-->
{
...
packagename: "com.appFactory.torchapp",
...
}
Good Luck...
Use this method:
$_product = wc_get_product( $id );
Official API-docs: wc_get_product
Although this thread dates back to 2014, the issue can still be current to many of us. Here is how I dealt with it in a jQuery 1.12 /PHP 5.6 context:
PHP Code sample:
if (!empty($_SERVER['HTTP_ORIGIN'])) {
// Uh oh, this XHR comes from outer space...
// Use this opportunity to filter out referers that shouldn't be allowed to see this request
if (!preg_match('@\.partner\.domain\.net$@'))
die("End of the road if you're not my business partner.");
// otherwise oblige
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
}
else {
// local request, no need to send a specific header for CORS
}
In particular, don't add an exit;
as no preflight is needed.