My own version of using Moment in Angular
npm i moment --save
import * as _moment from 'moment';
...
moment: _moment.Moment = _moment();
constructor() { }
ngOnInit() {
const unix = this.moment.format('X');
console.log(unix);
}
First import moment as _moment
, then declare moment
variable with type _moment.Moment
with an initial value of _moment()
.
Plain import of moment wont give you any auto completion but if you will declare moment with type Moment
interface from _moment
namespace from 'moment'
package initialized with moment namespace invoked _moment()
gives you auto completion of moment's api's.
I think this is the most angular way of using moment without using @types
typings
or angular providers, if you're looking auto completion for vanilla javascript libraries like moment.
EDIT: This answer is now outdated, see the updated version.
In my R package I have enhanced sample
so that it now behaves as expected also for data frames:
library(devtools); install_github('kimisc', 'krlmlr')
library(kimisc)
example(sample.data.frame)
smpl..> set.seed(42)
smpl..> sample(data.frame(a=c(1,2,3), b=c(4,5,6),
row.names=c('a', 'b', 'c')), 10, replace=TRUE)
a b
c 3 6
c.1 3 6
a 1 4
c.2 3 6
b 2 5
b.1 2 5
c.3 3 6
a.1 1 4
b.2 2 5
c.4 3 6
This is achieved by making sample
an S3 generic method and providing the necessary (trivial) functionality in a function. A call to setMethod
fixes everything. The original implementation still can be accessed through base::sample
.
The reason you can't get it to work is because the Load
event is called before the form is drawn or rendered.
It like telling a pizza place how to make your pizza, and then asking them to send you a picture of how much pepperoni is on your pizza before they made it.
using System;
using System.Windows.Forms;
namespace Testing
{
public partial class TestForm : Form
{
public TestForm()
{
InitializeComponent();
Load += TestForm_Load;
VisibleChanged += TestForm_VisibleChanged;
Shown += TestForm_Shown;
Show();
}
private void TestForm_Load(object sender, EventArgs e)
{
MessageBox.Show("This event is called before the form is rendered.");
}
private void TestForm_VisibleChanged(object sender, EventArgs e)
{
MessageBox.Show("This event is called before the form is rendered.");
}
private void TestForm_Shown(object sender, EventArgs e)
{
MessageBox.Show("This event is called after the form is rendered.");
txtFirstName.Focus();
}
}
}
Using a custom url attribute makes the HTML invalid. Although that may not be a huge problem, the given examples are neither accessible. Not for keyboard navigation and not in cases when JavaScript is turned off (or blocked by some other script). Even Google will not find the page located at the specified url, not via this route at least.
It's quite easy to make this accessible though. Just make sure there's a regular link inside the div that points to the url. Using JavaScript/jQuery you add an onclick to the div that redirects to the location specified by the link's href attribute. Now, when JavaScript doesn't work, the link still does and it can even catch the focus when using the keyboard to navigate (and you don't need custom attributes, so your HTML can be valid).
I wrote a jQuery plugin some time ago that does this. It also adds classNames to the div (or any other element you want to make clickable) and the link so you can alter their looks with CSS when the div is indeed clickable. It even adds classNames that you can use to specify hover and focus styles.
All you need to do is specify the element(s) you want to make clickable and call their clickable() method: in your case that would be $("div.clickable).clickable();
For downloading + documentation see the plugin's page: jQuery: clickable — jLix
I need to divide a list by a number and fixed like this.
l = [1,2,3,4,5,6]
def divideByN(data, n):
return [data[i*n : (i+1)*n] for i in range(len(data)//n)]
>>> print(divideByN(l,2))
[[1, 2], [3, 4], [5, 6]]
>>> print(divideByN(l,3))
[[1, 2, 3], [4, 5, 6]]
I wanted an utility class which is not managed by spring, so no spring annotations like @Component
, @Configuration
etc. But I wanted the class to read from application.properties
I managed to get it working by getting the class to be aware of the Spring Context, hence is aware of Environment
, and hence environment.getProperty()
works as expected.
To be explicit, I have:
application.properties
mypath=somestring
Utils.java
import org.springframework.core.env.Environment;
// No spring annotations here
public class Utils {
public String execute(String cmd) {
// Making the class Spring context aware
ApplicationContextProvider appContext = new ApplicationContextProvider();
Environment env = appContext.getApplicationContext().getEnvironment();
// env.getProperty() works!!!
System.out.println(env.getProperty("mypath"))
}
}
ApplicationContextProvider.java (see Spring get current ApplicationContext)
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class ApplicationContextProvider implements ApplicationContextAware {
private static ApplicationContext CONTEXT;
public ApplicationContext getApplicationContext() {
return CONTEXT;
}
public void setApplicationContext(ApplicationContext context) throws BeansException {
CONTEXT = context;
}
public static Object getBean(String beanName) {
return CONTEXT.getBean(beanName);
}
}
They are simply showed like this:
_______________________
| <<enumeration>> |
| DaysOfTheWeek |
|_____________________|
| Sunday |
| Monday |
| Tuesday |
| ... |
|_____________________|
And then just have an association between that and your class.
I use this function :
<?php
function is_ping_address($ip) {
exec('ping -c1 -w1 '.$ip, $outcome, $status);
preg_match('/([0-9]+)% packet loss/', $outcome[3], $arr);
return ( $arr[1] == 100 ) ? false : true;
}
One more way - mark such buttons with a CSS class and filter:
$('#myButton:not(.bound)').addClass('bound').bind('click', onButtonClicked);
In recent jQuery versions replace bind
with on
:
$('#myButton:not(.bound)').addClass('bound').on('click', onButtonClicked);
If df
is a pandas.DataFrame
then df['new_col']= Series list_object of length len(df)
will add the or Series list_object as a column named 'new_col'
. df['new_col']= scalar
(such as 5 or 6 in your case) also works and is equivalent to df['new_col']= [scalar]*len(df)
So a two-line code serves the purpose:
df = pd.DataFrame({'a':[1, 2], 'b':[3, 4]})
s = pd.Series({'s1':5, 's2':6})
for x in s.index:
df[x] = s[x]
Output:
a b s1 s2
0 1 3 5 6
1 2 4 5 6
It's worth noting that multiple field indexes can drastically improve your query performance. So in the above example we assume ProductID is the only field to lookup but were the query to say ProductID = 1 AND Category = 7 then a multiple column index helps. This is achieved with the following:
ALTER TABLE `table` ADD INDEX `index_name` (`col1`,`col2`)
Additionally the index should match the order of the query fields. In my extended example the index should be (ProductID,Category) not the other way around.
You're missing semi-colons after your javascript lines. Also, window.location
should have .href
or .replace
etc to redirect - See this post for more information.
echo '<script type="text/javascript">';
echo 'alert("review your answer");';
echo 'window.location.href = "index.php";';
echo '</script>';
For clarity, try leaving PHP tags for this:
?>
<script type="text/javascript">
alert("review your answer");
window.location.href = "index.php";
</script>
<?php
NOTE: semi colons on seperate lines are optional, but encouraged - however as in the comments below, PHP won't break lines in the first example here but will in the second, so semi-colons are required in the first example.
The best thing I've found for diagnosing things like this is the service trace viewer. It's pretty simple to set up (assuming you can edit the configs):
http://msdn.microsoft.com/en-us/library/ms732023.aspx
Hope this helps.
This may not have been the OP's problem, but I had the same problem and solved it by flushing then disabling Supercache on my cpanel. Perhaps some other newbies like myself won't know that many hosting providers cache CSS and some other static files, and these cached old versions of CSS files will persist in the cloud for hours after you edit the file on your server. If your site serves up old versions of CSS files after you edit them, and you're certain you've cleared your browser cache, and you don't know whether your host is caching stuff, check that first before you try any other more complicated suggestions.
I ran into this problem when I inadvertently had a copy of the view file (About.cshtml) for the route /about in the root directory. (Not the views folder) Once I moved the file out of the root, the problem went away.
For all, who has installed GiT completly with "Git Bash": You can just write:
scp login@ip_addres:/location/to/folders/file.tar .
(with space and DOT at the end to copy to current location). Than just add certificate (y), write password and that's all.
Taking advantage of Matt Fenwick's idea that helped me to solve the problem (a lot of thanks), let's reduce it to only one query:
select
history.*,
coalesce(sum(case when itemname = "A" then itemvalue end), 0) as A,
coalesce(sum(case when itemname = "B" then itemvalue end), 0) as B,
coalesce(sum(case when itemname = "C" then itemvalue end), 0) as C
from history
group by hostid
in the graphical layout, you can choose the theme on the toolbar. (the one that looks like a star).
choose the NoTitleBar
and have fun.
For whose have a problem with installing rabbitmqadmin, You should firstly install python.
UNIX-like operating system users need to copy rabbitmqadmin to a directory in PATH, e.g. /usr/local/bin.
Windows users will need to ensure Python is on their PATH, and invoke rabbitmqadmin as python.exe rabbitmqadmin.
Then
http://{hostname}:15672/cli/rabbitmqadmin
to download. To list Queues
python rabbitmqadmin list queues
.
To delete Queue
python rabbitmqadmin delete queue name=Name_of_queue
To Delete all Queues
1- Declare Policy
python rabbitmqadmin declare policy name='expire_all_policies' pattern=.* definition={\"expires\":1} apply-to=queues
2- Remove the policy
python rabbitmqadmin delete policy name='expire_all_policies'
Razor is just a templating engine.
You should create a regular class.
If you want to make a method inside of a Razor page, put them in an @functions
block.
Several factors affect speed of SFTP transfer:
If you can use LINQ you can use:
var e = enumerable.First();
This will throw an exception though if enumerable is empty: in which case you can use:
var e = enumerable.FirstOrDefault();
FirstOrDefault()
will return default(T)
if the enumerable is empty, which will be null
for reference types or the default 'zero-value' for value types.
If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the GetEnumerator
and MoveNext
methods to retrieve the first result (this example assumes enumerable is an IEnumerable<Elem>
):
Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
if (enumer.MoveNext()) e = enumer.Current;
}
Joel Coehoorn mentioned .Single()
in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding SingleOrDefault()
method that covers this scenario in a similar fashion to FirstOrDefault()
. However, David B explains that SingleOrDefault()
may still throw an exception in the case where the enumerable contains more than one item.
Edit: Thanks Marc Gravell for pointing out that I need to dispose of my IEnumerator
object after using it - I've edited the non-LINQ example to display the using
keyword to implement this pattern.
You may want to consider using Java EE, which includes the javax.servlet.*
packages. If you require a specific version of the servlet api, for instance to target a specific web application server, you will probably want the Java EE version which matches, see this version table.
To get the index
values as a list
/list
of tuple
s for Index
/MultiIndex
do:
df.index.values.tolist() # an ndarray method, you probably shouldn't depend on this
or
list(df.index.values) # this will always work in pandas
We can create static constructor
static class StaticParent
{
StaticParent()
{
//write your initialization code here
}
}
and it is always parameter less.
static class StaticParent
{
static int i =5;
static StaticParent(int i) //Gives error
{
//write your initialization code here
}
}
and it doesn't have the access modifier
WordPress have the function get_metadata this get all meta of object (Post, term, user...)
Just use
get_metadata( 'post', 15 );
to stop a docker process and release the ports, first use ctrl-c to leave the exit the container then use docker ps to find the list of running containers. Then you can use the docker container stop to stop that process and release its ports. The container name you can find from the docker ps command which gives the name in the name column. Hope this solves your queries....
The Error
constructor is used to create an error object. Error objects are thrown when runtime errors occur. The Error object can also be used as a base object for user-defined exceptions.
User-defined Errors are thrown via the throw
statement. program control will be passed to the first catch
block in the call stack.
The difference between throwing an error with and without Error object:
throw {'hehe':'haha'};
In chrome devtools looks like this:
Chrome tells us that we have an uncaught error which just is a JS object. The object itself could have information regarding the error but we still don't know immediately where it came from. Not very useful when we are working on our code and debugging it.
throw new Error({'hehe':'haha'});
In chrome devtools looks like this:
An error thrown with the Error object gives us a stack trace when we expand it. This gives us valuable information where the error precisely came from which is often valuable information when debugging your code. Further note that the error says [object Object]
, this is because the Error
constructor expects a message string as a first argument. When it receives a object it will coerce it into a string.
[Django HTML template doesn't support index as of now], but you can achieve the goal:
If you use Dictionary inside Dictionary in views.py then iteration is possible using key as index. example:
{% for key, value in DictionartResult.items %} <!-- dictionartResult is a dictionary having key value pair-->
<tr align="center">
<td bgcolor="Blue"><a href={{value.ProjectName}}><b>{{value.ProjectName}}</b></a></td>
<td> {{ value.atIndex0 }} </td> <!-- atIndex0 is a key which will have its value , you can treat this key as index to resolve-->
<td> {{ value.atIndex4 }} </td>
<td> {{ value.atIndex2 }} </td>
</tr>
{% endfor %}
Elseif you use List inside dictionary then not only first and last iteration can be controlled, but all index can be controlled. example:
{% for key, value in DictionaryResult.items %}
<tr align="center">
{% for project_data in value %}
{% if forloop.counter <= 13 %} <!-- Here you can control the iteration-->
{% if forloop.first %}
<td bgcolor="Blue"><a href={{project_data}}><b> {{ project_data }} </b></a></td> <!-- it will always refer to project_data[0]-->
{% else %}
<td> {{ project_data }} </td> <!-- it will refer to all items in project_data[] except at index [0]-->
{% endif %}
{% endif %}
{% endfor %}
</tr>
{% endfor %}
End If ;)
// Hope have covered the solution with Dictionary, List, HTML template, For Loop, Inner loop, If Else. Django HTML Documentaion for more methods: https://docs.djangoproject.com/en/2.2/ref/templates/builtins/
There is no way. You need a default constructor for array members and it will be called, afterwards, you can do any initialization you want in the constructor.
Adding SHA1 keys from Eclipse/keytool helped me only when creating the app on FB, then after rebuilding I would always get the OP error.
What solved my issue was adding the key in the error message to the Facebook dashboard settings.
I suggest that you take advantage of the fact that you can assign multiple classes to an element like so:
<ul>
<li class="list">test1</li>
<li class="list">test2</li>
<li class="list last">test3</li>
<li>test4</li>
</ul>
The last element has the list
class like its siblings but also has the last
class which you can use to set any CSS property you want, like so:
ul li.list {
color: #FF0000;
}
ul li.list.last {
background-color: #000;
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Stack2 {
public static void waitFor(List<Future<?>> futures) {
List<Future<?>> futureCopies = new ArrayList<Future<?>>(futures);//contains features for which status has not been completed
while (!futureCopies.isEmpty()) {//worst case :all task worked without exception, then this method should wait for all tasks
Iterator<Future<?>> futureCopiesIterator = futureCopies.iterator();
while (futureCopiesIterator.hasNext()) {
Future<?> future = futureCopiesIterator.next();
if (future.isDone()) {//already done
futureCopiesIterator.remove();
try {
future.get();// no longer waiting
} catch (InterruptedException e) {
//ignore
//only happen when current Thread interrupted
} catch (ExecutionException e) {
Throwable throwable = e.getCause();// real cause of exception
futureCopies.forEach(f -> f.cancel(true));//cancel other tasks that not completed
return;
}
}
}
}
}
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
Runnable runnable1 = new Runnable (){
public void run(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
};
Runnable runnable2 = new Runnable (){
public void run(){
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
}
}
};
Runnable fail = new Runnable (){
public void run(){
try {
Thread.sleep(1000);
throw new RuntimeException("bla bla bla");
} catch (InterruptedException e) {
}
}
};
List<Future<?>> futures = Stream.of(runnable1,fail,runnable2)
.map(executorService::submit)
.collect(Collectors.toList());
double start = System.nanoTime();
waitFor(futures);
double end = (System.nanoTime()-start)/1e9;
System.out.println(end +" seconds");
}
}
Another option would be to add engine='python'
to the command pandas.read_csv(filename, sep='\t', engine='python')
After looking at this and trying it out I found it actually didn't allow more than one instance of jquery to run at a time. After searching around I found that this did just the trick and was a whole lot less code.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>var $j = jQuery.noConflict(true);</script>
<script>
$(document).ready(function(){
console.log($().jquery); // This prints v1.4.2
console.log($j().jquery); // This prints v1.9.1
});
</script>
So then adding the "j" after the "$" was all I needed to do.
$j(function () {
$j('.button-pro').on('click', function () {
var el = $('#cnt' + this.id.replace('btn', ''));
$j('#contentnew > div').not(el).animate({
height: "toggle",
opacity: "toggle"
}, 100).hide();
el.toggle();
});
});
sudo apt install php-xml
will work but the thing is it will download the plugin for the latest PHP version.
If your PHP version is not the latest, then you can add version in it:
# PHP 7.1
sudo apt install php7.1-xml
# PHP 7.2:
sudo apt install php7.2-xml
# PHP 7.3
sudo apt install php7.3-xml
# PHP 7.4
sudo apt install php7.4-xml
# PHP 8
sudo apt install php-xml
This works for Swift 5:
self.navigationItem.backBarButtonItem?.title = ""
Please note it will be effective for the next pushed view controller not the current one on the display, that's why it's very confusing!
Also, check the storyboard and select the navigation item of the previous view controller then type something in the Back Button (Inspector).
This is not how you do things in Java. There are no dynamic variables in Java. Java variables have to be declared in the source code1.
Depending on what you are trying to achieve, you should use an array, a List
or a Map
; e.g.
int n[] = new int[3];
for (int i = 0; i < 3; i++) {
n[i] = 5;
}
List<Integer> n = new ArrayList<Integer>();
for (int i = 1; i < 4; i++) {
n.add(5);
}
Map<String, Integer> n = new HashMap<String, Integer>();
for (int i = 1; i < 4; i++) {
n.put("n" + i, 5);
}
It is possible to use reflection to dynamically refer to variables that have been declared in the source code. However, this only works for variables that are class members (i.e. static and instance fields). It doesn't work for local variables. See @fyr's "quick and dirty" example.
However doing this kind of thing unnecessarily in Java is a bad idea. It is inefficient, the code is more complicated, and since you are relying on runtime checking it is more fragile. And this is not "variables with dynamic names". It is better described as dynamic access to variables with static names.
1 - That statement is slightly inaccurate. If you use BCEL or ASM, you can "declare" the variables in the bytecode file. But don't do it! That way lies madness!
It is safer and more flexible to load the assembly into its own AppDomain
first.
So instead of the answer given previously:
var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
I would suggest the following (adapted from this answer to a related question):
var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();
Now you can unload the assembly and have different security settings.
If you want even more flexibility and power for dynamic loading and unloading of assemblies, you should look at the Managed Add-ins Framework (i.e. the System.AddIn
namespace). For more information, see this article on Add-ins and Extensibility on MSDN.
<video width="320" height="240" autoplay="autoplay">
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
WITH PATHLIB MODULE (UPDATED ANSWER)
One should consider using pathlib for new development. It is in the stdlib for Python3.4, but available on PyPI for earlier versions. This library provides a more object-orented method to manipulate paths <opinion>
and is much easier read and program with </opinion>
.
>>> import pathlib
>>> existGDBPath = pathlib.Path(r'T:\Data\DBDesign\DBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:\Data\DBDesign')
WITH OS MODULE
Use the os.path module:
>>> import os
>>> existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr
'T:\Data\DBDesign'
You can go ahead and assume that if you need to do some sort of filename manipulation it's already been implemented in os.path
. If not, you'll still probably need to use this module as the building block.
See the Scripting Guy! Blog:
How Can I Tell Whether a Value Exists in the Registry?
They discuss doing the check on a remote computer and show that if you read a string value from the key, and if the value is Null (as opposed to Empty), the key does not exist.
With respect to using the RegRead method, if the term "key" refers to the path (or folder) where registry values are kept, and if the leaf items in that key are called "values", using WshShell.RegRead(strKey) to detect key existence (as opposed to value existance) consider the following (as observed on Windows XP):
If strKey name is not the name of an existing registry path, Err.Description reads "Invalid root in registry key"... with an Err.Number of 0x80070002.
If strKey names a registry path that exists but does not include a trailing "\" the RegRead method appears to interpret strKey as a path\value reference rather than as a simple path reference, and returns the same Err.Number but with an Err.Description of "Unable to open registry key". The term "key" in the error message appears to mean "value". This is the same result obtained when strKey references a path\value where the path exists, but the value does not exist.
Like this:
numrows = len(input) # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example
Assuming that all the sublists have the same length (that is, it's not a jagged array).
The accepted answer is good, but it can be greatly improved by additionally backing up on every save and backing up versioned files.
First, basic settings as described in the accepted answer:
(setq version-control t ;; Use version numbers for backups.
kept-new-versions 10 ;; Number of newest versions to keep.
kept-old-versions 0 ;; Number of oldest versions to keep.
delete-old-versions t ;; Don't ask to delete excess backup versions.
backup-by-copying t) ;; Copy all files, don't rename them.
Next, also backup versioned files, which Emacs does not do by default (you don't commit on every save, right?):
(setq vc-make-backup-files t)
Finally, make a backup on each save, not just the first. We make two kinds of backups:
per-session backups: once on the first save of the buffer in each Emacs session. These simulate Emac's default backup behavior.
per-save backups: once on every save. Emacs does not do this by default, but it's very useful if you leave Emacs running for a long time.
The backups go in different places and Emacs creates the backup dirs automatically if they don't exist:
;; Default and per-save backups go here:
(setq backup-directory-alist '(("" . "~/.emacs.d/backup/per-save")))
(defun force-backup-of-buffer ()
;; Make a special "per session" backup at the first save of each
;; emacs session.
(when (not buffer-backed-up)
;; Override the default parameters for per-session backups.
(let ((backup-directory-alist '(("" . "~/.emacs.d/backup/per-session")))
(kept-new-versions 3))
(backup-buffer)))
;; Make a "per save" backup on each save. The first save results in
;; both a per-session and a per-save backup, to keep the numbering
;; of per-save backups consistent.
(let ((buffer-backed-up nil))
(backup-buffer)))
(add-hook 'before-save-hook 'force-backup-of-buffer)
I became very interested in this topic after I wrote $<
instead of
$@
in my Makefile
, about three hours after my previous commit :P
The above is based on an Emacs Wiki page I heavily edited.
For reference, try this! It works!
jQuery("classNameofDiv").click(function() {
var contentPanelId = jQuery(this).attr("id");
alert(contentPanelId);
});
I don't see either MacPorts or Homebrew mentioned in other answers here, but since I do see them mentioned elsewhere on Stack Overflow for related questions, I'll add my own US$0.02 that many folks seem to consider MacPorts as not only a package manager for packages in general (as of today they list 16311 packages/ports, 2931 matching "python", albeit only for Macs), but also as a decent (maybe better) package manager for Python packages/modules:
"...what is the method that Mac python developers use to manage their modules?"
I'm still debating on whether or not to use MacPorts myself, but at the moment I'm leaning in that direction.
Found an easy way which works with all browsers I have (Chrome 49, Edge 25, Firefox 44, IE11, Safari 5 [Win], Safari 8 (MacOS)) :
// Clean svg content (if you want to update the svg's objects)_x000D_
// Note : .html('') doesn't works for svg in some browsers_x000D_
$('#svgObject').empty();_x000D_
// add some objects_x000D_
$('#svgObject').append('<polygon class="svgStyle" points="10,10 50,10 50,50 10,50 10,10" />');_x000D_
$('#svgObject').append('<circle class="svgStyle" cx="100" cy="30" r="25"/>');_x000D_
_x000D_
// Magic happens here: refresh DOM (you must refresh svg's parent for Edge/IE and Safari)_x000D_
$('#svgContainer').html($('#svgContainer').html());
_x000D_
.svgStyle_x000D_
{_x000D_
fill:cornflowerblue;_x000D_
fill-opacity:0.2;_x000D_
stroke-width:2;_x000D_
stroke-dasharray:5,5;_x000D_
stroke:black;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="svgContainer">_x000D_
<svg id="svgObject" height="100" width="200"></svg>_x000D_
</div>_x000D_
_x000D_
<span>It works if two shapes (one square and one circle) are displayed above.</span>
_x000D_
You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to int
it will be accepted as input (although it will be questionable if that's the right way to do it).
It would be better to convert your training scores by using scikit's labelEncoder
function.
The same is true for your DecisionTree and KNeighbors qualifier.
from sklearn import preprocessing
from sklearn import utils
lab_enc = preprocessing.LabelEncoder()
encoded = lab_enc.fit_transform(trainingScores)
>>> array([1, 3, 2, 0], dtype=int64)
print(utils.multiclass.type_of_target(trainingScores))
>>> continuous
print(utils.multiclass.type_of_target(trainingScores.astype('int')))
>>> multiclass
print(utils.multiclass.type_of_target(encoded))
>>> multiclass
If you are looking for a specific content in all files from a directory structure, you may use find
since it is more clear what you are doing:
find -type f -exec grep -l "texthere" {} +
Note that -l
(downcase of L) shows the name of the file that contains the text. Remove it if you instead want to print the match itself. Or use -H
to get the file together with the match. All together, other alternatives are:
find -type f -exec grep -Hn "texthere" {} +
Where -n
prints the line number.
I had this same error while trying to include a PHP file in my Wordpress theme. I was able to get around it by referencing the file name using dirname(__FILE__)
. I couldn't use relative paths since my file was going to be included in different places throughout the theme, so something like require_once '../path-to/my-file'
wouldn't work.
Replacing require_once get_template_directory_uri() . '/path-to/my-file'
with require_once dirname( __FILE__ ) . '/path-to/my-file'
did the trick.
If you want a table where only the columns scroll horizontally, you can position: absolute
the first column (and specify its width explicitly), and then wrap the entire table in an overflow-x: scroll
block. Don't bother trying this in IE7, however...
Relevant HTML & CSS:
table {_x000D_
border-collapse: separate;_x000D_
border-spacing: 0;_x000D_
border-top: 1px solid grey;_x000D_
}_x000D_
_x000D_
td, th {_x000D_
margin: 0;_x000D_
border: 1px solid grey;_x000D_
white-space: nowrap;_x000D_
border-top-width: 0px;_x000D_
}_x000D_
_x000D_
div {_x000D_
width: 500px;_x000D_
overflow-x: scroll;_x000D_
margin-left: 5em;_x000D_
overflow-y: visible;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.headcol {_x000D_
position: absolute;_x000D_
width: 5em;_x000D_
left: 0;_x000D_
top: auto;_x000D_
border-top-width: 1px;_x000D_
/*only relevant for first row*/_x000D_
margin-top: -1px;_x000D_
/*compensate for top border*/_x000D_
}_x000D_
_x000D_
.headcol:before {_x000D_
content: 'Row ';_x000D_
}_x000D_
_x000D_
.long {_x000D_
background: yellow;_x000D_
letter-spacing: 1em;_x000D_
}
_x000D_
<div>_x000D_
<table>_x000D_
<tr><th class="headcol">1</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
<tr><th class="headcol">2</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
<tr><th class="headcol">3</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
<tr><th class="headcol">4</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
<tr><th class="headcol">5</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
<tr><th class="headcol">6</th><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td><td class="long">QWERTYUIOPASDFGHJKLZXCVBNM</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
Most basic possible copy/paste complete runnable example of using a custom class as the key for an unordered_map
(basic implementation of a sparse matrix):
// UnorderedMapObjectAsKey.cpp
#include <iostream>
#include <vector>
#include <unordered_map>
struct Pos
{
int row;
int col;
Pos() { }
Pos(int row, int col)
{
this->row = row;
this->col = col;
}
bool operator==(const Pos& otherPos) const
{
if (this->row == otherPos.row && this->col == otherPos.col) return true;
else return false;
}
struct HashFunction
{
size_t operator()(const Pos& pos) const
{
size_t rowHash = std::hash<int>()(pos.row);
size_t colHash = std::hash<int>()(pos.col) << 1;
return rowHash ^ colHash;
}
};
};
int main(void)
{
std::unordered_map<Pos, int, Pos::HashFunction> umap;
// at row 1, col 2, set value to 5
umap[Pos(1, 2)] = 5;
// at row 3, col 4, set value to 10
umap[Pos(3, 4)] = 10;
// print the umap
std::cout << "\n";
for (auto& element : umap)
{
std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
}
std::cout << "\n";
return 0;
}
I once wrote an unround tool, to find the minimal perturbation to a set of numbers to match a goal. It was a different problem, but one could in theory use a similar idea here. In this case, we have a set of choices.
Thus for the first element, we can either round it up to 14, or down to 13. The cost (in a binary integer programming sense) of doing so is less for the round up than the round down, because the round down requires we move that value a larger distance. Similarly, we can round each number up or down, so there are a total of 16 choices we must choose from.
13.626332
47.989636
9.596008
+ 28.788024
-----------
100.000000
I'd normally solve the general problem in MATLAB, here using bintprog, a binary integer programming tool, but there are only a few choices to be tested, so it is easy enough with simple loops to test out each of the 16 alternatives. For example, suppose we were to round this set as:
Original Rounded Absolute error
13.626 13 0.62633
47.99 48 0.01036
9.596 10 0.40399
+ 28.788 29 0.21198
---------------------------------------
100.000 100 1.25266
The total absolute error made is 1.25266. It can be reduced slightly by the following alternative rounding:
Original Rounded Absolute error
13.626 14 0.37367
47.99 48 0.01036
9.596 9 0.59601
+ 28.788 29 0.21198
---------------------------------------
100.000 100 1.19202
In fact, this will be the optimal solution in terms of the absolute error. Of course, if there were 20 terms, the search space will be of size 2^20 = 1048576. For 30 or 40 terms, that space will be of significant size. In that case, you would need to use a tool that can efficiently search the space, perhaps using a branch and bound scheme.
In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)
It's not because you are using alert, it will happen when use document.write() too. This problem generally arises when you name your id or class of any tag as same as any variable which you are using in you javascript code. Try by changing either the javascript variable name or by changing your tag's id/class name.
My code example: bank.html
<!doctype html>
<html>
<head>
<title>Transaction Tracker</title>
<script src="bank.js"></script>
</head>
<body>
<div><button onclick="bitch()">Press me!</button></div>
</body>
</html>
Javascript code: bank.js
function bitch(){ amt = 0;
var a = Math.random(); ran = Math.floor(a * 100);
return ran; }
function all(){
amt = amt + bitch(); document.write(amt + "
"); } setInterval(all,2000);
you can have a look and understand the concept from my code. Here i have used a variable named 'amt' in JS. You just try to run my code. It will work fine but as you put an [id="amt"](without square brackets) (which is a variable name in JS code )for div tag in body of html you will see the same error that you are talking about. So simple solution is to change either the variable name or the id or class name.
element.get_attribute('innerHTML')
The required SQL will be some like:-
SELECT * FROM cd
LEFT JOIN ab ON ab.sht = cd.sht
LEFT JOIN aa ON aa.sht = cd.sht
....
Hope it helps.
import os, time, datetime
file = "somefile.txt"
print(file)
print("Modified")
print(os.stat(file)[-2])
print(os.stat(file).st_mtime)
print(os.path.getmtime(file))
print()
print("Created")
print(os.stat(file)[-1])
print(os.stat(file).st_ctime)
print(os.path.getctime(file))
print()
modified = os.path.getmtime(file)
print("Date modified: "+time.ctime(modified))
print("Date modified:",datetime.datetime.fromtimestamp(modified))
year,month,day,hour,minute,second=time.localtime(modified)[:-3]
print("Date modified: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))
print()
created = os.path.getctime(file)
print("Date created: "+time.ctime(created))
print("Date created:",datetime.datetime.fromtimestamp(created))
year,month,day,hour,minute,second=time.localtime(created)[:-3]
print("Date created: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))
prints
somefile.txt
Modified
1429613446
1429613446.0
1429613446.0
Created
1517491049
1517491049.28306
1517491049.28306
Date modified: Tue Apr 21 11:50:46 2015
Date modified: 2015-04-21 11:50:46
Date modified: 21/04/2015 11:50:46
Date created: Thu Feb 1 13:17:29 2018
Date created: 2018-02-01 13:17:29.283060
Date created: 01/02/2018 13:17:29
It will work for both iphone and ipad
func showImagePicker() {
var alertStyle = UIAlertController.Style.actionSheet
if (UIDevice.current.userInterfaceIdiom == .pad) {
alertStyle = UIAlertController.Style.alert
}
let alert = UIAlertController(title: "", message: "Upload Attachment", preferredStyle: alertStyle)
alert.addAction(UIAlertAction(title: "Choose from gallery", style: .default , handler:{ (UIAlertAction) in
self.pickPhoto(sourceType: .photoLibrary)
}))
alert.addAction(UIAlertAction(title: "Take Photo", style: .default, handler:{ (UIAlertAction) in
self.pickPhoto(sourceType: .camera)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{ (UIAlertAction) in
}))
present(alert, animated: true, completion: nil)
}
for i in 0..max
puts "Value of local variable is #{i}"
end
projectDetailsController.controller('ProjectDetailsCtrl', function ($scope, $routeParams, $http) {
$http.get('data/projects.json').success(function(data) {
$scope.projects = data;
console.log(data);
for(var i = 0; i < data.length; i++) {
$scope.project = data[i];
if($scope.project.name === $routeParams.projectName) {
console.log('project-details',$scope.project);
return $scope.project;
}
}
});
});
Not sure if it's really good, but this was helpful for me.. I needed to use $scope to make it work properly.
Try this:
Just change:
compile 'com.android.support:appcompat-v7:26.0.0-beta2'
to:
compile 'com.android.support:appcompat-v7:26.0.0-beta1'
If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object
Ex:
import each from 'foreach-object';
const object = {
firstName: 'Arosha',
lastName: 'Sum',
country: 'Australia'
};
each(object, (value, key, object) => {
console.log(key + ': ' + value);
});
// Console log output will be:
// firstName: Arosha
// lastName: Sum
// country: Australia
Your data types are mismatched when you are retrieving the field values.
Also check how you store your enums, default is ORDINAL (numeric value stored in database), but STRING (name of enum stored in database) is also an option. Make sure the Entity in your code and the Model in your database are exactly the same.
I had an enum mismatch. It was set to default (ORDINAL) but the database model was expecting a string VARCHAR2(100char). Solution:
@Enumerated(EnumType.STRING)
I know this thread is old.... but I faced the same problem... If you are willing to use thread.join()
import threading
class test:
def __init__(self):
self.msg=""
def hello(self,bar):
print('hello {}'.format(bar))
self.msg="foo"
def main(self):
thread = threading.Thread(target=self.hello, args=('world!',))
thread.start()
thread.join()
print(self.msg)
g=test()
g.main()
As others recommend, you can use Oracle SQL Developer. You can point to the location of the script to run it, as described. A slightly simpler method, though, is to just use drag-and-drop:
You may use MessageBox
if you want but it is recommended to use alert
(from JavaScript) instead.
If you want to use it you should write:
System.Windows.Forms.MessageBox.Show("Test");
Note that you must specify the namespace.
Put String.Join
into an extension method. Here is the version I use, which is less verbose than Jordaos version.
""
when list is empty. Aggregate
would throw exception instead.Aggregate
String.Join()
Usage
var myStrings = new List<string>() { "a", "b", "c" };
var joinedStrings = myStrings.Join(","); // "a,b,c"
Extensionmethods class
public static class ExtensionMethods
{
public static string Join(this IEnumerable<string> texts, string separator)
{
return String.Join(separator, texts);
}
}
If you only want to sort only on the 5th field then use -k5,5
.
Also, use the -t
command line switch to specify the delimiter to tab
. Try this:
sort -k5,5 -r -n -t \t filename
or if the above doesn't work (with the tab
) this:
sort -k5,5 -r -n -t $'\t' filename
The man page for sort states:
-t, --field-separator=SEP use SEP instead of non-blank to blank transition
Finally, this SO question Unix Sort with Tab Delimiter might be helpful.
You can call
java -jar jenkins.war --help
to see a list of all available parameters.
I put everything into:
<location path="." inheritInChildApplications="false">
....
</location>
except: <configSections/>
, <connectionStrings/>
and <runtime/>
.
There are some cases when we don't want to inherit some secions from <configSections />
, but we can't put <section/>
tag into <location/>
, so we have to create a <secionGroup />
and put our unwanted sections into that group. Section groups can be later inserted into a location tag.
So we have to change this:
<configSections>
<section name="unwantedSection" />
</configSections>
Into:
<configSections>
<sectionGroup name="myNotInheritedSections">
<section name="unwantedSection" />
</sectionGroup>
</configSections>
<location path="." inheritInChildApplications="false">
<myNotInheritedSections>
<unwantedSection />
</myNotInheritedSections>
</location>
The one poit I've noticed to be "the double edged sword" is:
placing the logic in hands of non technical staff
I've seen this work great, when you have one or two multidisciplinary geniuses on the non technical side, but I've also seen the lack of technicity leading to bloat, more bugs, and in general 4x the development/maintenance cost.
Thus you need to consider your user-base seriously.
Execute following commands:
brew update
brew install openssl
echo 'export PATH="/usr/local/opt/openssl/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile
You will have the latest version of openssl installed and accessible from cli (command line/terminal). Since the third command will add export path to .bash_profile
, the newly installed version of openssl will be accessible across system restarts.
Here is what i tried to do to add parameter in the url which contain the specific character in the url.
jQuery('a[href*="google.com"]').attr('href', function(i,href) {
//jquery date addition
var requiredDate = new Date();
var numberOfDaysToAdd = 60;
requiredDate.setDate(requiredDate.getDate() + numberOfDaysToAdd);
//var convertedDate = requiredDate.format('d-M-Y');
//var newDate = datepicker.formatDate('yy/mm/dd', requiredDate );
//console.log(requiredDate);
var month = requiredDate.getMonth()+1;
var day = requiredDate.getDate();
var output = requiredDate.getFullYear() + '/' + ((''+month).length<2 ? '0' : '') + month + '/' + ((''+day).length<2 ? '0' : '') + day;
//
Working Example Click
You could use logging libraries instead of re-inventing the wheel. Log4j for instance will provide methods for different messages like info()
, warn()
and error()
.
or simply make a println
method of your own and call it:
void println(Object line) {
System.out.println(line);
}
println("Hello World");
IntelliJ IDEA and NetBeans:
you type sout
then press TAB, and it types System.out.println()
for you, with the cursor in the right place.
Eclipse:
Type syso
then press CTRL + SPACE.
Other
Find a "snippets" plugin for your favorite text editor/IDE
import static java.lang.System.out;
out.println("Hello World");
println("Hello, World!")
println "Hello, World!"
print "Hello, World!"
puts "Hello, World!"
(println "Hello, World!")
print('Hello, World!');
Use:
Class<?> typeOfTheList = aListWithTypeSpiderMan.toArray().getClass().getComponentType();
autoscroll
will be defined and modified in the controller:
<span ng-class= "autoscroll?'class_if_true':'class_if_false'"></span>
Add multiple classes based on condition by:
<span ng-class= "autoscroll?'first second third':'classes_if_false'"></span>
Actually, you should use several tools to get a bulletproof approach:
DIR_PATH=`readlink -f "${the_stuff_you_test}"` # Get rid of symlinks and get abs path
if [[ -d "${DIR_PATH}" ]] ; Then # Now you're testing
echo "It's a dir";
fi
There isn't any need to worry about spaces and special characters as long as you use "${}"
.
Note that [[]]
is not as portable as []
, but since most people work with modern versions of Bash (since after all, most people don't even work with command line :-p), the benefit is greater than the trouble.
"A requires a peer of B but none was installed". Consider it as "A requires one of B's peers but that peer was not installed and we're not telling you which of B's peers you need."
The automatic installation of peer dependencies was explicitly removed with npm 3.
So you cannot install peer dependencies automatically with npm 3 and upwards.
Updated Solution:
Use following for each peer dependency to install that and remove the error
npm install --save-dev xxxxx
Deprecated Solution:
You can use npm-install-peers to find and install required peer dependencies.
npm install -g npm-install-peers
npm-install-peers
If you are getting this error after updating any package's version then remove node_modules
directory and reinstall packages by npm install
or npm cache clean
and npm install
.
This is not bullet but you can consider it. As there is nothing like big dot.
I used below symbol in the description and its working fine.
? Black Circle
New Moon
Full Moon
Diamond With a Dot
Small Orange Diamond
? Gear
Black Flag
White Flag
? Play Button
? Fast-Forward Button
? Heavy Large Circle
? Eight-Pointed Star
? Black Medium Square
? White Medium-Small Square
? Black Medium-Small Square
? Black Large Square
You just need to copy and paste it over description. Below is the result.
You can use the mixin make-col-ready
and set the gutter width to zero:
@include make-col-ready(0);
In the Web Developer Toolbar, have you tried the Tools -> Validate HTML
or Tools -> Validate Local HTML
options?
The Validate HTML
option sends the url to the validator, which works well with publicly facing sites. The Validate Local HTML
option sends the current page's HTML to the validator, which works well with pages behind a login, or those that aren't publicly accessible.
You may also want to try View Source Chart (also as FireFox add-on). An interesting note there:
Q. Why does View Source Chart change my XHTML tags to HTML tags?
A. It doesn't. The browser is making these changes, VSC merely displays what the browser has done with your code. Most common: self closing tags lose their closing slash (/). See this article on Rendered Source for more information (archive.org).
go to the master branch our-team
pull all the new changes from our-team
branch
go to your branch featurex
featurex
merge the changes of our-team
branch into featurex
branch
our-team
{commit-hash}
if you want to merge specific commitspush your changes with the changes of our-team
branch
Note: probably you will have to fix conflicts after merging our-team
branch into featurex
branch before pushing
You can access the index attribute of a df using df.index[i]
>> import pandas as pd
>> import numpy as np
>> df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
a b
0 0 1.088998
1 1 -1.381735
2 2 0.035058
3 3 -2.273023
4 4 1.345342
>> df.index[1] ## Second index
>> df.index[-1] ## Last index
>> for i in xrange(len(df)):print df.index[i] ## Using loop
...
0
1
2
3
4
It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:
#include <iostream>
using namespace std;
int main()
{
int pause;
struct Customer
{
int uid;
string name;
};
Customer customerRecords[2];
customerRecords[0] = {25, "Bob Jones"};
customerRecords[1] = {26, "Jim Smith"};
cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
cin >> pause;
return 0;
}
This would definitely help Many!
private void axWindowsMediaPlayer1_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e)
{
if(e.nButton==2)
{
contextMenuStrip1.Show(MousePosition);
}
}
[ e.nbutton==2 ] is like [ e.button==MouseButtons.Right ]
transient
is the solution for me. thanks! it's native to Java and avoids you to add another framework-specific annotation.
TO ADD: @Christopher's answer does not work on API 7/8 (as per @Jonny's correct comment) IF you are using colours, instead of drawables. (In my testing, using drawables as per Christopher works fine)
Here is the FIX for 2.3 and below when using colours:
As per @Charles Harley, there is a bug in 2.3 and below where filling the list item with a colour causes the colour to flow out over the whole list. His fix is to define a shape
drawable containing the colour you want, and to use that instead of the colour.
I suggest looking at this link if you want to just use a colour as selector, and are targeting Android 2 (or at least allow for Android 2).
Actually MySQL provide a lot of easy to use function in daily life without more effort from user side-
NOW() it produce date and time both in current scenario whereas CURDATE() produce date only, CURTIME() display time only, we can use one of them according to our need with CAST or merge other calculation it, MySQL rich in these type of function.
NOTE:- You can see the difference using query select NOW() as NOWDATETIME, CURDATE() as NOWDATE, CURTIME() as NOWTIME ;
Adding my that also cleans out the name of nodes that have namespace prefixes:
public static string RemoveAllNamespaces(XElement element)
{
string tex = element.ToString();
var nsitems = element.DescendantsAndSelf().Select(n => n.ToString().Split(' ', '>')[0].Split('<')[1]).Where(n => n.Contains(":")).DistinctBy(n => n).ToArray();
//Namespace prefix on nodes: <a:nodename/>
tex = nsitems.Aggregate(tex, (current, nsnode) => current.Replace("<"+nsnode + "", "<" + nsnode.Split(':')[1] + ""));
tex = nsitems.Aggregate(tex, (current, nsnode) => current.Replace("</" + nsnode + "", "</" + nsnode.Split(':')[1] + ""));
//Namespace attribs
var items = element.DescendantsAndSelf().SelectMany(d => d.Attributes().Where(a => a.IsNamespaceDeclaration || a.ToString().Contains(":"))).DistinctBy(o => o.Value);
tex = items.Aggregate(tex, (current, xAttribute) => current.Replace(xAttribute.ToString(), ""));
return tex;
}
Based on this blog, one could share a docker image without a docker registry by executing:
docker save --output latestversion-1.0.0.tar dockerregistry/latestversion:1.0.0
Once this command has been completed, one could copy the image to a server and import it as follows:
docker load --input latestversion-1.0.0.tar
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
This is a method that works based on the text of the option, not the index. Just tested.
var theText = "GOOGLE";
$("#HowYouKnow option:contains(" + theText + ")").attr('selected', 'selected');
Or, if there are similar values (thanks shanabus):
$("#HowYouKnow option").each(function() {
if($(this).text() == theText) {
$(this).attr('selected', 'selected');
}
});
I think you should consider using IO.binread("/path/to/file")
if you have a recent ruby interpreter (i.e. >= 1.9.2)
You could find IO
class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html
package isevenodd;
import java.util.Scanner;
public class IsEvenOdd {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter number: ");
int y = scan.nextInt();
boolean isEven = (y % 2 == 0) ? true : false;
String x = (isEven) ? "even" : "odd";
System.out.println("Your number is " + x);
}
}
You can't use Microsoft.Office.Interop.Excel without having ms office installed.
Just search in google for some libraries, which allows to modify xls or xlsx:
Found this by searching for "linux output formatted columns".
http://www.unix.com/shell-programming-scripting/117543-formatting-output-columns.html
For your needs, it's like:
awk '{ printf "%-20s %-40s\n", $1, $2}'
Note : This answer is now out-of-date. This changes the theme in "preview" only as @imjohnking and @john-ktejik pointed out. As @Shahzeb mentioned, theme can modified in res>values>styles
Android Studio 0.8.2 provides a slightly easier way to change the theme. In the preview window, you can select the theme of "Holo.Light.DarkActionBar" by clicking on the theme combo box just above the phone.
Or do a ctrl + click on the @style/AppTheme in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.
When using the Support Library, you must instead use the Theme.AppCompat themes:
Source http://forums.udacity.com/questions/100200635/choosing-theme-in-android-studio-08x
In Java 8 and JUnit 5 (Jupiter) we can assert for exceptions as follows.
Using org.junit.jupiter.api.Assertions.assertThrows
public static < T extends Throwable > T assertThrows(Class< T > expectedType, Executable executable)
Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.
If no exception is thrown, or if an exception of a different type is thrown, this method will fail.
If you do not want to perform additional checks on the exception instance, simply ignore the return value.
@Test
public void itShouldThrowNullPointerExceptionWhenBlahBlah() {
assertThrows(NullPointerException.class,
()->{
//do whatever you want to do here
//ex : objectName.thisMethodShoulThrowNullPointerExceptionForNullParameter(null);
});
}
That approach will use the Functional Interface Executable
in org.junit.jupiter.api
.
Refer :
I don't know whether this has appeared obvious here. I would like to point out that as far as client-side (browser) JavaScript is concerned, you can add type="module"
to both external as well as internal js scripts.
Say, you have a file 'module.js':
var a = 10;
export {a};
You can use it in an external script, in which you do the import, eg.:
<!DOCTYPE html><html><body>
<script type="module" src="test.js"></script><!-- Here use type="module" rather than type="text/javascript" -->
</body></html>
test.js:
import {a} from "./module.js";
alert(a);
You can also use it in an internal script, eg.:
<!DOCTYPE html><html><body>
<script type="module">
import {a} from "./module.js";
alert(a);
</script>
</body></html>
It is worthwhile mentioning that for relative paths, you must not omit the "./" characters, ie.:
import {a} from "module.js"; // this won't work
To write it with a while loop you can do:
ls -f /var | while read -r file; do cmd $file; done
The primary disadvantage of this is that cmd is run in a subshell, which causes some difficulty if you are trying to set variables. The main advantages are that the shell does not need to load all of the filenames into memory, and there is no globbing. When you have a lot of files in the directory, those advantages are important (that's why I use -f on ls; in a large directory ls itself can take several tens of seconds to run and -f speeds that up appreciably. In such cases 'for file in /var/*' will likely fail with a glob error.)
to get this working for a date error I had to delete the error first before calling $setValidity for the form to be marked valid.
delete currentmodal.form.$error.date;
currentmodal.form.$setValidity('myDate', true);
Are you sure you're using the correct proxy as system properties?
Also if you are using 1.5 or 1.6 you could pass a java.net.Proxy instance to the openConnection() method. This is more elegant imo:
//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);
How about either of:
>>> df
date duration user_id
0 2013-04-01 30 0001
1 2013-04-01 15 0001
2 2013-04-01 20 0002
3 2013-04-02 15 0002
4 2013-04-02 30 0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
>>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})
duration user_id
date
2013-04-01 65 2
2013-04-02 45 1
In my case I'm in wrong directory,
My directory Path
eCommerce-shop/eCommerce
I am in inside eCommerce-shop and executing this command composer intsall so that't it throwing this error.
Make sure that your file has .cpp extension and not .c, I just had this problem
I believe what you're looking for is:
// ...inside the render() function
var size = 3;
var items = list.slice(0, size).map(i => {
return <myview item={i} key={i.id} />
}
return (
<div>
{items}
</div>
)
select * from mytable where year(Columnx) = 2010
Regarding index usage (answering Simon's comment):
if you have an index on Columnx, SQLServer WON'T use it if you use the function "year" (or any other function).
There are two possible solutions for it, one is doing the search by interval like Columnx>='01012010' and Columnx<='31122010' and another one is to create a calculated column with the year(Columnx) expression, index it, and then do the filter on this new column
I see in your code that you are trying to pass an ARRAY to POST action. In that case follow below working code -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
function submitForm() {
var roles = ["role1", "role2", "role3"];
jQuery.ajax({
type: "POST",
url: "@Url.Action("AddUser")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(roles),
success: function (data) { alert(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
<input type="button" value="Click" onclick="submitForm()"/>
And the controller action is going to be -
public ActionResult AddUser(List<String> Roles)
{
return null;
}
Then when you click on the button -
you can use category. set padding to left and right
UITextField+Padding.h
@interface UITextField (Padding)
@property (nonatomic, assign) CGFloat paddingValue;
@property (nonatomic, assign) CGFloat leftPadding;
@property (nonatomic, assign) CGFloat rightPadding;
//overwrite
-(CGRect)textRectForBounds:(CGRect)bounds;
-(CGRect)editingRectForBounds:(CGRect)bounds;
@end
UITextField+Padding.m
#import "UITextField+Padding.h"
#import <objc/runtime.h>
static char TAG_LeftPaddingKey;
static char TAG_RightPaddingKey;
static char TAG_Left_RightPaddingKey;
@implementation UITextField (Padding)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
-(CGRect)textRectForBounds:(CGRect)bounds {
CGFloat offset_Left=0;
CGFloat offset_Right=0;
if (self.paddingValue>0) {
offset_Left=self.paddingValue;
offset_Right=offset_Left;
}else{
if (self.leftPadding>0){
offset_Left=self.leftPadding;
}
if (self.rightPadding>0){
offset_Right=self.rightPadding;
}
}
if (offset_Left>0||offset_Right>0) {
return CGRectMake(bounds.origin.x+ offset_Left ,bounds.origin.y ,
bounds.size.width- (offset_Left+offset_Right), bounds.size.height-2 );
}else{
return bounds;
}
}
-(CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
#pragma clang diagnostic pop
#pragma maek -setter&&getter
- (CGFloat)paddingValue
{
return [objc_getAssociatedObject(self,&TAG_Left_RightPaddingKey) floatValue];
}
-(void)setPaddingValue:(CGFloat)paddingValue
{
objc_setAssociatedObject(self, &TAG_Left_RightPaddingKey, @(paddingValue), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(CGFloat)leftPadding
{
return [objc_getAssociatedObject(self,&TAG_LeftPaddingKey) floatValue];
}
-(void)setLeftPadding:(CGFloat)leftPadding
{
objc_setAssociatedObject(self, &TAG_LeftPaddingKey, @(leftPadding), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(CGFloat)rightPadding
{
return [objc_getAssociatedObject(self,&TAG_RightPaddingKey) floatValue];
}
-(void)setRightPadding:(CGFloat)rightPadding
{
objc_setAssociatedObject(self, &TAG_RightPaddingKey, @(rightPadding), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
you can set padding like this self.phoneNumTF.paddingValue=10.f; or self.phoneNumTF.leftPadding=10.f;
This is easily the simplest solution. For those who don't know how to do this:
Install the C++ compiler https://visualstudio.microsoft.com/downloads/#build-tools-for-visual-studio-2019
Go to the installation folder (In my case it is): C:\Program Files (x86)\Microsoft Visual C++ Build Tools
Open Visual C++ 2015 x86 x64 Cross Build Tools Command Prompt
Type: pip install package_name
Looks like that is the best way to do it:
String first = strs.iterator().next();
Great question... At first, it seems like an oversight for the Collection
interface.
Note that "first" won't always return the first thing you put in the collection, and may only make sense for ordered collections. Maybe that is why there isn't a get(item)
call, since the order isn't necessarily preserved.
While it might seem a bit wasteful, it might not be as bad as you think. The Iterator
really just contains indexing information into the collection, not a usually a copy of the entire collection. Invoking this method does instantiate the Iterator
object, but that is really the only overhead (not like copying all the elements).
For example, looking at the type returned by the ArrayList<String>.iterator()
method, we see that it is ArrayList::Itr
. This is an internal class that just accesses the elements of the list directly, rather than copying them.
Just be sure you check the return of iterator()
since it may be empty or null
depending on the implementation.
The following shorter version opens fine in Excel, maybe your issue was the trailing comma
StringBuilder sb = new StringBuilder();
string[] columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName).
ToArray();
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
string[] fields = row.ItemArray.Select(field => field.ToString()).
ToArray();
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText("test.csv", sb.ToString());
And as Tim pointed out, if you are on .net>=4, you can make it even shorter:
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().
Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
sb.AppendLine(string.Join(",", fields));
}
File.WriteAllText("test.csv", sb.ToString());
As suggested by Christian, if you want to handle special characters escaping in fields, replace the loop block by:
foreach (DataRow row in dt.Rows)
{
IEnumerable<string> fields = row.ItemArray.Select(field =>
string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
sb.AppendLine(string.Join(",", fields));
}
And last suggestion, you could write the csv content line by line instead of as a whole document, to avoid having a big document in memory.
int rows = 5;
int cols = 10;
int[] multD = new int[rows * cols];
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
int index = r * cols + c;
multD[index] = index * 2;
}
}
Enjoy!
Another related tip is to use "%~1" instead of "%1". Type "CALL /?" at the command line in Windows to get more details.
They don't really have any formal meaning. A folder is a folder to SVN. They are a generally accepted way to organize your project.
The trunk is where you keep your main line of developmemt. The branch folder is where you might create, well, branches, which are hard to explain in a short post.
A branch is a copy of a subset of your project that you work on separately from the trunk. Maybe it's for experiments that might not go anywhere, or maybe it's for the next release, which you will later merge back into the trunk when it becomes stable.
And the tags folder is for creating tagged copies of your repository, usually at release checkpoints.
But like I said, to SVN, a folder is a folder. branch
, trunk
and tag are just a convention.
I'm using the word 'copy' liberally. SVN doesn't actually make full copies of things in the repository.
It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.
However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.
Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.
Use a list instead and replace your foreach
loop with a for
loop:
@model IList<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
@Html.HiddenFor(x => x[i].IP)
@Html.CheckBoxFor(x => x[i].Checked)
</td>
<td>
@Html.DisplayFor(x => x[i].IP)
</td>
</tr>
}
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
Alternatively you could use an editor template:
@model IEnumerable<BlockedIPViewModel>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
@Html.EditorForModel()
<div>
<input type="submit" value="Unblock IPs" />
</div>
}
and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml
which will automatically be rendered for each element of the collection:
@model BlockedIPViewModel
<tr>
<td>
@Html.HiddenFor(x => x.IP)
@Html.CheckBoxFor(x => x.Checked)
</td>
<td>
@Html.DisplayFor(x => x.IP)
</td>
</tr>
The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article
.
Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.
table-layout: fixed
will get force the cells to fit the table (and not the other way around), e.g.:
<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
table-layout: fixed;">
<tr>
<td>
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
</td>
</tr>
</table>
just bind handler normally and then run:
element.data('events').action.reverse();
so for example:
$('#mydiv').data('events').click.reverse();
First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.
In my case, I found (after much hair-pulling) that the "pending" status was caused by the AdBlock extension. The image that I couldn't get to load had the word "ad" in the URL, so AdBlock kept it from loading.
Disabling AdBlock fixes this issue.
Renaming the file so that it doesn't contain "ad" in the URL also fixes it, and is obviously a better solution. Unless it's an advertisement, in which case you should leave it like that. :)
Writing this answer for people who wants to get a file to download with specific content from javascript. I was struggling with the same thing.
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN
This will handle paths with spaces:
find ./ -type f -name "*.php" -o -name "*.html" -exec tar uvf myarchives.tar {} +
$cfg['Servers'][$i]['AllowNoPassword'] = false;
Operators Overloadability
+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.
+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.
==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.
&&, || They can't be overloaded
() (Conversion operator) They can't be overloaded
+=, -=, *=, /=, %= These compound assignment operators can be
overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.
=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded
[ ] Can be overloaded but not always!
For bracket:
public Object this[int index]
{
}
The array indexing operator cannot be overloaded; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).
From MSDN
Have a look at this code:
HTML:
<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>
JS:
$('.multiple-elements').each(
function(index, element) {
$(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color
}
);
this
refers to the current element that the DOM engine is sort of working on, or referring to.
Another example:
<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>
Hope you understand now. The this
keyword occurs while dealing with object oriented systems, or as we have in this case, element oriented systems :)
In my case, I ran pip show virtualenv
to get the information about virtualenv package. I will look similar to this and will also show location of the package:
user@machine:~$ pip show virtualenv
Name: virtualenv
Version: 16.2.0
Summary: Virtual Python Environment builder
Home-page: https://virtualenv.pypa.io/
Author: Ian Bicking
Author-email: [email protected]
License: MIT
Location: /home/user/.local/lib/python3.6/site-packages
Requires: setuptools
From that grab the part of location up to the .local
part, which in this case is /home/user/.local/
. You can find virtualenv command under /home/user/.local/bin/virtualenv
.
You can then run commands like /home/user/.local/bin/virtualenv newvirtualenv
.
I found a solution wich is to do:
<span class="visible-sm"> your code without col </span>
<span class="visible-xs"> your code with col </span>
It's not very optimized but it works. Did you find something better? It really miss a class like col-sm-0 to apply colons just to the xs size...
Default rounding in python and numpy:
In: [round(i) for i in np.arange(10) + .5]
Out: [0, 2, 2, 4, 4, 6, 6, 8, 8, 10]
I used this to get integer rounding to be applied to a pandas series:
import decimal
and use this line to set the rounding to "half up" a.k.a rounding as taught in school:
decimal.getcontext().rounding = decimal.ROUND_HALF_UP
Finally I made this function to apply it to a pandas series object
def roundint(value):
return value.apply(lambda x: int(decimal.Decimal(x).to_integral_value()))
So now you can do roundint(df.columnname)
And for numbers:
In: [int(decimal.Decimal(i).to_integral_value()) for i in np.arange(10) + .5]
Out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Credit: kares
the best you export it as sql file and open it with editor such as visual studio code and find and repalace your words. i replace in 1 gig file sql in 1 minutes for 16 word that total is 14600 word. its the best way. and after replace it save and import it again. do not forget compress it with zip for import.
declare this
var intro;
outside of $(document).ready()
because, $(document).ready()
will hide your variable from global scope.
Code
var intro;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
Another way:
window.intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
window.intro = true;
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function(){
if(this.checked) {
window.intro = false;
$('.enabled').removeClass('enabled').addClass('disabled');
} else {
window.intro = true;
if($('.intro').exists()) {
$('.disabled').removeClass('disabled').addClass('enabled');
} else {
$('.intro').wrap('<div class="disabled"></div>');
}
}
});
});
console.log(intro);
outside of DOM ready function (currently you've) will log undefined
, but within DOM ready it will give you true/ false.
console.log
execute before DOM ready execute, because DOM ready execute after all resource appeared to DOM i.e after DOM is prepared, so I think you'll always get absurd result.I need to use it outside of DOM ready function
You can use following approach:
var intro = undefined;
$(document).ready(function() {
if ($('.intro_check').is(':checked')) {
intro = true;
introCheck();
$('.intro').wrap('<div class="disabled"></div>');
};
$('.intro_check').change(function() {
if (this.checked) {
intro = true;
} else {
intro = false;
}
introCheck();
});
});
function introCheck() {
console.log(intro);
}
After change the value of intro
I called a function that will fire with new value of intro
.
The following are possible issues:
The most likely one is that the Security Group is not configured properly to provide SSH access on port 22 to your i.p. Change in security setting does not require a restart of server for it to be effective but need to wait a few minutes for it to be applicable.
The local firewall configuration does not allow SSH access to the server. ( you can try a different internet connection, your phone/dongle to try it)
The server is not started properly ( then the access checks will fail even on the amazon console), in which case you would need to stop and start the server.
You can use boost::array to do that:
boost::array<char, 5> test = {'a', 'b', 'c', 'd', 'e'};
std::vector<boost::array<char, 5> > v;
v.push_back(test);
Edit:
Or you can use a vector of vectors as shown below:
char test[] = {'a', 'b', 'c', 'd', 'e'};
std::vector<std::vector<char> > v;
v.push_back(std::vector<char>(test, test + sizeof(test)/ sizeof(test[0])));
If you want, you can use the "define" function, but this function creates a constant which can't be changed once defined.
<?php
define("GREETING", "Welcome to W3Schools.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
I wonder if you could write a custom rule for Fiddler to do what you want? IE uses no proxy, Firefox points to Fiddler, Fiddler uses custom rule to direct requests to the dev server...
To add to the other answers: If yout want the 0000-00-00
string, you can use noDatetimeStringSync=true
(with the caveat of sacrificing timezone conversion).
The official MySQL bug: https://bugs.mysql.com/bug.php?id=47108.
Also, for history, JDBC used to return NULL
for 0000-00-00
dates but now return an exception by default.
Source
Since you are using textarea
, you may find \n or \r (or \r\n) for line breaks. So, the following is suggested:
$('#keywords').val().split(/\r|\n/)
try this
public void VolleyPostReqWithResponseListenerwithHeaders(String URL,final Map<String, String> params,final Map<String, String> headers,Response.Listener<String> responseListener) {
String url = URL;
Log.i("url:", ":" + url);
StringRequest mStringRequest = new StringRequest(Request.Method.POST,
url, responseListener, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
//Log.d("Error.Response", error.getLocalizedMessage());
}
}){
@Override
protected Map<String, String> getParams() {
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
};
mStringRequest.setRetryPolicy(new DefaultRetryPolicy(
60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
mStringRequest.setShouldCache(true);
// dialog.show();
SingletonRequestQueue.getInstance(context).addToRequestQueue(mStringRequest);
}
If you define classproperty
as follows, then your example works exactly as you requested.
class classproperty(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, owner):
return self.f(owner)
The caveat is that you can't use this for writable properties. While e.I = 20
will raise an AttributeError
, Example.I = 20
will overwrite the property object itself.
You have to use ':' colon instead of ';' semicolon.
As it stands now you try to execute the jar file which has not the execute bit set, hence the Permission denied.
And the variable must be CLASSPATH not classpath.
Most of the solutions here count the amount of commits you'd like to go back. I think this is an error prone methodology. Counting would require recounting.
You can simply pass the commit hash of the commit you want to be at HEAD or in other words, the commit you'd like to be the last commit via:
(Notice see commit hash)
To avoid this:
1) git checkout master
2) git branch <feature branch> master
3) git reset --hard <commit hash>
4) git push -f origin master
Would something like this work:
In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]:
func2 func1
dummy
1 -4.263768e-16 -0.188565
select persons.personsid,name,info.id,address
-> from persons
-> inner join persons on info.infoid = info.info.id;
You can use wc -l
to figure out the total # of lines.
You can then combine head
and tail
to get at the range you want. Let's assume the log is 40,000 lines, you want the last 1562 lines, then of those you want the first 838. So:
tail -1562 MyHugeLogFile.log | head -838 | ....
Or there's probably an easier way using sed
or awk
.
You can use the Unix-style -l
switch – typically terse and cryptic – or the equivalent --files-with-matches
– longer and more readable.
The output of grep --help
is not easy to read, but it's there:
-l, --files-with-matches print only names of FILEs containing matches
Programming Language: PHP
// Inintialize URL to the variable
$url = 'https://www.youtube.com/watch?v=qnMxsGeDz90';
// Use parse_url() function to parse the URL
// and return an associative array which
// contains its various components
$url_components = parse_url($url);
// Use parse_str() function to parse the
// string passed via URL
parse_str($url_components['query'], $params);
// Display result
echo 'v parameter value is '.$params['v'];
This worked for me. I hope, it will also help you :)
I highly recommend the book "Pro Git" by Scott Chacon. Take time and really read it, while exploring an actual git repo as you do.
HEAD: the current commit your repo is on. Most of the time HEAD
points to the latest commit in your current branch, but that doesn't have to be the case. HEAD
really just means "what is my repo currently pointing at".
In the event that the commit HEAD
refers to is not the tip of any branch, this is called a "detached head".
master: the name of the default branch that git creates for you when first creating a repo. In most cases, "master" means "the main branch". Most shops have everyone pushing to master, and master is considered the definitive view of the repo. But it's also common for release branches to be made off of master for releasing. Your local repo has its own master branch, that almost always follows the master of a remote repo.
origin: the default name that git gives to your main remote repo. Your box has its own repo, and you most likely push out to some remote repo that you and all your coworkers push to. That remote repo is almost always called origin, but it doesn't have to be.
HEAD
is an official notion in git. HEAD
always has a well-defined meaning. master
and origin
are common names usually used in git, but they don't have to be.
If you want to do multiple (3+) columns here is a great snippet that works perfectly and validates as valid HTML5:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Multiple Colums</title>
<!-- Styles -->
<style>
.flex-center {
width: 100%;
align-items: center;/*These two properties center vetically*/
height: 100vh;/*These two properties center vetically*/
display: flex;/*This is the attribute that separates into columns*/
justify-content: center;
text-align: center;
position: relative;
}
.spaceOut {
margin-left: 25px;
margin-right: 25px;
}
</style>
</head>
<body>
<section class="flex-center">
<h4>Tableless Columns Example</h4><br />
<div class="spaceOut">
Column 1<br />
</div>
<div class="spaceOut">
Column 2<br />
</div>
<div class="spaceOut">
Column 3<br />
</div>
<div class="spaceOut">
Column 4<br />
</div>
<div class="spaceOut">
Column 5<br />
</div>
</section>
</body>
</html>
Simply Use Jquery/Javascript trick to add an empty div:
if($('.exposegrid').length%3==2){
$(".exposegrid").append('<div class="exposetab"></div>');
}
Set the highlighted properties. Set MaximimSize and MinimizeSize properties the same size
Your problem is because of the way the icon has been made - it doesn't conform to Apple's custom tab bar icon specs:
To design a custom bar icon, follow these guidelines:
(From the guidelines.)
Something that would be possible looks like this. You can find such icons on most free tab bar icon sites.
Just set the last value of the enum to a value large enough to make it the size you would like the enum to be, it should then be that size:
enum value{a=0,b,c,d,e,f,g,h,i,j,l,m,n,last=0xFFFFFFFFFFFFFFFF};
Your code below is zooming the map to fit the specified bounds:
addMarker(27.703402,85.311668,'New Road');
center = bounds.getCenter();
map.fitBounds(bounds);
If you only have 1 marker and add it to the bounds, that results in the closest zoom possible:
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
}
If you keep track of the number of markers you have "added" to the map (or extended the bounds with), you can only call fitBounds if that number is greater than one. I usually push the markers into an array (for later use) and test the length of that array.
If you will only ever have one marker, don't use fitBounds. Call setCenter
, setZoom
with the marker position and your desired zoom level.
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(your desired zoom);
}
html,
body,
#map {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
}
_x000D_
<html>
<head>
<script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk" type="text/javascript"></script>
<script type="text/javascript">
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
var center = null;
var map = null;
var currentPopup;
var bounds = new google.maps.LatLngBounds();
function addMarker(lat, lng, info) {
var pt = new google.maps.LatLng(lat, lng);
map.setCenter(pt);
map.setZoom(5);
var marker = new google.maps.Marker({
position: pt,
icon: icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: info,
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
addMarker(27.703402, 85.311668, 'New Road');
// center = bounds.getCenter();
// map.fitBounds(bounds);
}
</script>
</head>
<body onload="initMap()" style="margin:0px; border:0px; padding:0px;">
<div id="map"></div>
</body>
</html>
_x000D_
You can use the sequence method list.extend
to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.
>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
So you can use list.append()
to append a single value, and list.extend()
to append multiple values.
If you want to insert the value of any checkbox immediately as it is being checked then this should work for you:
$(":checkbox").click(function(){
$("#id").text(this.value)
})
axios({
method: 'post', //put
url: url,
headers: {'Authorization': 'Bearer'+token},
data: {
firstName: 'Keshav', // This is the body part
lastName: 'Gera'
}
});
Regarding the technique of pulling build date/version info from the bytes of an assembly PE header, Microsoft has changed the default build parameters beginning with Visual Studio 15.4. The new default includes deterministic compilation, which makes a valid timestamp and automatically incremented version numbers a thing of the past. The timestamp field is still present but it gets filled with a permanent value that is a hash of something or other, but not any indication of the build time.
For those who prioritize a useful timestamp over deterministic compilation, there is a way to override the new default. You can include a tag in the .csproj file of the assembly of interest as follows:
<PropertyGroup>
...
<Deterministic>false</Deterministic>
</PropertyGroup>
Update: I endorse the T4 text template solution described in another answer here. I used it to solve my issue cleanly without losing the benefit of deterministic compilation. One caution about it is that Visual Studio only runs the T4 compiler when the .tt file is saved, not at build time. This can be awkward if you exclude the .cs result from source control (since you expect it to be generated) and another developer checks out the code. Without resaving, they won't have the .cs file. There is a package on nuget (I think called AutoT4) that makes T4 compilation part of every build. I have not yet confronted the solution to this during production deployment, but I expect something similar to make it right.
var myTable = $('#tblIdName').DataTable(); myTable.clear().rows.add(myTable.data).draw();
This worked for me without using ajax.
SELECT *
FROM Contacts
WHERE ContactId IN
(SELECT a.ContactID
FROM
(SELECT ContactId, Replace(Postcode, ' ', '') AS P
FROM Contacts
WHERE Postcode LIKE '%N%W%1%0%1%') a
WHERE a.P LIKE 'NW101%')
Based on zenpoy's answer:
import Image
import numpy
def image2pixelarray(filepath):
"""
Parameters
----------
filepath : str
Path to an image file
Returns
-------
list
A list of lists which make it simple to access the greyscale value by
im[y][x]
"""
im = Image.open(filepath).convert('L')
(width, height) = im.size
greyscale_map = list(im.getdata())
greyscale_map = numpy.array(greyscale_map)
greyscale_map = greyscale_map.reshape((height, width))
return greyscale_map
If anyone came here looking for a simple method to scale/resize an image in Python, without using additional libraries, here's a very simple image resize function:
#simple image scaling to (nR x nC) size
def scale(im, nR, nC):
nR0 = len(im) # source number of rows
nC0 = len(im[0]) # source number of columns
return [[ im[int(nR0 * r / nR)][int(nC0 * c / nC)]
for c in range(nC)] for r in range(nR)]
Example usage: resizing a (30 x 30) image to (100 x 200):
import matplotlib.pyplot as plt
def sqr(x):
return x*x
def f(r, c, nR, nC):
return 1.0 if sqr(c - nC/2) + sqr(r - nR/2) < sqr(nC/4) else 0.0
# a red circle on a canvas of size (nR x nC)
def circ(nR, nC):
return [[ [f(r, c, nR, nC), 0, 0]
for c in range(nC)] for r in range(nR)]
plt.imshow(scale(circ(30, 30), 100, 200))
This works to shrink/scale images, and works fine with numpy arrays.
I know this doesn't really answer your question, but different View Engines have different purposes. The Spark View Engine, for example, aims to rid your views of "tag soup" by trying to make everything fluent and readable.
Your best bet would be to just look at some implementations. If it looks appealing to the intent of your solution, try it out. You can mix and match view engines in MVC, so it shouldn't be an issue if you decide to not go with a specific engine.
I also played with this, discovering that redirecting output worked, but I never saw output to the console window, which is present for every windows application. This is my solution so far, until I find a Qt replacement for ShowWindow and GetConsoleWindow.
Run this from a command prompt without parameters - get the window. Run from command prompt with parameters (eg. cmd aaa bbb ccc) - you get the text output on the command prompt window - just as you would expect for any Windows console app.
Please excuse the lame example - it represents about 30 minutes of tinkering.
#include "mainwindow.h"
#include <QTextStream>
#include <QCoreApplication>
#include <QApplication>
#include <QWidget>
#include <windows.h>
QT_USE_NAMESPACE
int main(int argc, char *argv[])
{
if (argc > 1) {
// User has specified command-line arguments
QCoreApplication a(argc, argv);
QTextStream out(stdout);
int i;
ShowWindow (GetConsoleWindow(),SW_NORMAL);
for (i=1; i<argc; i++)
out << i << ':' << argv [i] << endl;
out << endl << "Hello, World" << endl;
out << "Application Directory Path:" << a.applicationDirPath() << endl;
out << "Application File Path:" << a.applicationFilePath() << endl;
MessageBox (0,(LPCWSTR)"Continue?",(LPCWSTR)"Silly Question",MB_YESNO);
return 0;
} else {
QApplication a(argc, argv);
MainWindow w;
w.setWindowTitle("Simple example");
w.show();
return a.exec();
}
}
document.ondomcontentready=function(){}
should do the trick, but it doesn't have full browser compatibility.
Seems like you should just use jQuery min
You can use Record
for this:
https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt
Example (A mapping between AppointmentStatus enum and some meta data):
const iconMapping: Record<AppointmentStatus, Icon> = {
[AppointmentStatus.Failed]: { Name: 'calendar times', Color: 'red' },
[AppointmentStatus.Canceled]: { Name: 'calendar times outline', Color: 'red' },
[AppointmentStatus.Confirmed]: { Name: 'calendar check outline', Color: 'green' },
[AppointmentStatus.Requested]: { Name: 'calendar alternate outline', Color: 'orange' },
[AppointmentStatus.None]: { Name: 'calendar outline', Color: 'blue' }
}
Now with interface as value:
interface Icon {
Name: string
Color: string
}
Usage:
const icon: SemanticIcon = iconMapping[appointment.Status]
I am using this solution that works perfectly for me in Python 3
import logging
log = logging.getLogger(__name__)
...
def deep_compare(self,left, right, level=0):
if type(left) != type(right):
log.info("Exit 1 - Different types")
return False
elif type(left) is dict:
# Dict comparison
for key in left:
if key not in right:
log.info("Exit 2 - missing {} in right".format(key))
return False
else:
if not deep_compare(left[str(key)], right[str(key)], level +1 ):
log.info("Exit 3 - different children")
return False
return True
elif type(left) is list:
# List comparison
for key in left:
if key not in right:
log.info("Exit 4 - missing {} in right".format(key))
return False
else:
if not deep_compare(left[left.index(key)], right[right.index(key)], level +1 ):
log.info("Exit 5 - different children")
return False
return True
else:
# Other comparison
return left == right
return False
It compares dict, list and any other types that implements the "==" operator by themselves. If you need to compare something else different, you need to add a new branch in the "if tree".
Hope that helps.
I am using following:
using System.Web.Script.Serialization;
...
public static T ParseResponse<T>(string data)
{
return new JavaScriptSerializer().Deserialize<T>(data);
}
Simplest solution without changing configs. (ubuntu) Change user, then connect to database cli.
sudo -i -u postgres
psql
taken from https://www.digitalocean.com/community/tutorials/how-to-install-and-use-postgresql-on-ubuntu-18-04
XMLSpectrum formats XML, supports attribute indentation and also does syntax-highlighting for XML and any embedded XPath expressions:
XMLSpectrum is an open source project, coded in XSLT 2.0 - so you can run this server-side with a processor such as Saxon-HE (recommended) or client-side using Saxon-CE.
XMLSpectrum is not yet optimised to run in the browser - hence the recommendation to run this server-side.
i think you have to set it in the options:
$(".form_datetime").datetimepicker({
isRTL: false,
format: 'dd.mm.yyyy hh:ii',
autoclose:true,
language: 'ru'
});
if its not working, be sure that:
$.fn.datetimepicker.dates['en'] = {
days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
today: "Today"
};
is defined for 'ru'
.Net 4.5 introduces a new Caller Information Attributes.
private void OnPropertyChanged<T>([CallerMemberName]string caller = null) {
// make sure only to call this if the value actually changes
var handler = PropertyChanged;
if (handler != null) {
handler(this, new PropertyChangedEventArgs(caller));
}
}
It's probably a good idea to add a comparer to the function as well.
EqualityComparer<T>.Default.Equals
Ok so I took Joshoun code and made it generic. I am not sure if I should implement singleton pattern on SynchronousPost class. Maybe someone more knowledgeble can help.
FileCategory x = new FileCategory { CategoryName = "Some Bs"};
SynchronousPost<FileCategory>test= new SynchronousPost<FileCategory>();
test.PostEntity(x, "/api/ApiFileCategories");
public class SynchronousPost<T>where T :class
{
public SynchronousPost()
{
Client = new WebClient { UseDefaultCredentials = true };
}
public void PostEntity(T PostThis,string ApiControllerName)//The ApiController name should be "/api/MyName/"
{
//this just determines the root url.
Client.BaseAddress = string.Format(
(
System.Web.HttpContext.Current.Request.Url.Port != 80) ? "{0}://{1}:{2}" : "{0}://{1}",
System.Web.HttpContext.Current.Request.Url.Scheme,
System.Web.HttpContext.Current.Request.Url.Host,
System.Web.HttpContext.Current.Request.Url.Port
);
Client.Headers.Add(HttpRequestHeader.ContentType, "application/json;charset=utf-8");
Client.UploadData(
ApiControllerName, "Post",
Encoding.UTF8.GetBytes
(
JsonConvert.SerializeObject(PostThis)
)
);
}
private WebClient Client { get; set; }
}
public class ApiFileCategoriesController : ApiBaseController
{
public ApiFileCategoriesController(IMshIntranetUnitOfWork unitOfWork)
{
UnitOfWork = unitOfWork;
}
public IEnumerable<FileCategory> GetFiles()
{
return UnitOfWork.FileCategories.GetAll().OrderBy(x=>x.CategoryName);
}
public FileCategory GetFile(int id)
{
return UnitOfWork.FileCategories.GetById(id);
}
//Post api/ApileFileCategories
public HttpResponseMessage Post(FileCategory fileCategory)
{
UnitOfWork.FileCategories.Add(fileCategory);
UnitOfWork.Commit();
return new HttpResponseMessage();
}
}
I am using ninject, and repo pattern with unit of work. Anyways, the generic class above really helps.
You need to look at the Backgroundworker example:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Especially how it interacts with the UI layer. Based on your posting, this seems to answer your issues.
I think it's better to always use ApplicationContext, unless you're in a mobile environment like someone else said already. ApplicationContext has more functionality and you definitely want to use the PostProcessors such as RequiredAnnotationBeanPostProcessor, AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor, which will help you simplify your Spring configuration files, and you can use annotations such as @Required, @PostConstruct, @Resource, etc in your beans.
Even if you don't use all the stuff ApplicationContext offers, it's better to use it anyway, and then later if you decide to use some resource stuff such as messages or post processors, or the other schema to add transactional advices and such, you will already have an ApplicationContext and won't need to change any code.
If you're writing a standalone app, load the ApplicationContext in your main method, using a ClassPathXmlApplicationContext, and get the main bean and invoke its run() (or whatever method) to start your app. If you're writing a web app, use the ContextLoaderListener in web.xml so that it creates the ApplicationContext and you can later get it from the ServletContext, regardless of whether you're using JSP, JSF, JSTL, struts, Tapestry, etc.
Also, remember you can use multiple Spring configuration files and you can either create the ApplicationContext by listing all the files in the constructor (or listing them in the context-param for the ContextLoaderListener), or you can just load a main config file which has import statements. You can import a Spring configuration file into another Spring configuration file by using <import resource="otherfile.xml" /> which is very useful when you programmatically create the ApplicationContext in the main method and load only one Spring config file.
Those are two different things, as others have mentioned.
When you specify # -*- coding: utf-8 -*-
, you're telling Python the source file you've saved is utf-8
. The default for Python 2 is ASCII (for Python 3 it's utf-8
). This just affects how the interpreter reads the characters in the file.
In general, it's probably not the best idea to embed high unicode characters into your file no matter what the encoding is; you can use string unicode escapes, which work in either encoding.
When you declare a string with a u
in front, like u'This is a string'
, it tells the Python compiler that the string is Unicode, not bytes. This is handled mostly transparently by the interpreter; the most obvious difference is that you can now embed unicode characters in the string (that is, u'\u2665'
is now legal). You can use from __future__ import unicode_literals
to make it the default.
This only applies to Python 2; in Python 3 the default is Unicode, and you need to specify a b
in front (like b'These are bytes'
, to declare a sequence of bytes).
It makes it clear that the method accepts null values, and that if you override the method, you should also accept null values.
It also serves as a hint for code analyzers like FindBugs. For example, if such a method dereferences its argument without checking for null first, FindBugs will emit a warning.
Sometimes offsetHeight will return zero because the element you've created has not been rendered in the Dom yet. I wrote this function for such circumstances:
function getHeight(element)
{
var e = element.cloneNode(true);
e.style.visibility = "hidden";
document.body.appendChild(e);
var height = e.offsetHeight + 0;
document.body.removeChild(e);
e.style.visibility = "visible";
return height;
}
Another option, how to achieve this, is by using pandas.DataFrame.query()
method. Let me show you an example on the following data frame called df
.
>>> df = pd.DataFrame(np.random.random((5, 1)), columns=['col_1'])
>>> df['date'] = pd.date_range('2020-1-1', periods=5, freq='D')
>>> print(df)
col_1 date
0 0.015198 2020-01-01
1 0.638600 2020-01-02
2 0.348485 2020-01-03
3 0.247583 2020-01-04
4 0.581835 2020-01-05
As an argument, use the condition for filtering like this:
>>> start_date, end_date = '2020-01-02', '2020-01-04'
>>> print(df.query('date >= @start_date and date <= @end_date'))
col_1 date
1 0.244104 2020-01-02
2 0.374775 2020-01-03
3 0.510053 2020-01-04
If you do not want to include boundaries, just change the condition like following:
>>> print(df.query('date > @start_date and date < @end_date'))
col_1 date
2 0.374775 2020-01-03
You can use flexbox to center your text. By the way no need for extra containers because text is considered as anonymous flex item.
From flexbox specs:
Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space (i.e. characters that can be affected by the
white-space
property) is not rendered (just as if it weredisplay:none
).
So just make grid items as flex containers (display: flex
), and add align-items: center
and justify-content: center
to center both vertically and horizontally.
Also performed optimization of HTML and CSS:
html,_x000D_
body {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: grid;_x000D_
grid-template-columns: 1fr 1fr;_x000D_
grid-template-rows: 100vh;_x000D_
_x000D_
font-family: Raleway;_x000D_
font-size: large;_x000D_
}_x000D_
_x000D_
.left_bg,_x000D_
.right_bg {_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
.left_bg {_x000D_
background-color: #3498db;_x000D_
}_x000D_
_x000D_
.right_bg {_x000D_
background-color: #ecf0f1;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="left_bg">Review my stuff</div>_x000D_
<div class="right_bg">Hire me!</div>_x000D_
</div>
_x000D_
My Problem has also been solved by changing in styles.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
I'm fully aware that the code in the original quesiton displays a situation of being navbar related. But as you also dive into other compontents, it maybe helpful to know that the class options for text styling may not work.
But you can still create your own helper classes to keep the "Bootstrap flow" going in your HTML. Here is one idea to help style links that are in panel-title regions.
The following code by itself will not style a warning color on your anchor link...
<div class="panel panel-default my-panel-styles">
...
<h4 class="panel-title">
<a class="accordion-toggle btn-block text-warning" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
My Panel title that is also a link
</a>
</h4>
...
</div>
But you could extend the Bootstrap styling package by adding your own class with appropriate colors like this...
.my-panel-styles .text-muted {color:#777;}
.my-panel-styles .text-primary {color:#337ab7;}
.my-panel-styles .text-success {color:#d44950;}
.my-panel-styles .text-info {color:#31708f;}
.my-panel-styles .text-warning {color:#8a6d3b;}
.my-panel-styles .text-danger {color:#a94442;}
...Now you can continue building out your panel anchor links with the Bootstrap colors you want.
long/int to the byte array looks like exact purpose of struct.pack
. For long integers that exceed 4(8) bytes, you can come up with something like the next:
>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
parts.append(i & limit)
i >>= 32
>>> struct.pack('>' + 'L'*len(parts), *parts )
'\xb1l\x1c\xb1\x11"\x10\xf4'
>>> struct.unpack('>LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
(2976652465L, 287445236)
>>> (287445236L << 32) + 2976652465L
1234567890987654321L
The issue's coming from Jackson. When it doesn't have enough information on what class to deserialize to, it uses LinkedHashMap
.
Since you're not informing Jackson of the element type of your ArrayList
, it doesn't know that you want to deserialize into an ArrayList
of Account
s. So it falls back to the default.
Instead, you could probably use as(JsonNode.class)
, and then deal with the ObjectMapper
in a richer manner than rest-assured allows. Something like this:
ObjectMapper mapper = new ObjectMapper();
JsonNode accounts = given().when().expect().statusCode(expectedResponseCode)
.get("accounts/" + newClub.getOwner().getCustId() + "/clubs")
.as(JsonNode.class);
//Jackson's use of generics here are completely unsafe, but that's another issue
List<Account> accountList = mapper.convertValue(
accounts,
new TypeReference<List<Account>>(){}
);
assertThat(accountList.get(0).getId()).isEqualTo(expectedId);
pip install PyYAML
If libyaml is not found or compiled PyYAML can do without it on Mavericks.
try this code worked for me
SELECT user_display_image AS user_image,
user_display_name AS user_name,
invitee_phone,
(CASE WHEN invitee_status = 1 THEN "attending"
WHEN invitee_status = 2 THEN "unsure"
WHEN invitee_status = 3 THEN "declined"
WHEN invitee_status = 0 THEN "notreviwed"
END) AS invitee_status
FROM your_table
Maybe this answer is not quite what you're looking for, but it will fomat any language with the same keyboard shortcut. The solution are language specific keyboard shortcuts.
For every language you want to format, you must find and download a plugin for that, for example a html formatter and a C# formatter. And then you map the command for every plugin to the same key, but with a differnt context (see the link).
Greets
An implicit interface implementation is where you have a method with the same signature of the interface.
An explicit interface implementation is where you explicitly declare which interface the method belongs to.
interface I1
{
void implicitExample();
}
interface I2
{
void explicitExample();
}
class C : I1, I2
{
void implicitExample()
{
Console.WriteLine("I1.implicitExample()");
}
void I2.explicitExample()
{
Console.WriteLine("I2.explicitExample()");
}
}
simple:
today="$(date '+%Y-%m-%d')"
yesterday="$(date -d yesterday '+%Y-%m-%d')"
It depends on where you're displaying the text. On the console or a textbox for example, \n will suffice. On a RichTextBox I think you need both.
As mentioned both select.select()
and socket.settimeout()
will work.
Note you might need to call settimeout
twice for your needs, e.g.
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("",0))
sock.listen(1)
# accept can throw socket.timeout
sock.settimeout(5.0)
conn, addr = sock.accept()
# recv can throw socket.timeout
conn.settimeout(5.0)
conn.recv(1024)
To show all privileges:
select name from system_privilege_map;
THIS IS NOT AN ANSWER TO THE ORIGINAL QUESTION, IT'S AN ANSWER TO @Teddy's QUESTION IN @Dudi's ANSWER'S COMMENTS
Here's a way to list id's in the active presentation to the immediate window (Ctrl + G) in VBA editor:
Sub ListAllShapes()
Dim curSlide As Slide
Dim curShape As Shape
For Each curSlide In ActivePresentation.Slides
Debug.Print curSlide.SlideID
For Each curShape In curSlide.Shapes
If curShape.TextFrame.HasText Then
Debug.Print curShape.Id
End If
Next curShape
Next curSlide
End Sub
I'm not completely sure how your data is handled, so this may or may not work, but have you considered paginating with a timestamp field?
When you query /foos you get 100 results. Your API should then return something like this (assuming JSON, but if it needs XML the same principles can be followed):
{
"data" : [
{ data item 1 with all relevant fields },
{ data item 2 },
...
{ data item 100 }
],
"paging": {
"previous": "http://api.example.com/foo?since=TIMESTAMP1"
"next": "http://api.example.com/foo?since=TIMESTAMP2"
}
}
Just a note, only using one timestamp relies on an implicit 'limit' in your results. You may want to add an explicit limit or also use an until
property.
The timestamp can be dynamically determined using the last data item in the list. This seems to be more or less how Facebook paginates in its Graph API (scroll down to the bottom to see the pagination links in the format I gave above).
One problem may be if you add a data item, but based on your description it sounds like they would be added to the end (if not, let me know and I'll see if I can improve on this).
This is the sort of thing that sed
is really good at: $ sed 's/[ \t]*$//'
. Be aware the you will probably need to literally type a TAB character instead of \t
for this to work.
Interestingly I checked this on an app of mine and I got the same error.
I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES
and found nothing.
So I moved the
#define _USE_MATH_DEFINES
#include <cmath>
to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h"
) and suddenly it compile perfectly.
Try moving it higher up the page. Totally unsure as to why this would cause issues though.
Edit: Figured it out. The #include <math.h>
occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath
without the #define
specified. math.h
is specifically designed so that you can include it again with that define now changed to add M_PI
etc. This is NOT the case with cmath
. So you need to make sure you #define _USE_MATH_DEFINES
before you include anything else. Hope that clears it up for you :)
Failing that just include math.h
you are using non-standard C/C++ as already pointed out :)
Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)
Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )
I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)
$(document).ready(function() {
$('#Button').click(function() {
$(this).addClass('active');
});
});
should do the trick. unless you're loading the button with ajax. In which case you could do:
$('#Button').live('click', function() {...
Also remember not to use the same id more than once in your html code.
Your use of @PathParam is incorrect. It does not follow these requirements as documented in the javadoc here. I believe you just want to POST the JSON entity. You can fix this in your resource method to accept JSON entity.
@Path("/hello")
public class Hello {
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public JSONObject sayPlainTextHello(JSONObject inputJsonObj) throws Exception {
String input = (String) inputJsonObj.get("input");
String output = "The input you sent is :" + input;
JSONObject outputJsonObj = new JSONObject();
outputJsonObj.put("output", output);
return outputJsonObj;
}
}
And, your client code should look like this:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
client.addFilter(new LoggingFilter());
WebResource service = client.resource(getBaseURI());
JSONObject inputJsonObj = new JSONObject();
inputJsonObj.put("input", "Value");
System.out.println(service.path("rest").path("hello").accept(MediaType.APPLICATION_JSON).post(JSONObject.class, inputJsonObj));
As HungryDB said the easier way for do that is:
$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);
Have a look at your php version because this parameter has been added in version 5.4.0