var defaults = {_x000D_
_x000D_
"background-color": "#000",_x000D_
color: "#fff",_x000D_
weekdays: [_x000D_
{0: 'sun'},_x000D_
{1: 'mon'},_x000D_
{2: 'tue'},_x000D_
{3: 'wed'},_x000D_
{4: 'thu'},_x000D_
{5: 'fri'},_x000D_
{6: 'sat'}_x000D_
]_x000D_
_x000D_
};_x000D_
_x000D_
console.log(defaults.weekdays[3]);
_x000D_
If you're looking for an interface builder only solution there is one for iOS 11 and higher. See my answer here: https://stackoverflow.com/a/58626264
JAVA HOME
is used for setting up the environment variable for JAVA. It means that you are providing a path for compiling a JAVA program and also running the same. So, if you do not set the JAVA HOME( PATH ) and try to run a java or any dependent program in the command prompt.
You will deal with an error as
javac : not recognized as internal or external command
.
Now to set this, Just open your Java jdk then open bin folder then copy the PATH of that bin folder.
Now, go to My computer right click on it----> select properties-----> select Advanced system settings----->Click on Environment Variables------>select New----->give a name in the text box Variable Name and then paste the path in Value.
That's All!!
You might just have to install the packages.
yum install php-pdo php-mysqli
After they're installed, restart Apache.
httpd restart
or
apachectl restart
In Scott’s specific case I’d go with something like:
String.prototype.toCamelCase = function() {
return this.replace(/^([A-Z])|\s(\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
};
'EquipmentClass name'.toCamelCase() // -> equipmentClassName
'Equipment className'.toCamelCase() // -> equipmentClassName
'equipment class name'.toCamelCase() // -> equipmentClassName
'Equipment Class Name'.toCamelCase() // -> equipmentClassName
The regex will match the first character if it starts with a capital letter, and any alphabetic character following a space, i.e. 2 or 3 times in the specified strings.
By spicing up the regex to /^([A-Z])|[\s-_](\w)/g
it will also camelize hyphen and underscore type names.
'hyphen-name-format'.toCamelCase() // -> hyphenNameFormat
'underscore_name_format'.toCamelCase() // -> underscoreNameFormat
query.setParameterList("name", new String[] { "Ron", "Som", "Roxi"}); fixed my issue
tl;dr:
commit()
writes the data synchronously (blocking the thread its called from). It then informs you about the success of the operation.apply()
schedules the data to be written asynchronously. It does not inform you about the success of the operation.apply()
and immediately read via any getX-method, the new value will be returned!apply()
at some point and it's still executing, any calls to commit()
will block until all past apply-calls and the current commit-call are finished.More in-depth information from the SharedPreferences.Editor Documentation:
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.
As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.
The SharedPreferences.Editor interface isn't expected to be implemented directly. However, if you previously did implement it and are now getting errors about missing apply(), you can simply call commit() from apply().
Here is one version that works with filenames that may contain spaces, newlines, and glob characters as well:
find . -type f -printf "%T@ %p\0" | sort -zk1nr
find ... -printf
prints the file modification time (Epoch value) followed by a space and \0
terminated filenames.sort -zk1nr
reads NUL terminated data and sorts it reverse numericallyAs the question is tagged with Linux, I am assuming GNU Core Utilities are available.
You can pipe the above with:
xargs -0 printf "%s\n"
to print the modification time and filenames sorted by modification time (most recent first) terminated by newlines.
Hi, you can do something like that. This function deletes all spaces.
string delSpaces(string &str)
{
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
return str;
}
I made another function, that deletes all unnecessary spaces.
string delUnnecessary(string &str)
{
int size = str.length();
for(int j = 0; j<=size; j++)
{
for(int i = 0; i <=j; i++)
{
if(str[i] == ' ' && str[i+1] == ' ')
{
str.erase(str.begin() + i);
}
else if(str[0]== ' ')
{
str.erase(str.begin());
}
else if(str[i] == '\0' && str[i-1]== ' ')
{
str.erase(str.end() - 1);
}
}
}
return str;
}
If you are using Sql Server this should work
DECLARE @Table TABLE(
ID INT,
Val INT
)
INSERT INTO @Table (ID,Val) SELECT 1, 3
INSERT INTO @Table (ID,Val) SELECT 2, NULL
INSERT INTO @Table (ID,Val) SELECT 3, 5
INSERT INTO @Table (ID,Val) SELECT 4, NULL
INSERT INTO @Table (ID,Val) SELECT 5, NULL
INSERT INTO @Table (ID,Val) SELECT 6, 2
SELECT *,
ISNULL(Val, (SELECT TOP 1 Val FROM @Table WHERE ID < t.ID AND Val IS NOT NULL ORDER BY ID DESC))
FROM @Table t
Use attributed string:
// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]
// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString
You need to define attributes.
Using attributed string you can mix colors, sizes, fonts etc within one text
Try this,
HtmlElement head = _windowManager.ActiveBrowser.Document.GetElementsByTagName("head")[0];
HtmlElement scriptEl = _windowManager.ActiveBrowser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
element.text = "window.onload = function() { document.forms[0].submit(); }";
head.AppendChild(scriptEl);
strAdditionalHeader = "";
_windowManager.ActiveBrowser.Document.InvokeScript("webBrowserControl");
Browsers, by default, have their option to print background-colors and images turned off. You can add some lines in CSS to bypass this. Just add:
* {
-webkit-print-color-adjust: exact !important; /* Chrome, Safari */
color-adjust: exact !important; /*Firefox*/
}
This is a really open ended question, and it all depends on how its being used and the type of temp table (Table variable or traditional table).
A traditional temp table stores the data in the temp DB, which does slow down the temp tables; however table variables do not.
You can expose it as a JMX feature, startable via JConsole:
@ManagedResource
@Named
public class DbManager {
@ManagedOperation(description = "Start HSQL DatabaseManagerSwing.")
public void dbManager() {
String[] args = {"--url", "jdbc:hsqldb:mem:embeddedDataSource", "--noexit"};
DatabaseManagerSwing.main(args);
}
}
XML context:
<context:component-scan base-package="your.package.root" scoped-proxy="targetClass"/>
<context:annotation-config />
<context:mbean-server />
<context:mbean-export />
e.currentTarget is element(parent) where event is registered, e.target is node(children) where event is pointing to.
You can use Collections
for to sort data:
import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
public class tes
{
public static void main(String args[])
{
List<Integer> lList = new ArrayList<Integer>();
lList.add(4);
lList.add(1);
lList.add(7);
lList.add(2);
lList.add(9);
lList.add(1);
lList.add(5);
Collections.sort(lList);
for(int i=0; i<lList.size();i++ )
{
System.out.println(lList.get(i));
}
}
}
Below gives the total physical memory.
gwmi Win32_OperatingSystem | Measure-Object -Property TotalVisibleMemorySize -Sum | % {[Math]::Round($_.sum/1024/1024)}
Despite this question being rather old, I had to deal with a similar warning and wanted to share what I found out.
First of all this is a warning and not an error. So there is no need to worry too much about it. Basically it means, that Tomcat does not know what to do with the source
attribute from context.
This source
attribute is set by Eclipse (or to be more specific the Eclipse Web Tools Platform) to the server.xml
file of Tomcat to match the running application to a project in workspace.
Tomcat generates a warning for every unknown markup in the server.xml
(i.e. the source
attribute) and this is the source of the warning. You can safely ignore it.
Late answer but might be useful useful for someone else
If neither DBCC ShrinkDatabase/ShrinkFile or SSMS (Tasks/Shrink/Database) doesn’t help, there are tools from Quest and ApexSQL that can get the job done, and even schedule periodic shrinking if you need it.
I’ve used the latter one in free trial to do this some time ago, by following short description at the end of this article:
All you need to do is install ApexSQL Backup, click "Shrink database" button in the main ribbon, select database in the window that will pop-up, and click "Finish".
I'm also surprised these aren't compile time constants. But I suppose you could create these values easily enough by simply executing an instruction that returns such an invalid result. Dividing by 0, log of 0, tan of 90, that kinda thing.
The reason is your base class is not public-ed, then Mockito cannot intercept it due to visibility, if you change base class as public, or @Override in sub class (as public), then Mockito can mock it correctly.
public class BaseService{
public boolean foo(){
return true;
}
}
public ChildService extends BaseService{
}
@Test
@Mock ChildService childService;
public void testSave() {
Mockito.when(childService.foo()).thenReturn(false);
// When
assertFalse(childService.foo());
}
Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues
I had the same problem. I think the best solution is to use log.exception, which will automatically print out stack trace and error message, such as:
try:
pass
log.info('Success')
except:
log.exception('Failed')
String one = object.getdata();
Log.d(one,"");
Just cd
to your working folder and then start the IPython notebook server
. This way you can be mobile.
You're opening a file, then passing the file pointer to a function that only wants a file name to open the file itself. You can simplify your call to;
void main(void)
{
printf("LINES: %d\n",countlines("Test.txt"));
}
EDIT: You're changing the question around so it's very hard to answer; at first you got your change to main()
wrong, you forgot that the first parameter is argc, so it crashed. Now you have the problem of;
if (fp == NULL); // <-- note the extra semicolon that is the only thing
// that runs conditionally on the if
return 0; // Always runs and returns 0
which will always return 0. Remove that extra semicolon, and you should get a reasonable count.
Object is a collection of methods and variables.You can't print the variables in object by just cout operation . if you want to show the things inside the object you have to declare either a getter or a display text method in class.
ex
#include <iostream>
using namespace std;
class mystruct
{
private:
int m_a;
float m_b;
public:
mystruct(int x, float y)
{
m_a = x;
m_b = y;
}
public:
void getm_aAndm_b()
{
cout<<m_a<<endl;
cout<<m_b<<endl;
}
};
int main()
{
mystruct m = mystruct(5,3.14);
cout << "my structure " << endl;
m.getm_aAndm_b();
return 0;
}
Not that this is just a one way of doing it
A more modern solution:
Using display: flex
and flex-direction: row
form {_x000D_
display: flex; /* 2. display flex to the rescue */_x000D_
flex-direction: row;_x000D_
}_x000D_
_x000D_
label, input {_x000D_
display: block; /* 1. oh noes, my inputs are styled as block... */_x000D_
}
_x000D_
<form>_x000D_
<label for="name">Name</label>_x000D_
<input type="text" id="name" />_x000D_
<label for="address">Address</label>_x000D_
<input type="text" id="address" />_x000D_
<button type="submit">_x000D_
Submit_x000D_
</button>_x000D_
</form>
_x000D_
Create a Game model which extends Eloquent and use this:
Game::take(30)->skip(30)->get();
take()
here will get 30 records and skip()
here will offset to 30 records.
In recent Laravel versions you can also use:
Game::limit(30)->offset(30)->get();
EDIT 30/Dec/2017: This answer appears in top results of Google searches, so I decided to update it. The old answer is still at the end.
dryscape isn't maintained anymore and the library dryscape developers recommend is Python 2 only. I have found using Selenium's python library with Phantom JS as a web driver fast enough and easy to get the work done.
Once you have installed Phantom JS, make sure the phantomjs
binary is available in the current path:
phantomjs --version
# result:
2.1.1
To give an example, I created a sample page with following HTML code. (link):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Javascript scraping test</title>
</head>
<body>
<p id='intro-text'>No javascript support</p>
<script>
document.getElementById('intro-text').innerHTML = 'Yay! Supports javascript';
</script>
</body>
</html>
without javascript it says: No javascript support
and with javascript: Yay! Supports javascript
import requests
from bs4 import BeautifulSoup
response = requests.get(my_url)
soup = BeautifulSoup(response.text)
soup.find(id="intro-text")
# Result:
<p id="intro-text">No javascript support</p>
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get(my_url)
p_element = driver.find_element_by_id(id_='intro-text')
print(p_element.text)
# result:
'Yay! Supports javascript'
You can also use Python library dryscrape to scrape javascript driven websites.
import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit(my_url)
response = session.body()
soup = BeautifulSoup(response)
soup.find(id="intro-text")
# Result:
<p id="intro-text">Yay! Supports javascript</p>
\df+ <function_name>
in psql.
According to the Oracle PLSQL language definition, a character literal can contain "any printable character in the character set". https://docs.oracle.com/cd/A97630_01/appdev.920/a96624/02_funds.htm#2876
@Robert Love's answer exhibits a best practice for readable code, but you can also just type in the linefeed character into the code. Here is an example from a Linux terminal using sqlplus
:
SQL> set serveroutput on
SQL> begin
2 dbms_output.put_line( 'hello' || chr(10) || 'world' );
3 end;
4 /
hello
world
PL/SQL procedure successfully completed.
SQL> begin
2 dbms_output.put_line( 'hello
3 world' );
4 end;
5 /
hello
world
PL/SQL procedure successfully completed.
Instead of the CHR( NN ) function you can also use Unicode literal escape sequences like u'\0085'
which I prefer because, well you know we are not living in 1970 anymore. See the equivalent example below:
SQL> begin
2 dbms_output.put_line( 'hello' || u'\000A' || 'world' );
3 end;
4 /
hello
world
PL/SQL procedure successfully completed.
For fair coverage I guess it is worth noting that different operating systems use different characters/character sequences for end of line handling. You've got to have a think about the context in which your program output is going to be viewed or printed, in order to determine whether you are using the right technique.
u'\000D\000A'
u'\000A'
u'\0085'
'<BR>'
'<br />'
An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.
It's as easy as this:
import requests
from requests_toolbelt.utils import dump
resp = requests.get('https://httpbin.org/redirect/5')
data = dump.dump_all(resp)
print(data.decode('utf-8'))
Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html
You can simply install it by typing:
pip install requests_toolbelt
You need to use convert in order by as well:
SELECT Convert(varchar,A.InsertDate,103) as Tran_Date
order by Convert(varchar,A.InsertDate,103)
Beamer just delegates responsibility for managing layout of itemize
environments back to the base LaTeX packages, so there's nothing funky you need to do in Beamer itself to alter the apperaance / layout of your lists.
Since Beamer redefines itemize, item, etc., the fully proper way to manipulate things like indentation is to redefine the Beamer templates. I get the impression that you're not looking to go that far, but if that's not the case, let me know and I'll elaborate.
There are at least three ways of accomplishing your goal from within your document, without mussing about with Beamer templates.
itemize
In the following code snippet, you can change the value of \itemindent
from 0em
to whatever you please, including negative values. 0em
is the default item indentation.
The advantage of this method is that the list is styled normally. The disadvantage is that Beamer's redefinition of itemize
and \item
means that the number of paramters that can be manipulated to change the list layout is limited. It can be very hard to get the spacing right with multi-line items.
\begin{itemize}
\setlength{\itemindent}{0em}
\item This is a normally-indented item.
\end{itemize}
list
In the following code snippet, the second parameter to \list
is the bullet to use, and the third parameter is a list of layout parameters to change. The \leftmargin
parameter adjusts the indentation of the entire list item and all of its rows; \itemindent
alters the indentation of subsequent lines.
The advantage of this method is that you have all of the flexibility of lists in non-Beamer LaTeX. The disadvantage is that you have to setup the bullet style (and other visual elements) manually (or identify the right command for the template you're using). Note that if you leave the second argument empty, no bullet will be displayed and you'll save some horizontal space.
\begin{list}{$\square$}{\leftmargin=1em \itemindent=0em}
\item This item uses the margin and indentation provided above.
\end{list}
customlist
environmentThe shortcomings of the list
solution can be ameliorated by defining a new customlist
environment that basically redefines the itemize
environment from Beamer but also incorporates the \leftmargin
and \itemindent
(etc.) parameters. Put the following in your preamble:
\makeatletter
\newenvironment{customlist}[2]{
\ifnum\@itemdepth >2\relax\@toodeep\else
\advance\@itemdepth\@ne%
\beamer@computepref\@itemdepth%
\usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
\usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
\usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
\begin{list}
{
\usebeamertemplate{itemize \beameritemnestingprefix item}
}
{ \leftmargin=#1 \itemindent=#2
\def\makelabel##1{%
{%
\hss\llap{{%
\usebeamerfont*{itemize \beameritemnestingprefix item}%
\usebeamercolor[fg]{itemize \beameritemnestingprefix item}##1}}%
}%
}%
}
\fi
}
{
\end{list}
\usebeamertemplate{itemize/enumerate \beameritemnestingprefix body end}%
}
\makeatother
Now, to use an itemized list with custom indentation, you can use the following environment. The first argument is for \leftmargin
and the second is for \itemindent
. The default values are 2.5em and 0em respectively.
\begin{customlist}{2.5em}{0em}
\item Any normal item can go here.
\end{customlist}
A custom bullet style can be incorporated into the customlist
solution using the standard Beamer mechanism of \setbeamertemplate
. (See the answers to this question on the TeX Stack Exchange for more information.)
Alternatively, the bullet style can just be modified directly within the environment, by replacing \usebeamertemplate{itemize \beameritemnestingprefix item}
with whatever bullet style you'd like to use (e.g. $\square$
).
Here's an example (source):
SET @randomId = Cast(((@maxValue + 1) - @minValue) * Rand() + @minValue AS tinyint);
To match a substring inside parentheses excluding any inner parentheses you may use
\(([^()]*)\)
pattern. See the regex demo.
In JavaScript, use it like
var rx = /\(([^()]*)\)/g;
Pattern details
\(
- a (
char([^()]*)
- Capturing group 1: a negated character class matching any 0 or more chars other than (
and )
\)
- a )
char.To get the whole match, grab Group 0 value, if you need the text inside parentheses, grab Group 1 value.
Most up-to-date JavaScript code demo (using matchAll
):
const strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
const rx = /\(([^()]*)\)/g;
strs.forEach(x => {
const matches = [...x.matchAll(rx)];
console.log( Array.from(matches, m => m[0]) ); // All full match values
console.log( Array.from(matches, m => m[1]) ); // All Group 1 values
});
_x000D_
Legacy JavaScript code demo (ES5 compliant):
var strs = ["I expect five hundred dollars ($500).", "I expect.. :( five hundred dollars ($500)."];
var rx = /\(([^()]*)\)/g;
for (var i=0;i<strs.length;i++) {
console.log(strs[i]);
// Grab Group 1 values:
var res=[], m;
while(m=rx.exec(strs[i])) {
res.push(m[1]);
}
console.log("Group 1: ", res);
// Grab whole values
console.log("Whole matches: ", strs[i].match(rx));
}
_x000D_
If you'd prefer a more direct approach, one that does NOT mess with symlinking between /etc/nginx/sites-available
and /etc/nginx/sites-enabled
, do the following:
/etc/nginx/nginx.conf
include /etc/nginx/conf.d/*.conf;
This tells nginx to pull in any files in the conf.d
directory that end in .conf
. (I know: it's weird that a directory can have a .
in it.)conf.d
directory if it doesn't already exist (per the path in step 3). Be sure to give it the right permissions/ownership. Likely root or www-data. /etc/nginx/sites-available
) into the directory conf.d
.Any .conf
files that you put into the conf.d
directory from here on out will become active as long as you reload/restart nginx after.
Note: You can use the conf.d
and sites-enabled
+ sites-available
method concurrently if you wish. I like to test on my dev box using conf.d
. Feels faster than symlinking and unsymlinking.
If you're looking to scatter by two variables and color by the third, Altair can be a great choice.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])
Altair plot
from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)
"Sencha way" for interacting with server data is setting up an Ext.data.Store
proxied by a Ext.data.proxy.Proxy
(in this case Ext.data.proxy.Ajax
) furnished with a Ext.data.reader.Json
(for JSON-encoded data, there are other readers available as well). For writing data back to the server there's a Ext.data.writer.Writer
s of several kinds.
Here's an example of a setup like that:
var store = Ext.create('Ext.data.Store', {
fields: [
'counter_name',
'counter_type',
'counter_unit'
],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
idProperty: 'counter_name',
rootProperty: 'counters'
}
}
});
data1.json
in this example (also available in this fiddle) contains your data verbatim. idProperty: 'counter_name'
is probably optional in this case but usually points at primary key attribute. rootProperty: 'counters'
specifies which property contains array of data items.
With a store setup this way you can re-read data from the server by calling store.load()
. You can also wire the store to any Sencha Touch appropriate UI components like grids, lists or forms.
You need to enclose that in <%! %> as follows:
<%!
public String getQuarter(int i){
String quarter;
switch(i){
case 1: quarter = "Winter";
break;
case 2: quarter = "Spring";
break;
case 3: quarter = "Summer I";
break;
case 4: quarter = "Summer II";
break;
case 5: quarter = "Fall";
break;
default: quarter = "ERROR";
}
return quarter;
}
%>
You can then invoke the function within scriptlets or expressions:
<%
out.print(getQuarter(4));
%>
or
<%= getQuarter(17) %>
Your approach is correct. (Depending on the circumstances, you might want to use configurations.all { exclude ... }
.) If these excludes really exclude more than a single dependency (I haven't ever noticed that when using them), please file a bug at http://forums.gradle.org, ideally with a reproducible example.
There are some problems when logical vector contains NA
values.
See for example:
z <- c(TRUE, FALSE, NA)
sum(z) # gives you NA
table(z)["TRUE"] # gives you 1
length(z[z == TRUE]) # f3lix answer, gives you 2 (because NA indexing returns values)
So I think the safest is to use na.rm = TRUE
:
sum(z, na.rm = TRUE) # best way to count TRUE values
(which gives 1). I think that table
solution is less efficient (look at the code of table
function).
Also, you should be careful with the "table" solution, in case there are no TRUE values in the logical vector. Suppose z <- c(NA, FALSE, NA)
or simply z <- c(FALSE, FALSE)
, then table(z)["TRUE"]
gives you NA
for both cases.
The following RegEx will work:
"@((((ht)|(f))tp[s]?://)|(www\.))([a-z][-a-z0-9]+\.)?([a-z][-a-z0-9]+\.)?[a-z][-a-z0-9]+\.[a-z]+[/]?[a-z0-9._\/~#&=;%+?-]*@si"
Try to:
$requestData = $request->all();
$requestData['img'] = $img;
Another way to do it:
$request->merge(['img' => $img]);
Thanks to @JoelHinz for this.
If you want to add or overwrite nested data:
$data['some']['thing'] = 'value';
$request->merge($data);
If you do not inject Request $request
object, you can use the global request()
helper or \Request::
facade instead of $request
Reinstalling Compass worked for me.. It's a magic!
sudo gem install -n /usr/local/bin compass
Just want to share my experience on this.
I, too, encountered this error. I'm using MS Visual Studio 2013 and I have an MS SQL Server 2008, though I have had MS SQL Server 2012 Installed before.
I was banging my head on this error for a day. I tried installing SharedManagementObject, SQLSysClrTypes and Native Client, but it didn't work. Why? Well I finally figured that I was installing 2008 or 2012 version of the said files, while I'm using Visual Studio 2013!! My idea is since it is a database issue, the version of the files should be the same with the MS SQL Server installed on the laptop, but apparently, I should have installed the 2013 version because the error is from the Visual Studio and not from the SQL Server.
The subject of the certificate is the entity its public key is associated with (i.e. the "owner" of the certificate).
As RFC 5280 says:
The subject field identifies the entity associated with the public key stored in the subject public key field. The subject name MAY be carried in the subject field and/or the subjectAltName extension.
X.509 certificates have a Subject (Distinguished Name) field and can also have multiple names in the Subject Alternative Name extension.
The Subject DN is made of multiple relative distinguished names (RDNs) (themselves made of attribute assertion values) such as "CN=yourname" or "O=yourorganization".
In the context of the article you're linking to, the subject would be the user/owner of the cert.
// you can send full url here
function getExtension(filename) {
return filename.split('.').pop();
}
If you are using express please add the following line when configuring middleware (bodyParser)
app.use(express.bodyParser({ keepExtensions: true}));
You can use sshpass
utility as below,
$ sshpass -p "your pass" ansible pattern -m module -a args \
-i inventory --ask-sudo-pass
Your code should be something like
require_once('class.twitter.php');
$t = new twitter;
$t->username = 'user';
$t->password = 'password';
$data = $t->publicTimeline();
There's no need for Prototype here: JavaScript has for..in
loops. If you're not sure that no one messed with Object.prototype
, check hasOwnProperty()
as well, ie
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
doSomethingWith(obj[prop]);
}
The accepted answer doesn't work for UILocalNotification. For some reason, %%%%
(4 percent signs) or the unicode character '\uFF05
' only work for this.
So to recap, when formatting your string you may use %%
. However, if your string is part of a UILocalNotification, use %%%%
or \uFF05
.
ANSIBLE_STDOUT_CALLBACK=debug ansible-playbook /tmp/foo.yml -vvv
Tasks with STDOUT will then have a section:
STDOUT:
What ever was in STDOUT
I think the question is not 100% answered. I was searching for issue with missing typeof(), which is compile time directive.
Following links will shine light on the situation:
https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Typeof.html
https://gcc.gnu.org/onlinedocs/gcc-5.3.0/gcc/Alternate-Keywords.html#Alternate-Keywords
as of conculsion try to use __typeof__()
instead. Also gcc ... -Dtypeof=__typeof__ ...
can help.
Option 1
You didn't say much about your environment, but assuming you have it available you could use a PowerShell script; one example is here. The essence of this is:
$smtp = New-Object Net.Mail.SmtpClient("ho-ex2010-caht1.exchangeserverpro.net")
$smtp.Send("[email protected]","[email protected]","Test Email","This is a test")
You could then launch the script from the command line as per this example:
powershell.exe -noexit c:\scripts\test.ps1
Note that PowerShell 2.0, which is installed by default on Windows 7 and Windows Server 2008R2, includes a simpler Send-MailMessage
command, making things easier.
Option 2
If you're prepared to use third-party software, is something line this SendEmail command-line tool. It depends on your target environment, though; if you're deploying your batch file to multiple machines, that will obviously require inclusion (but not formal installation) each time.
Option 3
You could drive Outlook directly from a VBA script, which in turn you would trigger from a batch file; this would let you send an email using Outlook itself, which looks to be closest to what you're wanting. There are two parts to this; first, figure out the VBA scripting required to send an email. There are lots of examples for this online, including from Microsoft here. Essence of this is:
Sub SendMessage(DisplayMsg As Boolean, Optional AttachmentPath)
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Set objOutlook = CreateObject("Outlook.Application")
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
Set objOutlookRecip = .Recipients.Add("Nancy Davolio")
objOutlookRecip.Type = olTo
' Set the Subject, Body, and Importance of the message.
.Subject = "This is an Automation test with Microsoft Outlook"
.Body = "This is the body of the message." &vbCrLf & vbCrLf
.Importance = olImportanceHigh 'High importance
If Not IsMissing(AttachmentPath) Then
Set objOutlookAttach = .Attachments.Add(AttachmentPath)
End If
For Each ObjOutlookRecip In .Recipients
objOutlookRecip.Resolve
Next
.Save
.Send
End With
Set objOutlook = Nothing
End Sub
Then, launch Outlook from the command line with the /autorun
parameter, as per this answer (alter path/macroname as necessary):
C:\Program Files\Microsoft Office\Office11\Outlook.exe" /autorun macroname
Option 4
You could use the same approach as option 3, but move the Outlook VBA into a PowerShell script (which you would run from a command line). Example here. This is probably the tidiest solution, IMO.
Type in the command:
netstat -aon | findstr :80
It will show you all processes that use port 80. Notice the pid (process id) in the right column.
If you would like to free the port, go to Task Manager, sort by pid and close those processes.
-a displays all connections and listening ports.
-o displays the owning process ID associated with each connection.
-n displays addresses and port numbers in numerical form.
I added binary before the column name and solve the charset error.
insert into tableA values(binary stringcolname1);
Being a middle tier developer I like
System.ComponentModel.EditorBrowsableAttribute
Allows me to hide properties so that the UI developer is not overwhelmed with properties that they don't need to see.
System.ComponentModel.BindableAttribute
Some things don't need to be databound. Again, lessens the work the UI developers need to do.
I also like the DefaultValue
that Lawrence Johnston mentioned.
System.ComponentModel.BrowsableAttribute
and the Flags
are used regularly.
I use
System.STAThreadAttribute
System.ThreadStaticAttribute
when needed.
By the way. I these are just as valuable for all the .Net framework developers.
It has a default indent/padding so that the bullets will not end up outside the list itself.
A CSS reset might or might not contain rules to reset the list, that would depend on which one you use.
Add set number
to your .vimrc
file in your home directory.
If the .vimrc
file is not in your home directory create one with
vim .vimrc
and add the commands you want at open.
Here's a site that explains the vimrc and how to use it.
You should do that in GridView's RowDataBound
event which is triggered for every GridViewRow
after it was databound.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Text = "Date";
}
}
or you can set AutogenerateColumns
to false
and add the columns declaratively on aspx:
<asp:gridview id="GridView1"
onrowdatabound="GridView1_RowDataBound"
autogeneratecolumns="False"
emptydatatext="No data available."
runat="server">
<Columns>
<asp:BoundField DataField="DateField" HeaderText="Date"
SortExpression="DateField" />
</Columns>
</asp:gridview>
I was having the same issue, this worked for me https://github.com/webpack/webpack/issues/1468
Jackson provides an annotation that can be used on class level (JsonIgnoreProperties).
Add the following to the top of your class (not to individual methods):
@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {
...
}
Depending on the jackson version you are using you would have to use a different import in the current version it is:
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
in older versions it has been:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
The function looks fine to me. I've written inline comments. Hope it helps:
// function takes a char array as input.
// modifies it to remove duplicates and adds a 0 to mark the end
// of the unique chars in the array.
public static void removeDuplicates(char[] str) {
if (str == null) return; // if the array does not exist..nothing to do return.
int len = str.length; // get the array length.
if (len < 2) return; // if its less than 2..can't have duplicates..return.
int tail = 1; // number of unique char in the array.
// start at 2nd char and go till the end of the array.
for (int i = 1; i < len; ++i) {
int j;
// for every char in outer loop check if that char is already seen.
// char in [0,tail) are all unique.
for (j = 0; j < tail; ++j) {
if (str[i] == str[j]) break; // break if we find duplicate.
}
// if j reachs tail..we did not break, which implies this char at pos i
// is not a duplicate. So we need to add it our "unique char list"
// we add it to the end, that is at pos tail.
if (j == tail) {
str[tail] = str[i]; // add
++tail; // increment tail...[0,tail) is still "unique char list"
}
}
str[tail] = 0; // add a 0 at the end to mark the end of the unique char.
}
To filter a list of dicts you can use the selectattr filter together with the equalto test:
network.addresses.private_man | selectattr("type", "equalto", "fixed")
The above requires Jinja2 v2.8 or later (regardless of Ansible version).
Ansible also has the tests match
and search
, which take regular expressions:
match
will require a complete match in the string, whilesearch
will require a match inside of the string.
network.addresses.private_man | selectattr("type", "match", "^fixed$")
To reduce the list of dicts to a list of strings, so you only get a list of the addr
fields, you can use the map filter:
... | map(attribute='addr') | list
Or if you want a comma separated string:
... | map(attribute='addr') | join(',')
Combined, it would look like this.
- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}
In Angular 6, with your router you can use:
RouterModule.forRoot(routes, { useHash: false })
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Parameter | openSession | getCurrentSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session creation | Always open new session | It opens a new Session if not exists , else use same session which is in current hibernate context. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Session close | Need to close the session object once all the database operations are done | No need to close the session. Once the session factory is closed, this session object is closed. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Flush and close | Need to explicity flush and close session objects | No need to flush and close sessions , since it is automatically taken by hibernate internally. |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Performance | In single threaded environment , it is slower than getCurrentSession | In single threaded environment , it is faster than openSession |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
| Configuration | No need to configure any property to call this method | Need to configure additional property: |
| | | <property name=""hibernate.current_session_context_class"">thread</property> |
+----------------------+----------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------+
If you have ListView in any Parent panel (ListView dock fill), you can use simply method...
private void ListViewHeaderWidth() {
int HeaderWidth = (listViewInfo.Parent.Width - 2) / listViewInfo.Columns.Count;
foreach (ColumnHeader header in listViewInfo.Columns)
{
header.Width = HeaderWidth;
}
}
As other people have answered, .cshtml
(or .vbhtml
if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx
extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.
This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.
Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.
The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.
Here is the function:
document.body.setScaledFont = function(f) {
var s = this.offsetWidth, fs = s * f;
this.style.fontSize = fs + '%';
return this
};
Then convert all your documents child element font sizes to em
's or %
.
Then add something like this to your code to set the base font size.
document.body.setScaledFont(0.35);
window.onresize = function() {
document.body.setScaledFont(0.35);
}
Just in case anyone else ends up here from a web search, and has Grunt already in their dependency list, the answer to this becomes trivial. Here's my solution:
/**
* Return all the subfolders of this path
* @param {String} parentFolderPath - valid folder path
* @param {String} glob ['/*'] - optional glob so you can do recursive if you want
* @returns {String[]} subfolder paths
*/
getSubfolders = (parentFolderPath, glob = '/*') => {
return grunt.file.expand({filter: 'isDirectory'}, parentFolderPath + glob);
}
This is basically the same answer provided by Evert, but extended to show-off
some cool options of fill_between
from matplotlib import pyplot as pl
import numpy as np
pl.clf()
pl.hold(1)
x = np.linspace(0, 30, 100)
y = np.sin(x) * 0.5
pl.plot(x, y, '-k')
x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape) +.1
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#CC4F1B')
pl.fill_between(x, y-error, y+error,
alpha=0.5, edgecolor='#CC4F1B', facecolor='#FF9848')
y = np.cos(x/6*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#1B2ACC')
pl.fill_between(x, y-error, y+error,
alpha=0.2, edgecolor='#1B2ACC', facecolor='#089FFF',
linewidth=4, linestyle='dashdot', antialiased=True)
y = np.cos(x/6*np.pi) + np.sin(x/3*np.pi)
error = np.random.rand(len(y)) * 0.5
y += np.random.normal(0, 0.1, size=y.shape)
pl.plot(x, y, 'k', color='#3F7F4C')
pl.fill_between(x, y-error, y+error,
alpha=1, edgecolor='#3F7F4C', facecolor='#7EFF99',
linewidth=0)
pl.show()
Ultimately no. You can query for listings with a search string from an RSS feed such as this:
http://YOURCITY.craigslist.org/search/sss?format=rss&query=SearchString
As far as posting, craiglist has not opened their API. However, this SO Question may shed some light and a possible solution - although not a very reliable one.
Craigslist Automated Posting API?
Write a note to craigslist asking them to open their API,
The primitive wrapper types are reference types that are automatically created behind the scenes whenever strings, numbers, or Booleans are read.For example :
var name = "foo";
var firstChar = name.charAt(0);
console.log(firstChar);
This is what happens behind the scenes:
// what the JavaScript engine does
var name = "foo";
var temp = new String(name);
var firstChar = temp.charAt(0);
temp = null;
console.log(firstChar);
Because the second line uses a string (a primitive) like an object, the JavaScript engine creates an instance of String so that charAt(0) will work.The String object exists only for one statement before it’s destroyed check this
The instanceof operator returns false because a temporary object is created only when a value is read. Because instanceof doesn’t actually read anything, no temporary objects are created, and it tells us the values aren’t instances of primitive wrapper types. You can create primitive wrapper types manually
Object assign copies one or more source objects to the target object. So we could use Object.assign
here.
Syntax: Object.assign(target, ...sources)
var obj = {};_x000D_
_x000D_
Object.assign(obj, {"1":"aa", "2":"bb"})_x000D_
_x000D_
console.log(obj)
_x000D_
After a couple of csv file downloads (lots of tests) chrome asked whether to allow more downloads from this page. I just dismissed the window. After that chrome did not download the file any more but the console sayed:
"Resource interpreted as Document but transferred with MIME type text/csv"
I could solve that issue by restarting chrome (completely Ctrl-Shift-Q).
[Update] Not sure why this post was deleted but it provided the solution for me. I had gotten the message earlier about trying to download multiple files and must have answered no. I got the "Resource interpreted..." message until I restarted the browser; then it worked perfectly. For some cases, this may be the right answer.
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
Kevin's answer works but It makes it hard to play with the data using that solution.
Best solution is don't start startActivityForResult()
on activity level.
in your case don't call getActivity().startActivityForResult(i, 1);
Instead, just use startActivityForResult()
and it will work perfectly fine! :)
You have use to repeat-y
as style="background-repeat:repeat-y;width: 200px;"
instead of style="repeat-y"
.
Try this inside the image tag or you can use the below css for the div
.div_backgrndimg
{
background-repeat: repeat-y;
background-image: url("/image/layout/lotus-dreapta.png");
width:200px;
}
You can always wrap the child elements of #first and save height height of the wrapper as a variable. This might not be the prettiest or most efficient answer, but it does the trick.
Here's a fiddle where I included a reset.
but for your purposes, here's the meat & potatoes:
$(function(){
//wrap everything inside #first
$('#first').children().wrapAll('<div class="wrapper"></div>');
//get the height of the wrapper
var expandedHeight = $('.wrapper').height();
//get the height of first (set to 200px however you choose)
var collapsedHeight = $('#first').height();
//when you click the element of your choice (a button in my case) #first will animate to height auto
$('button').click(function(){
$("#first").animate({
height: expandedHeight
})
});
});?
std::map::find
returns an iterator to the found element (or to the end()
if the element was not found). So long as the map
is not const, you can modify the element pointed to by the iterator:
std::map<char, int> m;
m.insert(std::make_pair('c', 0)); // c is for cookie
std::map<char, int>::iterator it = m.find('c');
if (it != m.end())
it->second = 42;
You can't have cells of arbitrarily different widths, this is generally a standard behaviour of tables from any space, e.g. Excel, otherwise it's no longer a table but just a list of text.
You can however have cells span multiple columns, such as:
<table>
<tr>
<td>25</td>
<td>50</td>
<td>25</td>
</tr>
<tr>
<td colspan="2">75</td>
<td>20</td>
</tr>
</table>
As an aside, you should avoid using style attributes like border
and bgcolor
and prefer CSS for those.
If you are using Primefaces, you should insert inside the the .xhtml file so it converts correctly to java integer. For example:
<p:selectCheckboxMenu
id="frameSelect"
widgetVar="frameSelectBox"
filter="true"
filterMatchMode="contains"
label="#{messages['frame']}"
value="#{platform.frameBean.selectedFramesTypesList}"
converter="javax.faces.Integer">
<f:selectItems
value="#{platform.frameBean.framesTypesList}"
var="area"
itemLabel="#{area}"
itemValue="#{area}" />
</p:selectCheckboxMenu>
$six_digit_random_number = mt_rand(100000, 999999);
As all numbers between 100,000 and 999,999 are six digits, of course.
This technique is now deprecated.
This used to tell Google how to index the page.
https://developers.google.com/webmasters/ajax-crawling/
This technique has mostly been supplanted by the ability to use the JavaScript History API that was introduced alongside HTML5. For a URL like www.example.com/ajax.html#!key=value
, Google will check the URL www.example.com/ajax.html?_escaped_fragment_=key=value
to fetch a non-AJAX version of the contents.
In modern browsers (everything except IE9 and below), our lives are a little easier now with the new URL api
var url = new window.URL(document.location); // fx. http://host.com/endpoint?abc=123
url.searchParams.set("foo", "bar");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=bar
url.searchParams.set("foo", "ooft");
console.log(url.toString()); // http://host/endpoint?abc=123&foo=ooft
There is also this one:
hash = { foo: "bar", baz: "qux" }
hash.map(&:last) #=> ["bar", "qux"]
Why it works:
The &
calls to_proc
on the object, and passes it as a block to the method.
something {|i| i.foo }
something(&:foo)
As I understood, the desired effect you want is to scroll to the end of a list (or scrollable div) when something happens (e.g.: a item is added to the list). If so, you can scroll to the end of a container element (or even the page it self) using only pure Javascript and the VueJS selectors.
var container = this.$el.querySelector("#container");
container.scrollTop = container.scrollHeight;
I've provided a working example in this fiddle: https://jsfiddle.net/my54bhwn
Every time a item is added to the list, the list is scrolled to the end to show the new item.
Hope this help you.
Your also have to register the receiver in onCreate(), like this:
IntentFilter filter = new IntentFilter();
filter.addAction("csinald.meg");
registerReceiver(receiver, filter);
Thanks @vpekar for your implementation. It helped a lot. I just found that it misses the tf-idf weight while calculating the cosine similarity. The Counter(word) returns a dictionary which has the list of words along with their occurence.
cos(q, d) = sim(q, d) = (q · d)/(|q||d|) = (sum(qi, di)/(sqrt(sum(qi2)))*(sqrt(sum(vi2))) where i = 1 to v)
Please feel free to view my code here. But first you will have to download the anaconda package. It will automatically set you python path in Windows. Add this python interpreter in Eclipse.
Try this:
jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
Or this:
yourTerminal:prompt> jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10
It looks like you're getting back an array. If it's always going to consist of just one element, you could do this (yes, it's pretty much the same thing as Tomalak's answer):
$.each(result[0], function(key, value){
console.log(key, value);
});
If you might have more than one element and you'd like to iterate over them all, you could nest $.each()
:
$.each(result, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
});
Specifying android:onClick
attribute results in Button
instance calling setOnClickListener
internally. Hence there is absolutely no difference.
To have clear understanding, let us see how XML onClick
attribute is handled by the framework.
When a layout file is inflated, all Views specified in it are instantiated. In this specific case, the Button
instance is created using public Button (Context context, AttributeSet attrs, int defStyle)
constructor. All of the attributes in the XML tag are read from the resource bundle and passed as AttributeSet
to the constructor.
Button
class is inherited from View
class which results in View
constructor being called, which takes care of setting the click call back handler via setOnClickListener
.
The onClick attribute defined in attrs.xml, is referred in View.java as R.styleable.View_onClick
.
Here is the code of View.java
that does most of the work for you by calling setOnClickListener
by itself.
case R.styleable.View_onClick:
if (context.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
final String handlerName = a.getString(attr);
if (handlerName != null) {
setOnClickListener(new OnClickListener() {
private Method mHandler;
public void onClick(View v) {
if (mHandler == null) {
try {
mHandler = getContext().getClass().getMethod(handlerName,
View.class);
} catch (NoSuchMethodException e) {
int id = getId();
String idText = id == NO_ID ? "" : " with id '"
+ getContext().getResources().getResourceEntryName(
id) + "'";
throw new IllegalStateException("Could not find a method " +
handlerName + "(View) in the activity "
+ getContext().getClass() + " for onClick handler"
+ " on view " + View.this.getClass() + idText, e);
}
}
try {
mHandler.invoke(getContext(), View.this);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Could not execute non "
+ "public method of the activity", e);
} catch (InvocationTargetException e) {
throw new IllegalStateException("Could not execute "
+ "method of the activity", e);
}
}
});
}
break;
As you can see, setOnClickListener
is called to register the callback, as we do in our code. Only difference is it uses Java Reflection
to invoke the callback method defined in our Activity.
Here are the reason for issues mentioned in other answers:
Java Class getMethod
is used, only functions with public access specifier are searched for. Otherwise be ready to handle IllegalAccessException
exception.getContext().getClass().getMethod()
call restricts the method search to the current context, which is Activity in case of Fragment. Hence method is searched within Activity class and not Fragment class.Java Class getMethod
searches for method which accepts View.class
as parameter.Try this code
import java.io.IOException;
public class CLS {
public static void main(String... arg) throws IOException, InterruptedException {
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
}
}
Now when the Java process is connected to a console, it will clear the console.
In case you are doing it from Windows you can use Python script hivehoney to extract table data to local CSV file.
It will:
Execute it like this:
set PROXY_HOST=your_bastion_host
set SERVICE_USER=you_func_user
set LINUX_USER=your_SOID
set LINUX_PWD=your_pwd
python hh.py --query_file=query.sql
If you don't want anything to display before the redirect, then you will need to use some server side scripting to accomplish the task before the page is served. The page has already begun loading by the time your Javascript is executed on the client side.
If Javascript is your only option, your best best is to make your script the first .js file included in the <head>
of your document.
Instead of Javascript, I recommend setting up your redirect logic in your Apache or nginx server configuration.
There's a Python3 pip package called githubdl
that can do this*:
export GIT_TOKEN=1234567890123456789012345678901234567890123
pip install githubdl
githubdl -u http://github.com/foobar/test -d foo
The project page is here
* Disclaimer: I wrote this package.
If you compile with debug symbols, you can use objdump
to produce a more readable disassembly.
>objdump --help
[...]
-S, --source Intermix source code with disassembly
-l, --line-numbers Include line numbers and filenames in output
objdump -drwC -Mintel
is nice:
-r
shows symbol names on relocations (so you'd see puts
in the call
instruction below)-R
shows dynamic-linking relocations / symbol names (useful on shared libraries)-C
demangles C++ symbol names-w
is "wide" mode: it doesn't line-wrap the machine-code bytes-Mintel
: use GAS/binutils MASM-like .intel_syntax noprefix
syntax instead of AT&T-S
: interleave source lines with disassembly.You could put something like alias disas="objdump -drwCS -Mintel"
in your ~/.bashrc
Example:
> gcc -g -c test.c
> objdump -d -M intel -S test.o
test.o: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
#include <stdio.h>
int main(void)
{
0: 55 push ebp
1: 89 e5 mov ebp,esp
3: 83 e4 f0 and esp,0xfffffff0
6: 83 ec 10 sub esp,0x10
puts("test");
9: c7 04 24 00 00 00 00 mov DWORD PTR [esp],0x0
10: e8 fc ff ff ff call 11 <main+0x11>
return 0;
15: b8 00 00 00 00 mov eax,0x0
}
1a: c9 leave
1b: c3 ret
Note that this isn't using -r
so the call rel32=-4
isn't annotated with the puts
symbol name. And looks like a broken call
that jumps into the middle of the call instruction in main. Remember that the rel32
displacement in the call encoding is just a placeholder until the linker fills in a real offset (to a PLT stub in this case, unless you statically link libc).
I've experienced that, at least with the Cygwin version of tar I'm using ("CYGWIN_NT-5.1 1.7.17(0.262/5/3) 2012-10-19 14:39 i686 Cygwin" on a Windows XP Home Edition SP3 machine), the order of options is important.
While this construction worked for me:
tar cfvz target.tgz --exclude='<dir1>' --exclude='<dir2>' target_dir
that one didn't work:
tar cfvz --exclude='<dir1>' --exclude='<dir2>' target.tgz target_dir
This, while tar --help
reveals the following:
tar [OPTION...] [FILE]
So, the second command should also work, but apparently it doesn't seem to be the case...
Best rgds,
$(this).dialog('destroy').remove()
This will destroy the dialog and then remove the div that was "hosting" the dialog completely from the DOM
Use an extension method.
Ex:
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
}
}
Usage:
DateTime.Now.Tomorrow();
or
AnyObjectOfTypeDateTime.Tomorrow();
Here is an example of concatenation operator:
architecture EXAMPLE of CONCATENATION is
signal Z_BUS : bit_vector (3 downto 0);
signal A_BIT, B_BIT, C_BIT, D_BIT : bit;
begin
Z_BUS <= A_BIT & B_BIT & C_BIT & D_BIT;
end EXAMPLE;
If you configure your gitconfig with this option, you will later have a problem cloning other repos of GitHub
git config --global --add url. "[email protected]". Instead, "https://github.com/"
Instead, I recommend that you use this option
echo "export GIT_TERMINAL_PROMPT=1" >> ~/.bashrc || ~/.zshrc
and do not forget to generate an access token from your private repository. When prompted to enter your password, just paste the access token. Happy clone :)
You say this :
I never see the final query as it's sent to the database
Well, actually, when using prepared statements, there is no such thing as a "final query" :
So, to answer your question :
Is there a way capture the complete SQL query sent by PDO to the database and log it to a file?
No : as there is no "complete SQL query" anywhere, there is no way to capture it.
The best thing you can do, for debugging purposes, is "re-construct" an "real" SQL query, by injecting the values into the SQL string of the statement.
What I usually do, in this kind of situations, is :
var_dump
(or an equivalent) just after, to display the values of the parametersThis is not great, when it comes to debugging -- but that's the price of prepared statements and the advantages they bring.
I had a problem which I have just managed to solve so I am sharing it as it may help someone.
I have a UITableView and added the methods shown to enable swipe to delete:
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return YES if you want the specified item to be editable.
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
//add code here for when you hit delete
}
}
I am working on an update that allows me to put the table into edit mode and enables multiselect. To do that I added the code from Apple's TableMultiSelect sample. Once I got that working I found that my swipe the delete function had stopped working.
It turns out that adding the following line to viewDidLoad was the issue:
self.tableView.allowsMultipleSelectionDuringEditing = YES;
With this line in, the multiselect would work but the swipe to delete wouldn't. Without the line it was the other way around.
The fix:
Add the following method to your viewController:
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
self.tableView.allowsMultipleSelectionDuringEditing = editing;
[super setEditing:editing animated:animated];
}
Then in your method that puts the table into editing mode (from a button press for example) you should use:
[self setEditing:YES animated:YES];
instead of:
[self.tableView setEditing:YES animated:YES];
This means that multiselect is only enabled when the table is in editing mode.
Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);
startActivity(in);
This is an explicit intent to start secondscreen activity.
Your hack of decrementing the count at the end is exactly that -- a hack.
Far better to write your loop correctly in the first place, so it doesn't count the last line twice.
int main() {
int number_of_lines = 0;
std::string line;
std::ifstream myfile("textexample.txt");
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;
return 0;
}
Personally, I think in this case, C-style code is perfectly acceptable:
int main() {
unsigned int number_of_lines = 0;
FILE *infile = fopen("textexample.txt", "r");
int ch;
while (EOF != (ch=getc(infile)))
if ('\n' == ch)
++number_of_lines;
printf("%u\n", number_of_lines);
return 0;
}
Edit: Of course, C++ will also let you do something a bit similar:
int main() {
std::ifstream myfile("textexample.txt");
// new lines will be skipped unless we stop it from happening:
myfile.unsetf(std::ios_base::skipws);
// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
std::istream_iterator<char>(myfile),
std::istream_iterator<char>(),
'\n');
std::cout << "Lines: " << line_count << "\n";
return 0;
}
The simplest and most widely available method to get user input at a shell prompt is the read
command. The best way to illustrate its use is a simple demonstration:
while true; do
read -p "Do you wish to install this program?" yn
case $yn in
[Yy]* ) make install; break;;
[Nn]* ) exit;;
* ) echo "Please answer yes or no.";;
esac
done
Another method, pointed out by Steven Huwig, is Bash's select
command. Here is the same example using select
:
echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
case $yn in
Yes ) make install; break;;
No ) exit;;
esac
done
With select
you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a while true
loop to retry if they give invalid input.
Also, Léa Gris demonstrated a way to make the request language agnostic in her answer. Adapting my first example to better serve multiple languages might look like this:
set -- $(locale LC_MESSAGES)
yesptrn="$1"; noptrn="$2"; yesword="$3"; noword="$4"
while true; do
read -p "Install (${yesword} / ${noword})? " yn
case $yn in
${yesptrn##^} ) make install; break;;
${noptrn##^} ) exit;;
* ) echo "Answer ${yesword} / ${noword}.";;
esac
done
Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.
Finally, please check out the excellent answer by F. Hauri.
By using itemStateChanged(ItemListener)
you can track selecting and deselecting checkbox (and do whatever you want based on it):
myCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
//do something...
} else {//checkbox has been deselected
//do something...
};
}
});
Java Swing itemStateChanged docu should help too. By using isSelected()
method you can just test if actual is checkbox selected:
if(myCheckBox.isSelected()){_do_something_if_selected_}
For many it's a permission issue, but for me it turns out the error was brought about by a mistake in the form I was trying to submit. To be specific i had accidentally put ">" sign after the value of "action". So I would suggest you take a second look at your code
You can simply use multiprocessing.Pool
:
from multiprocessing import Pool
def process_image(name):
sci=fits.open('{}.fits'.format(name))
<process>
if __name__ == '__main__':
pool = Pool() # Create a multiprocessing Pool
pool.map(process_image, data_inputs) # process data_inputs iterable with pool
Seems your resource POST
method won't get hit as @peeskillet mention. Most probably your ~POST~ request won't work, because it may not be a simple request. The only simple requests are GET, HEAD or POST and request headers are simple(The only simple headers are Accept, Accept-Language, Content-Language, Content-Type= application/x-www-form-urlencoded, multipart/form-data, text/plain).
Since in you already add Access-Control-Allow-Origin
headers to your Response, you can add new OPTIONS
method to your resource class.
@OPTIONS
@Path("{path : .*}")
public Response options() {
return Response.ok("")
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "2000")
.build();
}
My unorthodox but simple solution from scratch:
git clone
your repository into a fresh new directory.git remote add upstream <your github rep here>
git pull upstream master
git add .
git commit -m "your commit text here"
git push origin master
voila! worked like a charm in my case.
Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table
insert into funds (ID, date, price)
select
T.*
from
(select 23 ID, '2013-02-12' date, 22.43 price) T
left join
funds on funds.ID = T.ID and funds.date = T.date
where
funds.ID is null
For me the issue was about a comma not in the filename but as below: -
Response.ok(streamingOutput,MediaType.APPLICATION_OCTET_STREAM_TYPE).header("content-disposition", "attachment, filename=your_file_name").build();
I accidentally put a comma after attachment. Got it resolved by replacing comma with a semicolon.
My version:
div#dashmain { margin-left:150px; }
div#dashside {position:fixed; width:150px; height:100%; }
<div id="dashside"></div>
<div id="dashmain">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">Content</div>
</div>
</div>
</div>
This works for me without throwing an exception:
package com.sandbox;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Sandbox {
public static void main(String[] args) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
Date parsed = format.parse("20110210");
java.sql.Date sql = new java.sql.Date(parsed.getTime());
}
}
It should work. Try this
Select * from
(select col1, col2, case when 1=1 then 'ok' end as alias_col
from table)
as tmp_table
order by
case when @sortBy = 1 then tmp_table.alias_col end asc
Wikipedia points to the term Canonicalization.
A process for converting data that has more than one possible representation into a "standard" canonical representation. This can be done to compare different representations for equivalence, to count the number of distinct data structures, to improve the efficiency of various algorithms by eliminating repeated calculations, or to make it possible to impose a meaningful sorting order.
The Unicode example made the most sense to me:
Variable-length encodings in the Unicode standard, in particular UTF-8, have more than one possible encoding for most common characters. This makes string validation more complicated, since every possible encoding of each string character must be considered. A software implementation which does not consider all character encodings runs the risk of accepting strings considered invalid in the application design, which could cause bugs or allow attacks. The solution is to allow a single encoding for each character. Canonicalization is then the process of translating every string character to its single allowed encoding. An alternative is for software to determine whether a string is canonicalized, and then reject it if it is not. In this case, in a client/server context, the canonicalization would be the responsibility of the client.
In summary, a standard form of representation for data. From this form you can then convert to any representation you may need.
<description><![CDATA[first line<br/>second line<br/>]]></description>
The scenarios that you have mentioned are not of overloading, you are just concatenating different variables with a String.
System.out.print("Hello World");
System.out.print("My name is" + foo);
System.out.print("Sum of " + a + "and " + b + "is " + c);
System.out.print("Total USD is " + usd);
in all of these cases, you are only calling print(String s) because when something is concatenated with a string it gets converted to a String by calling the toString() of that object, and primitives are directly concatenated. However if you want to know of different signatures then yes print() is overloaded for various arguments.
If you have a table with this exact record layout, use its name as a type, otherwise you will have to declare the type explicitly:
CREATE OR REPLACE FUNCTION get_object_fields
(
name text
)
RETURNS mytable
AS
$$
DECLARE f1 INT;
DECLARE f2 INT;
…
DECLARE f8 INT;
DECLARE retval mytable;
BEGIN
-- fetch fields f1, f2 and f3 from table t1
-- fetch fields f4, f5 from table t2
-- fetch fields f6, f7 and f8 from table t3
retval := (f1, f2, …, f8);
RETURN retval;
END
$$ language plpgsql;
As per this question's answer
You will want something like this:
<bindings> <basicHttpBinding> <binding name="basicHttp" allowCookies="true" maxReceivedMessageSize="20000000" maxBufferSize="20000000" maxBufferPoolSize="20000000"> <readerQuotas maxDepth="32" maxArrayLength="200000000" maxStringContentLength="200000000"/> </binding> </basicHttpBinding> </bindings>
Please also read comments to the accepted answer there, those contain valuable input.
You can choose any one of them http://www.python-excel.org/
I would recommended python xlrd library.
install it using
pip install xlrd
import using
import xlrd
to open a workbook
workbook = xlrd.open_workbook('your_file_name.xlsx')
open sheet by name
worksheet = workbook.sheet_by_name('Name of the Sheet')
open sheet by index
worksheet = workbook.sheet_by_index(0)
read cell value
worksheet.cell(0, 0).value
If you want a less verbose hack:
void deleteDirectory(String path) {
Runtime.getRuntime().exec(String.format("rm -rf %s", path));
}
There is no such thing as array constant in Go.
Quoting from the Go Language Specification: Constants:
There are boolean constants, rune constants, integer constants, floating-point constants, complex constants, and string constants. Rune, integer, floating-point, and complex constants are collectively called numeric constants.
A Constant expression (which is used to initialize a constant) may contain only constant operands and are evaluated at compile time.
The specification lists the different types of constants. Note that you can create and initialize constants with constant expressions of types having one of the allowed types as the underlying type. For example this is valid:
func main() {
type Myint int
const i1 Myint = 1
const i2 = Myint(2)
fmt.Printf("%T %v\n", i1, i1)
fmt.Printf("%T %v\n", i2, i2)
}
Output (try it on the Go Playground):
main.Myint 1
main.Myint 2
If you need an array, it can only be a variable, but not a constant.
I recommend this great blog article about constants: Constants
Here you have example how to set the readonly attribute:
<form action="demo_form.asp">_x000D_
Country: <input type="text" name="country" value="Norway" readonly><br>_x000D_
<input type="submit" value="Submit">_x000D_
</form>
_x000D_
The answer anhic gave can be very inefficient if you have a large database and the attribute name is present only in some of the documents.
To improve efficiency you can add a $match to the aggregation.
db.collection.aggregate(
{"$match": {"name" :{ "$ne" : null } } },
{"$group" : {"_id": "$name", "count": { "$sum": 1 } } },
{"$match": {"count" : {"$gt": 1} } },
{"$project": {"name" : "$_id", "_id" : 0} }
)
You can use list comprehension together with the string methods.
>>> s
'foo-bar#baz?qux@127/\\9]'
>>> "".join(x for x in s if x.isalnum())
'foobarbazqux1279'
We follow the guidelines listed on this page: C++ Programming Style Guidelines
I'd also recommend you read The Elements of C++ Style by Misfeldt et al, which is quite an excellent book on this topic.
In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325
Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.
Make sure that you have checked it to work properly with the IE version you specify.
The simplest way is to:
intercept every button state
add !important
to override the states
.btn-primary:hover,
.btn-primary:active,
.btn-primary:visited,
.btn-primary:focus {
background-color: black !important;
border-color: black !important;
}
OR the more practical UI way is to make the hover state of the button darker than the original state. Just use the CSS snippet below:
.btn-primary {
background-color: Blue !important;
border-color: Blue !important;
}
.btn-primary:hover,
.btn-primary:active,
.btn-primary:visited,
.btn-primary:focus {
background-color: DarkBlue !important;
border-color: DarkBlue !important;
}
Short answer: Kill all the jobs which are running on the master.
In my case there were 3 jobs hung on the master for more than 10 days which were unnoticed. We usually do not run any jobs directly on the master, everything is run on slaves. I killed these 3 jobs which were hung, automatically the executors on the slave started picking up jobs.
Point to note that even though we have 8 slaves only 1 slave was in this affected state.
[EDIT] We found the answer to why only one slave was in this affected state. When a Jenkins slave goes down, all the pending jobs automatically get transferred over to the master. All the 3 hung jobs which I killed were from this slave, so its likely a connection issue between the master and this particular slave.
Checking download source/javadoc in Eclipse-Maven preference, sometimes is not enough. In the event maven failed to download them for some reason (a network blackout?), maven creates some *.lastUpdated files, then will never download again. My empirical solution was to delete the artifact directory from .m2/repository, and restart the eclipse workspace with download source/javadoc checked and update projects at startup checked as well. After the workspace has been restarted, maybe some projects can be marked in error, while eclipse progress is downloading, then any error will be cleared. Maybe this procedure is not so "scientific", but for me did succeded.
First of all, why would you need to output to console in a release mode build? Nobody will think to look there when there's a gui...
Second, qDebug is fancy :)
Third, you can try adding console
to your .pro
's CONFIG
, it might work.
Another way to do this
find . -name *.xml -exec sed -i "s/4.6.0-SNAPSHOT/5.0.0-SNAPSHOT/" {} \;
Some help regarding the above command
The find will do the find for you on the current directory indicated by .
-name
the name of the file in my case its pom.xml can give wild cards.
-exec
execute
sed
stream editor
-i
ignore case
s
is for substitute
/4.6.0.../
String to be searched
/5.0.0.../
String to be replaced
I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:
window.addEventListener("beforeunload", function() { debugger; }, false)
This will pause chrome before loading the new page by hitting a breakpoint.
I was having an issue with this, my server was running behind a load balancer. The load balancer was terminating the SSL/TLS connection. It then passed the request to the web servers using http.
Using the Url.Action() method with Request.Url.Schema, it kept creating a http url, in my case to create a link in an automated email (which my PenTester didn't like).
I may have cheated a little, but it is exactly what I needed to force a https url:
<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>
I actually use a web.config AppSetting so I can use http when debugging locally, but all test and prod environments use transformation to set the https value.
?max
shows you that there is an extra parameter na.rm
that you can set to TRUE
.
Apart from that, if you really want to remove the NA
s, just use something like:
myvec[!is.na(myvec)]
When nothing else works, force it to be shown:
editText.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
And then later, if you wish to close it, in onPause() for example, you can call:
InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
# List of packages for session
.packages = c("ggplot2", "plyr", "rms")
# Install CRAN packages (if not already installed)
.inst <- .packages %in% installed.packages()
if(length(.packages[!.inst]) > 0) install.packages(.packages[!.inst])
# Load packages into session
lapply(.packages, require, character.only=TRUE)
My approach:
<div class="left">Left</div>
<div class="right">Right</div>
CSS:
.left {
float: left;
width: calc(100% - 200px);
background: green;
}
.right {
float: right;
width: 200px;
background: yellow;
}
Modify your Jquery in following way:
$.ajax({
url: someurl,
contentType: 'application/json',
data: JSONObject,
headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
dataType: 'json',
type: 'POST',
success: function (Data) {....}
});
For Rails 4, see this answer.
For Rails 3.x, configure a logger in config/environments/test.rb
:
config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR
This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.
Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile
, then set up two appenders in config/environments/test.rb
:
logger = Logging.logger['test']
logger.add_appenders(
Logging.appenders.stdout,
Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger
I know this is ages old, but upon searching for something similar this morning, and reading up on Atømix' response (as this is what we're aiming on achieving), I found this: http://www.switchonthecode.com/tutorials/using-jquery-slider-to-scroll-a-div.
Just putting that there in case anyone else needs a solution. :)
You can use the dict.fromkeys
class method ...
>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}
This is the fastest way to create a dictionary where all the keys map to the same value.
But do not use this with mutable objects:
d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!
If you don't actually need to initialize all the keys, a defaultdict
might be useful as well:
from collections import defaultdict
d = defaultdict(True)
To answer the second part, a dict-comprehension is just what you need:
{k: k for k in range(10)}
You probably shouldn't do this but you could also create a subclass of dict
which works somewhat like a defaultdict
if you override __missing__
:
>>> class KeyDict(dict):
... def __missing__(self, key):
... #self[key] = key # Maybe add this also?
... return key
...
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}
My solution, it´s make with jquery-chosen and bootstrap, the id is for jquery chosen, tested and working, I had problems concatenating @foreach but now work with a double @foreach and double @if:
<div class="form-group">
<label for="tagLabel">Tags: </label>
<select multiple class="chosen-tag" id="tagLabel" name="tag_id[]" required>
@foreach($tags as $id => $name)
@if (is_array(Request::old('tag_id')))
<option value="{{ $id }}"
@foreach (Request::old('tag_id') as $idold)
@if($idold==$id)
selected
@endif
@endforeach
style="padding:5px;">{{ $name }}</option>
@else
<option value="{{ $id }}" style="padding:5px;">{{ $name }}</option>
@endif
@endforeach
</select>
</div>
this is the code por jquery chosen (the blade.php code doesn´t need this code to work)
$(".chosen-tag").chosen({
placeholder_text_multiple: "Selecciona alguna etiqueta",
no_results_text: "No hay resultados para la busqueda",
search_contains: true,
width: '500px'
});
You actually need 3 meta
tags to support Android, iPhone and Windows Phone
<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">
Thanks, i just need to use:
SETLOCAL EnableExtensions
And put a:
2^>nul
Into the REG QUERY called in the FOR command. Thanks a lot again! :)
import java.util.*
You can gethour and minute using calendar and formatter class. Calendar cal = Calendar.getInstance()
and Formatter fmt=new Formatter()
and set a format for display hour and minute fmt.format("%tl:%M",cal,cal)
and print System.out.println(fmt)
output shows like 10:12
Bootstrap offers various table styles. Have a look at Base CSS - Tables for documentation and examples.
The following style gives great looking tables:
<table class="table table-striped table-bordered table-condensed">
...
</table>
As some of the other answers have stated, you probably use an alias somewhere which maps cp
to cp -i
or something similar. You can run a command without any aliases by preceding it with a backslash. In your case, try
\cp -r /zzz/zzz/* /xxx/xxx
The backslash will temporarily disable any aliases you have called cp
.
after you build your image do the following:
docker tag <image id> mynewtag:version
after that you will see your image is no longer named <none>
when you go docker images
.
At least with Django 1.9.9 -- the version I'm currently using --, note that .get_fields()
actually also "considers" any foreign model as a field, which may be problematic. Say you have:
class Parent(models.Model):
id = UUIDField(primary_key=True)
class Child(models.Model):
parent = models.ForeignKey(Parent)
It follows that
>>> map(lambda field:field.name, Parent._model._meta.get_fields())
['id', 'child']
while, as shown by @Rockallite
>>> map(lambda field:field.name, Parent._model._meta.local_fields)
['id']
I've experienced the same issue because of certifi
library. Installing a different version helped me as well.
I did a quick non-scientific test in Release mode. I used two inputs: "2.34523" and "badinput" into both methods and iterated 1,000,000 times.
Valid input:
Double.TryParse = 646ms
Convert.ToDouble = 662 ms
Not much different, as expected. For all intents and purposes, for valid input, these are the same.
Invalid input:
Double.TryParse = 612ms
Convert.ToDouble = ..
Well.. it was running for a long time. I reran the entire thing using 1,000 iterations and Convert.ToDouble
with bad input took 8.3 seconds. Averaging it out, it would take over 2 hours. I don't care how basic the test is, in the invalid input case, Convert.ToDouble
's exception raising will ruin your performance.
So, here's another vote for TryParse
with some numbers to back it up.
By an "anonymous class", I take it you mean anonymous inner class.
An anonymous inner class can come useful when making an instance of an object with certain "extras" such as overriding methods, without having to actually subclass a class.
I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener
-- I can just instantiate an anonymous inner class without actually making a separate class.
I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class.
I see a lot of tricks and such being used. Now I'm not against beautiful tricks but personally I like to simply call the methods that are meant to do the work, so I've created yet another answer.
Note that if performance is any issue, use Jon Skeet's answer instead. This one is a bit more generalized and therefore slightly more readable in my opinion (and of course, reusable for strings and patterns).
public static int countOccurances(char c, String input) {
return countOccurancesOfPattern(Pattern.quote(Character.toString(c)), input);
}
public static int countOccurances(String s, String input) {
return countOccurancesOfPattern(Pattern.quote(s), input);
}
public static int countOccurancesOfPattern(String pattern, String input) {
Matcher m = Pattern.compile(pattern).matcher(input);
int count = 0;
while (m.find()) {
count++;
}
return count;
}
Change the profiles parameter to "commandline": "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i"
This works for me and allows for my .bash_profile alias autocomplete scripts to run.
There's one more "hack" by using HTTP Referer (we asume that browser window was closed current referer's domain name and curent page's domain name do not match):
session_start();
$_SESSION['somevariable'] = 'somevalue';
if(parse_url($_SERVER["HTTP_REFERER"], PHP_URL_HOST) != $_SERVER["SERVER_NAME"]){
session_destroy();
}
This also has some drawbacks, but it helped me few times.
You can easily convert object into urlencoded string:
function objToUrlEncode(obj, keys) {
let str = "";
keys = keys || [];
for (let key in obj) {
keys.push(key);
if (typeof (obj[key]) === 'object') {
str += objToUrlEncode(obj[key], keys);
} else {
for (let i in keys) {
if (i == 0) str += keys[0];
else str += `[${keys[i]}]`
}
str += `=${obj[key]}&`;
keys.pop();
}
}
return str;
}
console.log(objToUrlEncode({ key: 'value', obj: { obj_key: 'obj_value' } }));
// key=value&obj[obj_key]=obj_value&
You can call submit()
on the element object in which you entered your text.
Alternatively, you can specifically send the Enter key to it as shown in this Python snippet:
from selenium.webdriver.common.keys import Keys
element.send_keys(Keys.ENTER) # 'element' is the WebElement object corresponding to the input field on the page
Just to offer the alternative to the Test-Path
cmdlet (since nobody mentioned it):
[System.IO.File]::Exists($path)
Does (almost) the same thing as
Test-Path $path -PathType Leaf
except no support for wildcard characters
I created an abstraction layer over FPDI (might accommodate other engines). I published it as a Symfony2 bundle depending on a library, and as the library itself.
usage:
public function handlePdfChanges(Document $document, array $formRawData)
{
$oldPath = $document->getUploadRootDir($this->kernel) . $document->getOldPath();
$newTmpPath = $document->getFile()->getRealPath();
switch ($formRawData['insertOptions']['insertPosition']) {
case PdfInsertType::POSITION_BEGINNING:
// prepend
$newPdf = $this->pdfManager->insert($oldPath, $newTmpPath);
break;
case PdfInsertType::POSITION_END:
// Append
$newPdf = $this->pdfManager->append($oldPath, $newTmpPath);
break;
case PdfInsertType::POSITION_PAGE:
// insert at page n: PdfA={p1; p2; p3}, PdfB={pA; pB; pC}
// insert(PdfA, PdfB, 2) will render {p1; pA; pB; pC; p2; p3}
$newPdf = $this->pdfManager->insert(
$oldPath, $newTmpPath, $formRawData['insertOptions']['pageNumber']
);
break;
case PdfInsertType::POSITION_REPLACE:
// does nothing. overrides old file.
return;
break;
}
$pageCount = $newPdf->getPageCount();
$newPdf->renderFile($mergedPdfPath = "$newTmpPath.merged");
$document->setFile(new File($mergedPdfPath, true));
return $pageCount;
}
To do it programatically in a textview, untested in other views >>
TextView tv = (TextView) findViewById(R.id.mytext);
tv.setText("This is strike-thru");
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
If gnupg2 and gpg-agent 2.x are used, be sure to set the environment variable GPG_TTY
.
export GPG_TTY=$(tty)
the image has a property named Style ( like most of the react-native Compponents) and for Image's Styles, there is a property named resizeMode that takes values like: contain,cover,stretch,center,repeat
most of the time if you use center it will work for you
Others have given the 'Why', so I'll just add that your interface can define a Control; if you wrap it in a property:
public interface IView {
Control Year { get; }
}
public Form : IView {
public Control Year { get { return uxYear; } } //numeric text box or whatever
}
I feel like the simplest solution is sans javascript and simply putting the link in each cell (provided you don't have massive gullies between your cells or really think border lines). Have your css:
.tableClass td a{
display: block;
}
and then add a link per cell:
<table class="tableClass">
<tr>
<td><a href="#link">Link name</a></td>
<td><a href="#link">Link description</a></td>
<td><a href="#link">Link somthing else</a></td>
</tr>
</table>
boring but clean.
One way is:
select table.*
from table
join
(
select ID, max(Date) as max_dt
from table
group by ID
) t
on table.ID= t.ID and table.Date = t.max_dt
Note that if you have multiple equally higher dates for same ID, then you will get all those rows in result
CSS only (no icon sets) Codepen
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
<!-- <a class="navbar-brand" href="#">_x000D_
<img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
Bootstrap_x000D_
</a> -->_x000D_
<!-- https://stackoverflow.com/questions/26317679 -->_x000D_
<a class="nav-link" href="#">_x000D_
<div id="navBars">_x000D_
<input type="checkbox" /><span></span>_x000D_
<span></span>_x000D_
<span></span>_x000D_
</div>_x000D_
</a>_x000D_
<!-- /26317679 -->_x000D_
<div class="collapse navbar-collapse" id="navbarNav">_x000D_
<ul class="navbar-nav">_x000D_
<li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
<li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
<li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</nav>
_x000D_
You can use
$('selector').css({'width:'16px', 'color': 'green', 'margin': '0'});
The best way is to use $('selector').addClass('custom-class') and
.custom-class{
width:16px,
color: green;
margin: 0;
}
on Debian 10
apt install php-mysql
/etc/init.d/apache2 restart
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.
defer works with chrome , firefox , ie > 7 and Safari
ref: https://developer.mozilla.org/en-US/docs/HTML/Element/script
Use __new__
to return value from a class.
As others suggest __repr__
,__str__
or even __init__
(somehow) CAN give you what you want, But __new__
will be a semantically better solution for your purpose since you want the actual object to be returned and not just the string representation of it.
Read this answer for more insights into __str__
and __repr__
https://stackoverflow.com/a/19331543/4985585
class MyClass():
def __new__(cls):
return list() #or anything you want
>>> MyClass()
[] #Returns a true list not a repr or string
That's simple, if you reference them by index. If you want to hide the first column, you would:
Copy code
$('#thetable tr').find('td:nth-child(1),th:nth-child(1)').toggle();
The reason I first selected all table rows and then both td's and th's that were the n'th child is so that we wouldn't have to select the table and all table rows twice. This improves script execution speed. Keep in mind, nth-child()
is 1
based, not 0
.
I use Intellij IDEA but I think it will also work in Android Studio, can you see the "Event Log" at IDE right bottom corner, did it have some message like that "Android framework is detected in the project Configure", that means you should have a framework configuration. If so, just follow the message link.
In the same way, you can go to "File > Project Structure > Modules" , and then add a Android Facet.
by the way, if I want use a customized namespace like you do, I'll write the resource identifier as my package name as I define the AndroidManifest.xml package attribute of the manifest element, below is my code.
<manifest package="com.my.name.android">
...
</manifest>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/apk/res/com.my.name.android">
</RelativeLayout>
Hope this helps you.
The only thing that worked for me on Elementary OS Luna, a Ubuntu Fork. I am on x86 architecture. I tried all the answers here but finally decided to install it from source.
First, make sure its not installed using the package manager:
sudo apt-get purge nodejs npm -y
I went to the download page to lookup the latest source & download it, http://nodejs.org/download/. You can use curl, wget or your browser to get it:
wget http://nodejs.org/dist/v0.10.34/node-v0.10.34.tar.gz
tar -xvf node-v0.10.34.tar.gz
cd node-v0.10.34
./configure
make
sudo make install
The make might take a while. When done, you should have node and npm installed and working in your /usr/local/bin directory which should be already on your path. You should verify where it lives:
which npm node
I also had to change the permissions to get it to work:
sudo chown -R $USER /usr/local
If it didn't work check your path:
echo $PATH
Note that installing it this way, it will not be managed by apt-get package manager. Cheers!
If you really, really want to use strlen(), then
cout << strlen(str.c_str()) << endl;
else the use of .length() is more in keeping with C++.
This error:
python: can't open file 'test.py': [Errno 2] No such file or directory
Means that the file "test.py" doesn't exist. (Or, it does, but it isn't in the current working directory.)
I must save the file in any specific folder to make it run on terminal?
No, it can be where ever you want. However, if you just say, "test.py", you'll need to be in the directory containing test.py.
Your terminal (actually, the shell in the terminal) has a concept of "Current working directory", which is what directory (folder) it is currently "in".
Thus, if you type something like:
python test.py
test.py
needs to be in the current working directory. In Linux, you can change the current working directory with cd
. You might want a tutorial if you're new. (Note that the first hit on that search for me is this YouTube video. The author in the video is using a Mac, but both Mac and Linux use bash
for a shell, so it should apply to you.)
The reason this is failing is because (Python 3) input
returns a string. To convert it to an integer, use int(some_string)
.
You do not typically keep track of indices manually in Python. A better way to implement such a function would be
def cat_n_times(s, n):
for i in range(n):
print(s)
text = input("What would you like the computer to repeat back to you: ")
num = int(input("How many times: ")) # Convert to an int immediately.
cat_n_times(text, num)
I changed your API above a bit. It seems to me that n
should be the number of times and s
should be the string.
To find the env vars dialog in Windows 10:
Right Click Start
>> Click Control Panel (Or you may have System in the list)
>> Click System
>> Click Advanced system settings
>> Go to the Advanced Tab
>> Click the "Environment Variables..." button at the bottom of that dialog page.
What SSL private key should be sent along with the client certificate?
None of them :)
One of the appealing things about client certificates is it does not do dumb things, like transmit a secret (like a password), in the plain text to a server (HTTP basic_auth
). The password is still used to unlock the key for the client certificate, its just not used directly to during exchange or tp authenticate the client.
Instead, the client chooses a temporary, random key for that session. The client then signs the temporary, random key with his cert and sends it to the server (some hand waiving). If a bad guy intercepts anything, its random so it can't be used in the future. It can't even be used for a second run of the protocol with the server because the server will select a new, random value, too.
Fails with: error:14094410:SSL routines:SSL3_READ_BYTES:sslv3 alert handshake failure
Use TLS 1.0 and above; and use Server Name Indication.
You have not provided any code, so its not clear to me how to tell you what to do. Instead, here's the OpenSSL command line to test it:
openssl s_client -connect www.example.com:443 -tls1 -servername www.example.com \
-cert mycert.pem -key mykey.pem -CAfile <certificate-authority-for-service>.pem
You can also use -CAfile
to avoid the “verify error:num=20”. See, for example, “verify error:num=20” when connecting to gateway.sandbox.push.apple.com.
https://docs.angularjs.org/guide/$location#html-link-rewriting
In cases like the following, links are not rewritten; instead, the browser will perform a full page reload to the original link.
Links that contain target element Example:
<a href="/ext/link?a=b" target="_self">link</a>
Absolute links that go to a different domain Example:
<a href="http://angularjs.org/">link</a>
Links starting with '/' that lead to a different base path when base is defined Example:
<a href="/not-my-base/link">link</a>
So in your case, you should add a target attribute like so...
<a target="_self" href="example.com/uploads/asd4a4d5a.pdf" download="foo.pdf">
git log --format="%H" -n 1
Use the above command to get the commitid, hope this helps.
Try this
CSS
.header{
height:30px;
}
.Content{
height: 100%;
overflow: auto;
padding-top: 10px;
padding-bottom: 40px;
}
.Footer{
position: relative;
margin-top: -30px; /* negative value of footer height */
height: 30px;
clear:both;
}
HTML
<body>
<div class="Header">Header</div>
<div class="Content">Content</div>
<div class="Footer">Footer</div>
</body>
In case someone is still looking for a solution for this, the following plugin does the job http://mohammadyounes.github.io/jquery-scrollLock/
It fully addresses the issue of locking mouse wheel scroll inside a given container, preventing it from propagating to parent element.
It does not change wheel scrolling speed, user experience will not be affected. and you get the same behavior regardless of the OS mouse wheel vertical scrolling speed (On Windows it can be set to one screen or one line up to 100 lines per notch).
Demo: http://mohammadyounes.github.io/jquery-scrollLock/example/
The best solution if you don't care about staging modified files is to use git add -u
as said by mshameers and/or pb2q.
If you just want to remove deleted files, but not stage any modified ones, I think you should use the ls-files
argument with the --deleted
option (no need to use regex or other complex args/options) :
git ls-files --deleted | xargs git rm
Thanks to @a_horse_with_no_name's comment, I changed my PGPORT definition to 5432 in pg_env.sh. That fixed the problem for me. I don't know why postgres set it as 5433 initially when it was hosting the service at 5432.
You have to escape the double quote with a backslash.
s = s.Replace("\"","");
There's a Windows answer, and a Debian answer, so here's a Mac one:
This assumes you're just here looking for a quick way to make a customisable alert sound, and not specifically the piezeoelectric beep you get on Windows:
os.system( "say beep" )
Disclaimer: You can replace os.system
with a call to the subprocess
module if you're worried about someone hacking on your beep code.
Try turning the IEnumerable
into a List
. From this point on you will be able to use List
's Remove
method to remove items.
To pass it as a param to the Remove
method using Linq you can get the item by the following methods:
users.Single(x => x.userId == 1123)
users.First(x => x.userId == 1123)
The code is as follows:
users = users.ToList(); // Get IEnumerable as List
users.Remove(users.First(x => x.userId == 1123)); // Remove item
// Finished
The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).
You can use the GUI to do the installation, or you can script the installation of msbuild:
vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet
Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:
You can find documentation about the other available CLI switches here.
The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet
there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin
.
If you don't see them there, try running without --quiet
to see any error messages that may occur during installation.
You could use the between function to get all records between 2010-08-03 00:00:00:000 AND 2010-08-03 23:59:59:000
I have also face the Auth Fail issue, the problem with my code is that I have
channelSftp.cd("");
It changed it to
channelSftp.cd(".");
Then it works.