Your selector is missing a .
and though you say you want to change the border-color
- you're adding and removing a class that sets the background-color
As pointed out on a comment by amalloy, if by "current and last versions" you mean the last commit and the commit before that, you could simply use
git show
I have figured it out a bit of a strange way of doing it compared to the old WF forms:
ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;
string value = typeItem.Content.ToString();
Somewhere, you need to tell Apache that people are allowed to see contents of this directory.
<Directory "F:/bar/public">
Order Allow,Deny
Allow from All
# Any other directory-specific stuff
</Directory>
According to Microsoft's documentation
On the Tools menu, point to Macro, and then click Macros.
In the Macro name box, enter the name of the macro you want to assign to a keyboard shortcut key.
Click Options.
If you want to run the macro by pressing a keyboard shortcut key, enter a letter in the Shortcut key box. You can use CTRL+ letter (for lowercase letters) or CTRL+SHIFT+ letter (for uppercase letters), where letter is any letter key on the keyboard. The shortcut key cannot use a number or special character, such as @
or #
.
Note: The shortcut key will override any equivalent default Microsoft Excel shortcut keys while the workbook that contains the macro is open.
If you want to include a description of the macro, type it in the Description box.
Click OK.
Click Cancel.
Python can use all memory available to its environment. My simple "memory test" crashes on ActiveState Python 2.6 after using about
1959167 [MiB]
On jython 2.5 it crashes earlier:
239000 [MiB]
probably I can configure Jython to use more memory (it uses limits from JVM)
Test app:
import sys
sl = []
i = 0
# some magic 1024 - overhead of string object
fill_size = 1024
if sys.version.startswith('2.7'):
fill_size = 1003
if sys.version.startswith('3'):
fill_size = 497
print(fill_size)
MiB = 0
while True:
s = str(i).zfill(fill_size)
sl.append(s)
if i == 0:
try:
sys.stderr.write('size of one string %d\n' % (sys.getsizeof(s)))
except AttributeError:
pass
i += 1
if i % 1024 == 0:
MiB += 1
if MiB % 25 == 0:
sys.stderr.write('%d [MiB]\n' % (MiB))
In your app you read whole file at once. For such big files you should read the line by line.
use if (testString.Equals(testString2))
.
Lookups in lists are O(n), lookups in dictionaries are amortized O(1), with regard to the number of items in the data structure. If you don't need to associate values, use sets.
Both dictionaries and sets use hashing and they use much more memory than only for object storage. According to A.M. Kuchling in Beautiful Code, the implementation tries to keep the hash 2/3 full, so you might waste quite some memory.
If you do not add new entries on the fly (which you do, based on your updated question), it might be worthwhile to sort the list and use binary search. This is O(log n), and is likely to be slower for strings, impossible for objects which do not have a natural ordering.
Microsoft says here
Table variables does not have distribution statistics, they will not trigger recompiles. Therefore, in many cases, the optimizer will build a query plan on the assumption that the table variable has no rows. For this reason, you should be cautious about using a table variable if you expect a larger number of rows (greater than 100). Temp tables may be a better solution in this case.
setTimout
executes outside of angular. You need to use $timeout
service for this to work:
var app = angular.module('test', []);
app.controller('TestCtrl', function ($scope, $timeout) {
$scope.testValue = 0;
$timeout(function() {
console.log($scope.testValue++);
}, 500);
});
The reason is that two-way binding in angular uses dirty checking. This is a good article to read about angular's dirty checking. $scope.$apply()
kicks off a $digest
cycle. This will apply the binding. $timeout
handles the $apply
for you so it is the recommended service to use when using timeouts.
Essentially, binding happens during the $digest
cycle (if the value is seen to be different).
In the following line.
temp.Response = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();
You are calling First but the collection returned from db.Responses.Where is empty.
There are several ways to do plots in R; lattice
is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:
Reasonstats <- read.table(text="Category Reason Species
Decline Genuine 24
Improved Genuine 16
Improved Misclassified 85
Decline Misclassified 41
Decline Taxonomic 2
Improved Taxonomic 7
Decline Unclear 41
Improved Unclear 117", header=T)
ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3 <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason
windows()
barplot(t(Reasonstats3), beside=TRUE, ylab="number of species",
cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
box(bty="l")
Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline
and for Improved
. Then I made those categories the column names. I also made the Reason
s the row names. The barplot()
function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot()
function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot()
wants for your intended output.
With my experiance the best open source option will be UIKIT with its uikit slider component. and it is very easy to implement for example in your case you could do something like this.
<div data-uk-slider>
<div class="uk-slider-container">
<ul class="uk-slider uk-grid-width-medium-1-4"> // width of the elements
<li>...</li> //slide elements
...
</ul>
</div>
If you just want the old file in your working copy:
svn up -r 147 myfile.py
If you want to rollback, see this "How to return to an older version of our code in subversion?".
Yes. Youtube API is the best resource for this.
There are 3 way to embed a video:
<iframe>
tagsDEPRECATED
I think you are looking for the second one of them:
The HTML and JavaScript code below shows a simple example that inserts a YouTube player into the page element that has an id value of ytplayer. The onYouTubePlayerAPIReady() function specified here is called automatically when the IFrame Player API code has loaded. This code does not define any player parameters and also does not define other event handlers.
<div id="ytplayer"></div>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE'
});
}
</script>
Here are some instructions where you may take a look when starting using the API.
An embed example without using iframe
is to use <object>
tag:
<object width="640" height="360">
<param name="movie" value="http://www.youtube.com/embed/yt-video-id?html5=1&rel=0&hl=en_US&version=3"/
<param name="allowFullScreen" value="true"/>
<param name="allowscriptaccess" value="always"/>
<embed width="640" height="360" src="http://www.youtube.com/embed/yt-video-id?html5=1&rel=0&hl=en_US&version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>
(replace yt-video-id
with your video id)
unset
is a function, not an operator. Use it like unset($_SESSION['key']);
to unset that session key. You can, however, use session_destroy();
as well. (Make sure to start the session with session_start();
as well)
Use the -S (note: capital S) switch to GCC, and it will emit the assembly code to a file with a .s extension. For example, the following command:
gcc -O2 -S -c foo.c
I have tried dozens of XML editors hoping to find one which would be able to do some kind of visualization. The best lightweight viewer for windows I have found was XMLMarker - too bad the project has been dead for some years now. It is not so useful as an editor, but it does a good job of displaying flat XML data as tables.
There are tons of free editors that do XML syntax highlighting, including vim, emacs, scite, eclipse (J2EE edition), jedit, notepad++.
For heavyweight XML features, like XPath support, XSLT editing and debugging, SOAP/WSDL there are some good commercial tools like, XMLSpy, Oxygen, StylusStudio.
JEdit is open-source and also has plugins for XML, XPath and XSLT.
Word-2003 is fairly good for visualizing (but don't use it for editing). Excel-2003 and up also does a good job at visualizing flat XML data and can apply XSL transformations (again, no good as an editor).
HTML:
<div class="control-group">
<input class="btn" type="submit" value="Log in" ng-click="login.onSubmit($event)">
</div>
In your controller:
$scope.login = {
onSubmit: function(event) {
if (dataIsntValid) {
displayErrors();
event.preventDefault();
}
else {
submitData();
}
}
}
In my view page:
<p:dataTable ...>
<p:column>
<p:commandLink actionListener="#{inquirySOController.viewDetail}"
process="@this" update=":mainform:dialog_content"
oncomplete="dlg2.show()">
<h:graphicImage library="images" name="view.png"/>
<f:param name="trxNo" value="#{item.map['trxNo']}"/>
</p:commandLink>
</p:column>
</p:dataTable>
backing bean
public void viewDetail(ActionEvent e) {
String trxNo = getFacesContext().getRequestParameterMap().get("trxNo");
for (DTO item : list) {
if (item.get("trxNo").toString().equals(trxNo)) {
System.out.println(trxNo);
setSelectedItem(item);
break;
}
}
}
The following generic solution can be used with regular login, a Spring Social login, or most other Spring Security filters.
In your Spring MVC controller, when loading the product page, save the path to the product page in the session if user has not been logged in. In XML config, set the default target url. For example:
In your Spring MVC controller, the redirect method should read out the path from the session and return redirect:<my_saved_product_path>
.
So, after user logs in, they'll be sent to /redirect
page, which will promptly redirect them back to the product page that they last visited.
It is also possible to find that out using the fopen(),fseek() and ftell() function.
int get_file_size(std::string filename) // path to file
{
FILE *p_file = NULL;
p_file = fopen(filename.c_str(),"rb");
fseek(p_file,0,SEEK_END);
int size = ftell(p_file);
fclose(p_file);
return size;
}
To have text-align:center
work you need to add that style to the #siteInfo
div or wrap the input in a paragraph and add text-align:center
to the paragraph.
The column is ambiguous because it appears in both tables you would need to specify the where (or sort) field fully such as us_music.genre or de_music.genre but you'd usually specify two tables if you were then going to join them together in some fashion. The structure your dealing with is occasionally referred to as a partitioned table although it's usually done to separate the dataset into distinct files as well rather than to just split the dataset arbitrarily. If you're in charge of the database structure and there's no good reason to partition the data then I'd build one big table with an extra "origin" field that contains a country code but you're probably doing it for legitimate performance reason. Either use a union to join the tables you're interested in http://dev.mysql.com/doc/refman/5.0/en/union.html or by using the Merge database engine http://dev.mysql.com/doc/refman/5.1/en/merge-storage-engine.html.
@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.
For that we have provide one setter method for myobj and set the myobj value with mocked object.
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
In our Test class, we have to write below code
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
@test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in @before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
The equivalent of unistd.h
on Windows is windows.h
I ran into this issue with Python 3.6
and Python 3.7
. The top answer (running pip install --upgrade pip enum34
) did not solve the problem.
I don't know why, but the reason why this error happen is because enum.py
was missing from .venv/myvenv/lib/python3.7/
.
But the file was in /usr/lib/python3.7/
.
Following this answer, I just created the symbolic link by myself :
ln -s /usr/lib/python3.7/enum.py .venv/myvenv/lib/python3.7/enum.py
Ok, You should "construct" the html and find the .content div.
like this:
$.ajax({
url:href,
type:'GET',
success: function(data){
$('#content').html($(data).find('#content').html());
}
});
Simple!
A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.
public class UrlPrettyfierFilter implements Filter {
private static final String JSF_VIEW_ROOT_PATH = "/ui";
private static final String JSF_VIEW_SUFFIX = ".xhtml";
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
String requestURI = httpServletRequest.getRequestURI();
//Only process the paths starting with /ui, so as other requests get unprocessed.
//You can register the filter itself for /ui/* only, too
if (requestURI.startsWith(JSF_VIEW_ROOT_PATH)
&& !requestURI.contains(JSF_VIEW_SUFFIX)) {
request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
.forward(request,response);
} else {
chain.doFilter(httpServletRequest, response);
}
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
int dp1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1,
context.getResources().getDisplayMetrics());
tv.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
dp1 * 100)); // if you want to set layout height to 100dp
llview.addView(tv);
VAR=$(scan)
Exactly the same way as for programs.
Dowlnoad sqlite manager and install it from Here.Open the sqlite file using that browser.
In my case I ran on this problem while using Edge.js — all the problem was a JavaScript syntax error inside a C# Edge.js function definition.
Another option is snprintf
:
double pi = 3.1415926;
std::string s(16, '\0');
auto written = std::snprintf(&s[0], s.size(), "%.2f", pi);
s.resize(written);
Demo. Error handling should be added, i.e. checking for written < 0
.
It's not enough to have just compile project("xy")
dependency.
You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).
Create a settings.gradle file in the root of your project and add this:
include ':progressfragment'
to that file. Then sync Gradle and it should work.
Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.
In 2007 my project successfully used OpenOffice.org's Universal Network Objects (UNO) interface to programmatically generate MS-Word compatible documents (*.doc), as well as corresponding PDF documents, from a Java Web application (a Struts/JSP framework).
OpenOffice UNO also lets you build MS-Office-compatible charts, spreadsheets, presentations, etc. We were able to dynamically build sophisticated Word documents, including charts and tables.
We simplified the process by using template MS-Word documents with bookmark inserts into which the software inserted content, however, you can build documents completely from scratch. The goal was to have the software generate report documents that could be shared and further tweaked by end-users before converting them to PDF for final delivery and archival.
You can optionally produce documents in OpenOffice formats if you want users to use OpenOffice instead of MS-Office. In our case the users want to use MS-Office tools.
UNO is included within the OpenOffice suite. We simply linked our Java app to UNO-related libraries within the suite. An OpenOffice Software Development Kit (SDK) is available containing example applications and the UNO Developer's Guide.
I have not investigated whether the latest OpenOffice UNO can generate MS-Office 2007 Open XML document formats.
The important things about OpenOffice UNO are:
Here are some useful web sites:
Use JQuery
var scale=0.5;
minWidth=50;
minHeight=100;
if($("#id img").width()*scale>minWidth && $("#id img").height()*scale >minHeight)
{
$("#id img").width($("#id img").width()*scale);
$("#id img").height($("#id img").height()*scale);
}
You can use bcp utility.
To copy the result set from a Transact-SQL statement to a data file, use the queryout option. The following example copies the result of a query into the Contacts.txt data file. The example assumes that you are using Windows Authentication and have a trusted connection to the server instance on which you are running the bcp command. At the Windows command prompt, enter:
bcp "<your query here>" queryout Contacts.txt -c -T
You can use BCP by directly calling as operating sytstem command in SQL Agent job.
Add the following:
using System.Linq
...and call ToList()
on the IQueryable<>
.
Here's is a solution that I developed today in Python, using the docker inspect container
JSON output as the data source.
I have a lot of containers and infrastructures that I have to inspect, and I need to obtain basic network information from any container, in a fast and pretty manner. That's why I made this script.
IMPORTANT: Since the version 1.9, Docker allows you to create multiple networks and attach them to the containers.
#!/usr/bin/python
import json
import subprocess
import sys
try:
CONTAINER = sys.argv[1]
except Exception as e:
print "\n\tSpecify the container name, please."
print "\t\tEx.: script.py my_container\n"
sys.exit(1)
# Inspecting container via Subprocess
proc = subprocess.Popen(["docker","inspect",CONTAINER],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
out = proc.stdout.read()
json_data = json.loads(out)[0]
net_dict = {}
for network in json_data["NetworkSettings"]["Networks"].keys():
net_dict['mac_addr'] = json_data["NetworkSettings"]["Networks"][network]["MacAddress"]
net_dict['ipv4_addr'] = json_data["NetworkSettings"]["Networks"][network]["IPAddress"]
net_dict['ipv4_net'] = json_data["NetworkSettings"]["Networks"][network]["IPPrefixLen"]
net_dict['ipv4_gtw'] = json_data["NetworkSettings"]["Networks"][network]["Gateway"]
net_dict['ipv6_addr'] = json_data["NetworkSettings"]["Networks"][network]["GlobalIPv6Address"]
net_dict['ipv6_net'] = json_data["NetworkSettings"]["Networks"][network]["GlobalIPv6PrefixLen"]
net_dict['ipv6_gtw'] = json_data["NetworkSettings"]["Networks"][network]["IPv6Gateway"]
for item in net_dict:
if net_dict[item] == "" or net_dict[item] == 0:
net_dict[item] = "null"
print "\n[%s]" % network
print "\n{}{:>13} {:>14}".format(net_dict['mac_addr'],"IP/NETWORK","GATEWAY")
print "--------------------------------------------"
print "IPv4 settings:{:>16}/{:<5} {}".format(net_dict['ipv4_addr'],net_dict['ipv4_net'],net_dict['ipv4_gtw'])
print "IPv6 settings:{:>16}/{:<5} {}".format(net_dict['ipv6_addr'],net_dict['ipv6_net'],net_dict['ipv6_gtw'])
The output is:
$ python docker_netinfo.py debian1
[frontend]
02:42:ac:12:00:02 IP/NETWORK GATEWAY
--------------------------------------------
IPv4 settings: 172.18.0.2/16 172.18.0.1
IPv6 settings: null/null null
[backend]
02:42:ac:13:00:02 IP/NETWORK GATEWAY
--------------------------------------------
IPv4 settings: 172.19.0.2/16 172.19.0.1
IPv6 settings: null/null null
That means you must install simplejson
. On newer versions of python, it was included by default into python's distribution, and renamed to json
. So if you are on python 2.6+ you should change all instances of simplejson
to json
.
For a quick fix you could also edit the file and change the line:
import simplejson
to:
import json as simplejson
and hopefully things will work.
Here is a SUPER SIMPLE implementation/example of a FSM using just "if-else"s which avoids all of the above subclassing answers (taken from Using Finite State Machines for Pattern Matching in Java, where he is looking for a string which ends with "@" followed by numbers followed by "#"--see state graph here):
public static void main(String[] args) {
String s = "A1@312#";
String digits = "0123456789";
int state = 0;
for (int ind = 0; ind < s.length(); ind++) {
if (state == 0) {
if (s.charAt(ind) == '@')
state = 1;
} else {
boolean isNumber = digits.indexOf(s.charAt(ind)) != -1;
if (state == 1) {
if (isNumber)
state = 2;
else if (s.charAt(ind) == '@')
state = 1;
else
state = 0;
} else if (state == 2) {
if (s.charAt(ind) == '#') {
state = 3;
} else if (isNumber) {
state = 2;
} else if (s.charAt(ind) == '@')
state = 1;
else
state = 0;
} else if (state == 3) {
if (s.charAt(ind) == '@')
state = 1;
else
state = 0;
}
}
} //end for loop
if (state == 3)
System.out.println("It matches");
else
System.out.println("It does not match");
}
P.S: Does not answer your question directly, but shows you how to implement a FSM very easily in Java.
And if you just want to get the directory name and no need for the filename coming with it, then you can do that in the following conventional way using os
Python module.
>>> import os
>>> f = open('/Users/Desktop/febROSTER2012.xls')
>>> os.path.dirname(f.name)
>>> '/Users/Desktop/'
This way you can get hold of the directory structure.
With python or pandas when you use read_csv
or pd.read_csv
, both of them look into current working directory, by default where the python process have started. So you need to use os
module to chdir()
and take it from there.
import pandas as pd
import os
print(os.getcwd())
os.chdir("D:/01Coding/Python/data_sets/myowndata")
print(os.getcwd())
df = pd.read_csv('data.csv',nrows=10)
print(df.head())
I could install it in a windows machine and using Anaconda/Spyder with python 2.7 through the following commands:
!pip install psycopg2
Then to establish the connection to the database:
import psycopg2
conn = psycopg2.connect(dbname='dbname',host='host_name',port='port_number', user='user_name', password='password')
WebClient client = new WebClient();
using (Stream data = client.OpenRead(Text))
{
using (StreamReader reader = new StreamReader(data))
{
string content = reader.ReadToEnd();
string pattern = @"((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)";
MatchCollection matches = Regex.Matches(content,pattern);
List<string> urls = new List<string>();
foreach (Match match in matches)
{
urls.Add(match.Value);
}
}
If you need this solution for only few types of modals just use
style="width:90%"
attribute.
example:
div class="modal-dialog modal-lg" style="width:90%"
note: this will change only this particular modal
I don't know about methods; however, the type to GUID can be done via:
Guid iid = System.Runtime.InteropServices.Marshal.GenerateGuidForType(typeof(IFoo));
.size()
is not a native JS function of Array
(at least not in any browser that I know of).
.length
should be used.
.size()
does work on your page, make sure you do not have any extra libraries included like prototype that is mucking with the Array
prototype.
There might be some plugin on your browser that is mucking with the Array
prototype.
Same as above, might help some people.
setTimeout(() => {
if (pushToken!=null && deviceId!=null) {
console.log("pushToken & OS ");
this.setState({ pushToken: pushToken});
this.setState({ deviceId: deviceId });
console.log("pushToken & OS "+pushToken+"\n"+deviceId);
}
}, 1000);
What about this solution?
div.commentList > article.comment:not(:last-child):last-of-type
{
color:red; /*or whatever...*/
}
BUILDING Again on Nathan and JB's Answer:
How To Launch App From url w/o Extra Click If you prefer a solution that does not include the interim step of clicking a link, the following can be used. With this javascript, I was able to return a Httpresponse object from Django/Python that successfully launches an app if it is installed or alternatively launches the app store in the case of a time out. Note I also needed to adjust the timeout period from 500 to 100 in order for this to work on an iPhone 4S. Test and tweak to get it right for your situation.
<html>
<head>
<meta name="viewport" content="width=device-width" />
</head>
<body>
<script type="text/javascript">
// To avoid the "protocol not supported" alert, fail must open another app.
var appstorefail = "itms://itunes.apple.com/us/app/facebook/id284882215?mt=8&uo=6";
var loadedAt = +new Date;
setTimeout(
function(){
if (+new Date - loadedAt < 2000){
window.location = appstorefail;
}
}
,100);
function LaunchApp(){
window.open("unknown://nowhere","_self");
};
LaunchApp()
</script>
</body>
</html>
$ find proj
proj
proj/src
proj/src/index.js
$ cat proj/src/index.js
console.log("process.cwd() = " + process.cwd());
console.log("__dirname = " + __dirname);
$ cd proj; node src/index.js
process.cwd() = /tmp/proj
__dirname = /tmp/proj/src
The error message outlines the solution. The line
doNothing().when(cmd).dnsCheck(HOST, any(InetAddressFactory.class))
uses one raw value and one matcher, when it's required to use either all raw values or all matchers. A correct version might read
doNothing().when(cmd).dnsCheck(eq(HOST), any(InetAddressFactory.class))
You need to do two additional things after following the link that you have mentioned in your post:
One have to map the changed login cridentials in phpmyadmin's config.inc.php
and second, you need to restart your web and mysql servers..
php version is not the issue here..you need to go to phpmyadmin installation directory and find file config.inc.php
and in that file put your current mysql password at line
$cfg['Servers'][$i]['user'] = 'root'; //mysql username here
$cfg['Servers'][$i]['password'] = 'password'; //mysql password here
First install php-mysql
sudo apt-get install php7.0-mysql
//change the version number based on the php version
then enable the module
sudo phpenmod pdo_mysql
and restart apache
sudo service apache2 restart
Using jQuery will make this simpler.
The following code will take an array of arrays and store convert them into rows and cells.
$.getJSON(url , function(data) {
var tbl_body = "";
var odd_even = false;
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
});
tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
odd_even = !odd_even;
});
$("#target_table_id tbody").html(tbl_body);
});
You could add a check for the keys you want to exclude by adding something like
var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };
at the start of the getJSON callback function and adding:
if ( ( k in expected_keys ) && expected_keys[k] ) {
...
}
around the tbl_row += line.
Edit: Was assigning a null variable previously
Edit: Version based on Timmmm's injection-free contribution.
$.getJSON(url , function(data) {
var tbl_body = document.createElement("tbody");
var odd_even = false;
$.each(data, function() {
var tbl_row = tbl_body.insertRow();
tbl_row.className = odd_even ? "odd" : "even";
$.each(this, function(k , v) {
var cell = tbl_row.insertCell();
cell.appendChild(document.createTextNode(v.toString()));
});
odd_even = !odd_even;
});
$("#target_table_id").append(tbl_body); //DOM table doesn't have .appendChild
});
Your javascript values are client-side, your scriptlet is running server-side. So if you want to use your javascript variables in a scriptlet, you will need to submit them.
To achieve this, either store them in input fields and submit a form, or perform an ajax request. I suggest you look into JQuery for this.
From Working with CSS preprocessors in Chrome DevTools:
Many developers generate CSS style sheets using a CSS preprocessor, such as Sass, Less, or Stylus. Because the CSS files are generated, editing the CSS files directly is not as helpful.
For preprocessors that support CSS source maps, DevTools lets you live-edit your preprocessor source files in the Sources panel, and view the results without having to leave DevTools or refresh the page. When you inspect an element whose styles are provided by a generated CSS file, the Elements panel displays a link to the original source file, not the generated .css file.
Try this as a shortcut, not as a definitive solution (see comments):
<script type="text/javascript">
var ip = location.host;
alert(ip);
</script>
This solution cannot work in some scenarios but it can help for quick testing. Regards
Inside your AJAX callback you need to call the response
function; passing the array that contains items to display.
jQuery("input.suggest-user").autocomplete({
source: function (request, response) {
jQuery.get("usernames.action", {
query: request.term
}, function (data) {
// assuming data is a JavaScript array such as
// ["[email protected]", "[email protected]","[email protected]"]
// and not a string
response(data);
});
},
minLength: 3
});
If the response JSON does not match the formats accepted by jQuery UI autocomplete then you must transform the result inside the AJAX callback before passing it to the response callback. See this question and the accepted answer.
I had this problem and I just realized that if in the server you see the user in the menu SERVER -> USERS AND PRIVILEGES and find the user who has % as HOSTNAME, you can use it instead the root user.
That's all
Open AVD manager and click on the drop down along side with your emulator and select the show in disk and delete the file with .lock extension. After deleted, run your emulator. That works for me.
I recently migrated my MongoDB to DynamoDB, and wrote 3 blogs to share some experience and data about performance, cost.
Migrate from MongoDB to AWS DynamoDB + SimpleDB
Just leaving the default navbar built in with bootstrap works fine.
You just need to add the custom css below, that way everything still works as it should.
HTML:
<nav class="navbar navbar-default">
CSS:
.navbar-default {
background-color: transparent;
}
If user wants to search for the word in given text file.
fopen = open('logfile.txt',mode='r+')
fread = fopen.readlines()
x = input("Enter the search string: ")
for line in fread:
if x in line:
print(line)
newTitle
is a local variable where you create the fields. So when that functions ends, the variable newTitle
, does not exist anymore. (The JTextField that was referenced by newTitle
does still exist however.)
Thus, increase the scope of the variable, so that you can access it another method.
public SomeFrame extends JFrame {
JTextField myTitle;//can be used anywhere in this class
creationOfTheFields()
{
//other code
myTitle = new JTextField("spam");
myTitle.setBounds(80, 40, 225, 20);
options.add(myTitle);
//blabla other code
}
private void New_Name()
{
this.setTitle(myTitle.getText());
}
}
YES YOU CAN.
In your stored procedure, you fill the table @tbRetour
.
At the very end of your stored procedure, you write:
SELECT * FROM @tbRetour
To execute the stored procedure, you write:
USE [...]
GO
DECLARE @return_value int
EXEC @return_value = [dbo].[getEnregistrementWithDetails]
@id_enregistrement_entete = '(guid)'
GO
Ensures that the object is displayed (or should be) only to readers and similar devices. It give more sense in context with other element with attribute aria-hidden="true".
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Error:</span>
Enter a valid email address
</div>
Glyphicon will be displayed on all other devices, word Error: on text readers.
According to the documentation
x += y
is equivalent tox = operator.iadd(x, y)
. Another way to put it is to say thatz = operator.iadd(x, y)
is equivalent to the compound statementz = x; z += y
.
So x += 3
is the same as x = x + 3
.
x = 2
x += 3
print(x)
will output 5.
Notice that there's also
As nobody answer, I try something :
I think I understand why Attent one does not work. It's because joining a computer to a domain is somehow also renaming the computer (the domain name part, enter in the name of the machine).
So do you try to do it in full WMI way, you've got a method in Win32_ComputerSystem
class called JoinDomainOrWorkgroup
. Doing it on the same level perhaps gives you more chance to make it work.
Valentin Rocher's method works if you've extended your view, but if you're using an event listener, use this:
view.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
Toast toast = Toast.makeText(
getApplicationContext(),
"View touched",
Toast.LENGTH_LONG
);
toast.show();
return true;
}
});
// Obtain MotionEvent object
long downTime = SystemClock.uptimeMillis();
long eventTime = SystemClock.uptimeMillis() + 100;
float x = 0.0f;
float y = 0.0f;
// List of meta states found here: developer.android.com/reference/android/view/KeyEvent.html#getMetaState()
int metaState = 0;
MotionEvent motionEvent = MotionEvent.obtain(
downTime,
eventTime,
MotionEvent.ACTION_UP,
x,
y,
metaState
);
// Dispatch touch event to view
view.dispatchTouchEvent(motionEvent);
For more on obtaining a MotionEvent object, here is an excellent answer: Android: How to create a MotionEvent?
var id = $(this).find('option:selected').attr('id');
then you do whatever you want with selectedIndex
I've reedited my answer ... since selectedIndex isn't a good variable to give example...
While this is not a GUI tool, my quick tests indicated that diffxml has some promise. The author appears to have thought about the complexities of representing diffs for nested elements in a standardized way (his DUL - Delta Update Language specification).
Installing and running his tools, I can say that the raw text output is quite clear and concise. It doesn't offer the same degree of immediate apprehension as a GUI tool, but given that the output is standardized as DUL, perhaps you would be able to take that and build a tool to generate a visual representation. I'd certainly love to see one.
The author's "links" section does reference a few other XML differencing tools, but as you mentioned in your post, they're all proprietary.
std::remove
does not actually erase the element from the container, but it does return the new end iterator which can be passed to container_type::erase
to do the REAL removal of the extra elements that are now at the end of the container:
std::vector<int> vec;
// .. put in some values ..
int int_to_remove = n;
vec.erase(std::remove(vec.begin(), vec.end(), int_to_remove), vec.end());
It's not really an anwser but a workaround to open a local link in chrome using python.
Copy the local link you want to run then run the code bellow (using a shortcut), it will open your link.
import win32clipboard
import os
win32clipboard.OpenClipboard()
clipboard_data= win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
os.system("start "+clipboard_data)
RUN is an image build step, the state of the container after a RUN
command will be committed to the container image. A Dockerfile can have many RUN
steps that layer on top of one another to build the image.
CMD is the command the container executes by default when you launch the built image. A Dockerfile will only use the final CMD
defined. The CMD
can be overridden when starting a container with docker run $image $other_command
.
ENTRYPOINT is also closely related to CMD
and can modify the way a container starts an image.
do it simply
public class Test{
public Test(){
design();
}//end Test()
public void design(){
JFame f = new JFrame();
f.setSize(int w, int h);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
JPanel p = new JPanel();
f.getContentPane().add(p);
}
public static void main(String[] args){
EventQueue.invokeLater(new Runnable(){
public void run(){
try{
new Test();
}catch(Exception e){
e.printStackTrace();
}
}
);
}
}
Here is what I have found:
Use RenderAction when you do not have a model to send to the view and have a lot of html to bring back that doesn't need to be stored in a variable.
Use Action when you do not have a model to send to the view and have a little bit of text to bring back that needs to be stored in a variable.
Use RenderPartial when you have a model to send to the view and there will be a lot of html that doesn't need to be stored in a variable.
Use Partial when you have a model to send to the view and there will be a little bit of text that needs to be stored in a variable.
RenderAction and RenderPartial are faster.
The way i do it is:
var obj = new Object();
obj.name = "Raj";
obj.age = 32;
obj.married = false;
var jsonString= JSON.stringify(obj);
I guess this way can reduce chances for errors.
When I faced this issue the following solved it for me:
I was calling a OpenCV dll from inside another exe, my dll did not contained the already needed opencv dlls like highgui, features2d, and etc available in the folder of my exe file. I copied all these to the directory of my exe project and it suddenly worked.
Yes, this is a classpath issue. You need to tell the compiler and runtime that the directory where your .class files live is part of the CLASSPATH. The directory that you need to add is the parent of the "com" directory at the start of your package structure.
You do this using the -classpath argument for both javac.exe and java.exe.
Should also ask how the 3rd party classes you're using are packaged. If they're in a JAR, and I'd recommend that you have them in one, you add the .jar file to the classpath:
java -classpath .;company.jar foo.bar.baz.YourClass
Google for "Java classpath". It'll find links like this.
One more thing: "import" isn't loading classes. All it does it save you typing. When you include an import statement, you don't have to use the fully-resolved class name in your code - you can type "Foo" instead of "com.company.thing.Foo". That's all it's doing.
In My Case Used this Method:
public static float pxFromDp(float dp, Context mContext) {
return dp * mContext.getResources().getDisplayMetrics().density;
}
Here Set TextView's TextSize Programatically :
textView.setTextSize(pxFromDp(18, YourActivity.this));
Keep Enjoying:)
Just my 2 cents on the subject. I was having the exact same issue with trying to connect from MySQL Workbench. I'm running a bitnami-mysql virtual machine to set up a local sandbox for development.
Bitnami's tutorial said to run the 'Grant All Privileges' command:
/opt/bitnami/mysql/bin/mysql -u root -p -e "grant all privileges on *.* to 'root'@'%' identified by 'PASSWORD' with grant option";
This was clearly not working, I finally got it to work using Mike Lischke's answer.
What I think happened was that the root@% user had the wrong credentials associated to it. So if you've tried to modify the user's privileges and with no luck try:
From Mysql Console:
List Users (helpful to see all your users):
select user, host from mysql.user;
Drop Desired User:
drop user '{{ username }}'@'%';
Create User and Grant Permissions:
CREATE USER '{{ username }}'@'%' IDENTIFIED BY '{{ password }}';
GRANT ALL PRIVILEGES ON *.* TO '{{ username }}'@'%' WITH GRANT OPTION;
Run this command:
FLUSH PRIVILEGES;
Locate your mysql config file 'my.cnf' and look for a line that looks like this:
bind-address=127.0.0.1
and comment it using a '#':
#bind-address=127.0.0.1
Then restart your mysql service.
Hope this helps someone having the same issue!
internal is for assembly scope (i.e. only accessible from code in the same .exe or .dll)
private is for class scope (i.e. accessible only from code in the same class).
If you use numpy
, this is easy:
slice = arr[:2,:2]
or if you want the 0's,
slice = arr[0:2,0:2]
You'll get the same result.
*note that slice
is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".
Another way, if you're working with lists of lists*:
slice = [arr[i][0:2] for i in range(0,2)]
(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)]
would also work.).
What I did here is that I take each desired row 1 at a time (arr[i]
). I then slice the columns I want out of that row and add it to the list that I'm building.
If you naively try: arr[0:2]
You get the first 2 rows which if you then slice again arr[0:2][0:2]
, you're just slicing the first two rows over again.
*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.
I like Mozzi's answer but found that it did not retain the default fonts that are user specific. The text all appeared in a system font as normal text. The code below retains the user's favourite fonts, while making it only a little longer. It is based on Mozzi's approach, uses a regular expression to replace the default body text and places the user's chosen Body text where it belongs by using GetInspector.WordEditor. I found that the call to GetInspector did not populate the HTMLbody as dimitry streblechenko says above in this thread, at least, not in Office 2010, so the object is still displayed in my code. In passing, please note that it is important that the MailItem is created as an Object, not as a straightforward MailItem - see here for more. (Oh, and sorry to those of different tastes, but I prefer longer descriptive variable names so that I can find routines!)
Public Function GetSignedMailItemAsObject(ByVal ToAddress As String, _
ByVal Subject As String, _
ByVal Body As String, _
SignatureName As String) As Object
'================================================================================================================='Creates a new MailItem in HTML format as an Object.
'Body, if provided, replaces all text in the default message.
'A Signature is appended at the end of the message.
'If SignatureName is invalid any existing default signature is left in place.
'=================================================================================================================
' REQUIRED REFERENCES
' VBScript regular expressions (5.5)
' Microsoft Scripting Runtime
'=================================================================================================================
Dim OlM As Object 'Do not define this as Outlook.MailItem. If you do, some things will work and some won't (i.e. SendUsingAccount)
Dim Signature As String
Dim Doc As Word.Document
Dim Regex As New VBScript_RegExp_55.RegExp '(can also use use Object if VBScript is not Referenced)
Set OlM = Application.CreateItem(olMailItem)
With OlM
.To = ToAddress
.Subject = Subject
'SignatureName is the exactname that you gave your signature in the Message>Insert>Signature Dialog
Signature = GetSignature(SignatureName)
If Signature <> vbNullString Then
' Should really strip the terminal </body tag out of signature by removing all characters from the start of the tag
' but Outlook seems to handle this OK if you don't bother.
.Display 'Needed. Without it, there is no existing HTMLbody available to work with.
Set Doc = OlM.GetInspector.WordEditor 'Get any existing body with the WordEditor and delete all of it
Doc.Range(Doc.Content.Start, Doc.Content.End) = vbNullString 'Delete all existing content - we don't want any default signature
'Preserve all local email formatting by placing any new body text, followed by the Signature, into the empty HTMLbody.
With Regex
.IgnoreCase = True 'Case insensitive
.Global = False 'Regex finds only the first match
.MultiLine = True 'In case there are stray EndOfLines (there shouldn't be in HTML but Word exports of HTML can be dire)
.Pattern = "(<body.*)(?=<\/body)" 'Look for the whole HTMLbody but do NOT include the terminal </body tag in the value returned
OlM.HTMLbody = .Replace(OlM.HTMLbody, "$1" & Signature)
End With ' Regex
Doc.Range(Doc.Content.Start, Doc.Content.Start) = Body 'Place the required Body before the signature (it will get the default style)
.Close olSave 'Close the Displayed MailItem (actually Object) and Save it. If it is left open some later updates may fail.
End If ' Signature <> vbNullString
End With ' OlM
Set GetSignedMailItemAsObject = OlM
End Function
Private Function GetSignature(sigName As String) As String
Dim oTextStream As Scripting.TextStream
Dim oSig As Object
Dim appDataDir, Signature, sigPath, fileName As String
Dim FileSys As Scripting.FileSystemObject 'Requires Microsoft Scripting Runtime to be available
appDataDir = Environ("APPDATA") & "\Microsoft\Signatures"
sigPath = appDataDir & "\" & sigName & ".htm"
Set FileSys = CreateObject("Scripting.FileSystemObject")
Set oTextStream = FileSys.OpenTextFile(sigPath)
Signature = oTextStream.ReadAll
' fix relative references to images, etc. in Signature
' by making them absolute paths, OL will find the image
fileName = Replace(sigName, ".htm", "") & "_files/"
Signature = Replace(Signature, fileName, appDataDir & "\" & fileName)
GetSignature = Signature
End Function
If you are also running skype at the same time. It will give you error:
port 80 running a another webserver
First close skype and restart your apache it will work fine.
Try:
$articles = DB::table('articles')
->select('articles.id as articles_id', ..... )
->join('categories', 'articles.categories_id', '=', 'categories.id')
->join('users', 'articles.user_id', '=', 'user.id')
->get();
For me, I encountered this error many times,
Error inflating class android.support.design.widget.NavigationView #28 and #29
The solution that works for me is that you must match your support design library and your support appcompat library.
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
For me they must match. :) It works for me!
Using Date object guarantees that. For eg if you try to create April 31st
:
new Date(2014,3,31) // Thu May 01 2014 00:00:00
Please note that it's zero indexed, so Jan. is
0
, Feb. is1
etc.
it might sound strange but for me worked restarting my mac..i cant explain why and what happened but it works now. hope it will helps someone
<input type="submit" value="Create" name="button"/>_x000D_
<input type="submit" value="Reset" name="button" />
_x000D_
write the following code in Controler.
[HttpPost]
public ActionResult Login(string button)
{
switch (button)
{
case "Create":
return RedirectToAction("Deshboard", "Home");
break;
case "Reset":
return RedirectToAction("Login", "Home");
break;
}
return View();
}
$(document).on('click', 'selector', handler);
Where click
is an event name, and handler
is an event handler, like reference to a function or anonymous function function() {}
PS: if you know the particular node you're adding dynamic elements to - you could specify it instead of document
.
The C++ way would be to use a std::stringstream
object as:
std::stringstream fmt;
fmt << a << " " << b << " > " << c;
The C way would be to use sprintf
.
The C way is difficult to get right since:
Of course, you may want to fall back on the C way if performance is an issue (imagine you are creating fixed-size million little stringstream
objects and then throwing them away).
Since Oracle 12C, you can fetch a specific number of rows with FETCH FIRST ROW ONLY
.
In your case this implies an ORDER BY
, so the performance should be considered.
SELECT A, col_date
FROM TABLENAME t_ext
ORDER BY col_date DESC NULLS LAST
FETCH FIRST 1 ROW ONLY;
The NULLS LAST
is just in case you may have null values in your field.
du -aS /PATH/TO/folder | sort -rn | head -2 | tail -1
or
du -aS /PATH/TO/folder | sort -rn | awk 'NR==2'
You should first make sure that the process has completed running and the return code has been read out using the .wait
method. This will return the code. If you want access to it later, it's stored as .returncode
in the Popen
object.
I was looking for a simple package that would do this very same task and did not find anything so I created https://github.com/gregnb/react-to-print
You can use it like so:
<ReactToPrint
trigger={() => <a href="#">Print this out!</a>}
content={() => this.componentRef}
/>
<ComponentToPrint ref={el => (this.componentRef = el)} />
The following worked for me:
Registry Editor
(press windows key, type regedit
and hit Enter
) .HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun
and clear the values.HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun
.With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write
$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi
or, using the more efficient tr
$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd
I typically have a secrets.py
that is stored separately from my other python scripts and is not under version control. Then whenever required, you can do from secrets import <required_pwd_var>
. This way you can rely on the operating systems in-built file security system without re-inventing your own.
Using Base64
encoding/decoding is also another way to obfuscate the password though not completely secure
More here - Hiding a password in a python script (insecure obfuscation only)
In Ubuntu or any other platform (yes, Windows too!); starting git1.8.4, which was released 2013-08-23, you won't have to do anything:
Many tutorials teach users to set "color.ui" to "auto" as the first thing after you set "
user.name/email
" to introduce yourselves to Git. Now the variable defaults to "auto
".
So you will see colors by default.
You need to set the width of the container (auto
won't work):
#container {
width: 640px; /* Can be in percentage also. */
height: auto;
margin: 0 auto;
padding: 10px;
position: relative;
}
The CSS reference by MDN explains it all.
Check out these links:
auto
value in a CSS property - Stack OverflowIn action at jsFiddle.
(see detailed explanation here)
$text = Get-Content $filePath | Out-String
The IO.File.ReadAllText
didn't work for me with a relative path, it looks for the file in %USERPROFILE%\$filePath
instead of the current directory (when running from Powershell ISE at least):
$text = [IO.File]::ReadAllText($filePath)
$text = Get-Content $filePath -Raw
I've posted here some methods to convert interval to nanoseconds and nanoseconds to interval. These methods have a nanosecond precision.
You just need to adjust it to get milliseconds instead of nanoseconds.
A shorter method to convert interval to nanoseconds.
SELECT (EXTRACT(DAY FROM (
INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval --Maximum value: INTERVAL '+694444 10:39:59.999999999' DAY(6) TO SECOND(9) or up to 3871 year
) * 24 * 60) * 60 + EXTRACT(SECOND FROM (
INTERVAL '+18500 09:33:47.263027' DAY(5) TO SECOND --Replace line with desired interval
))) * 100 AS MILLIS FROM DUAL;
MILLIS
1598434427263.027
this works for me
<select class="form-control" id="foo">
<option value="first" data-id="1">first</option>
<option value="second" data-id="2">second</option>
</select>
and the script
$('#foo').on("change",function(){
var dataid = $("#foo option:selected").attr('data-id');
alert(dataid)
});
This is a select statement, so each branch of the case must return something. If you want to perform actions, just use an if.
string result = myList.FirstOrDefault(x => x == myString)
if(result != null)
{
//found
}
Using nginx/1.14.0
i have a websocket-server running on port 8097 and users connect from to wss on port 8098, nginx just decrypts the content and forwards it to the websocket server
So i have this config file (in my case /etc/nginx/conf.d/default.conf
)
server {
listen 8098;
ssl on;
ssl_certificate /etc/ssl/certs/domain.crt;
ssl_certificate_key /root/domain.key;
location / {
proxy_pass http://hostname:8097;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400;
}
}
$("input[type='number']").bind("focus", function() {
var value = $(this).val();
$(this).bind("blur", function() {
if(value != $(this).val()) {
alert("Value changed");
}
$(this).unbind("blur");
});
});
OR
$("input[type='number']").bind("input", function() {
alert("Value changed");
});
Here is an interesting solution: it uses the browsers CSS engine to to add a dummy property to elements matching the selector and then evaluates the computed style to find matched elements:
It does dynamically create a style rule [...] It then scans the whole document (using the much decried and IE-specific but very fast document.all) and gets the computed style for each of the elements. We then look for the foo property on the resulting object and check whether it evaluates as “bar”. For each element that matches, we add to an array.
you can try like this...you can use Array.IndexOf() , if you want to know the position also
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));
Just make sure that your Dates are compatible or can be run properly in your database manager(e.g. SQL Server Management Studio). For example, the DateTime.Now C# function is invalid in SQL server meaning your query has to include valid functions like GETDATE() for SQL Server.
This change has worked perfectly for me.
May be your HTML file doesn't support UTF-8 encoding, because the same code is working for me.
Or u can also these line of code:
NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"Notes For Apple" ofType:@"htm" inDirectory:nil];
NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
[WebView loadHTMLString:htmlString baseURL:nil];
If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.
<form name="myForm">
<input type="radio" id="genderm" name="gender" value="male" />
<label for="genderm">Male</label>
<input type="radio" id="genderf" name="gender" value="female" />
<label for="genderf">Female</label>
</form>
<script>
var selected = document.forms.myForm.gender.value;
</script>
for(var i = 0; i < BoardMessages.length;i++){
(function(j){
console.log("Loading message %d".green, j);
htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);
})(i);
}
That should work; however, you should never create a function in a loop. Therefore,
for(var i = 0; i < BoardMessages.length;i++){
composeMessage(BoardMessages[i]);
}
function composeMessage(message){
console.log("Loading message %d".green, message);
htmlMessageboardString += MessageToHTMLString(message);
}
You can also copy the link address and paste it in a new window to get around the security. This works in chrome and firefox but you may have to add slashes in firefox.
You are using getData() method as void.
You can not return values from void.
Not sure if it is what you want, but just simple example:
var input = document.getElementById('input');
input.addEventListener("change", function() {
var file = this.files[0];
var img = new Image();
img.onload = function() {
var sizes = {
width:this.width,
height: this.height
};
URL.revokeObjectURL(this.src);
console.log('onload: sizes', sizes);
console.log('onload: this', this);
}
var objectURL = URL.createObjectURL(file);
console.log('change: file', file);
console.log('change: objectURL', objectURL);
img.src = objectURL;
});
Just like any other language; convert your time periods to a unix timestamp (ie, seconds since the Unix epoch) and then simply subtract. Then, the resulting seconds should be used as a new unix timestamp and read formatted in whatever format you want.
Ah, give the above poster (genesiss) his due credit, code's always handy ;) Though, you now have an explanation as well :)
You can try ezxml -- it's a lightweight parser written entirely in C.
For C++ you can check out TinyXML++
Hadley Wickham
dplyr
packages is always a saver in case of data wrangling.
To add the desired division as a third variable I would use mutate()
d <- mutate(d, new = min / count2.freq)
All title
nodes with zipcode
or book
node as parent:
Version 1:
//title[parent::zipcode|parent::book]
Version 2:
//bookstore/book/title|//bookstore/city/zipcode/title
Version 3: (results are sorted based on source data rather than the order of book then zipcode)
//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]
or - used within true/false - a Boolean operator in xpath
| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.
function is_decimal_value( $a ) {
$d=0; $i=0;
$b= str_split(trim($a.""));
foreach ( $b as $c ) {
if ( $i==0 && strpos($c,"-") ) continue;
$i++;
if ( is_numeric($c) ) continue;
if ( stripos($c,".") === 0 ) {
$d++;
if ( $d > 1 ) return FALSE;
else continue;
} else
return FALSE;
}
return TRUE;
}
Known Issues with the above function:
1) Does not support "scientific notation" (1.23E-123), fiscal (leading $ or other) or "Trailing f" (C++ style floats) or "trailing currency" (USD, GBP etc)
2) False positive on string filenames that match a decimal: Please note that for example "10.0" as a filename cannot be distinguished from the decimal, so if you are attempting to detect a type from a string alone, and a filename matches a decimal name and has no path included, it will be impossible to discern.
On Debian i found out to run on port 80 you need to issue the command as root i.e
sudo node app.js
I hope it helps
I just want to mention a thing, there are many tools can do text processing, e.g. sort, cut, split, join, paste, comm, uniq, column, rev, tac, tr, nl, pr, head, tail.....
they are very handy but you have to learn their options etc.
A lazy way (not the best way) to learn text processing might be: only learn grep , sed and awk. with this three tools, you can solve almost 99% of text processing problems and don't need to memorize above different cmds and options. :)
AND, if you 've learned and used the three, you knew the difference. Actually, the difference here means which tool is good at solving what kind of problem.
a more lazy way might be learning a script language (python, perl or ruby) and do every text processing with it.
Presently I am working on web services where my function is defined and it was throwing an error undefined function.I just added this in autoload.php in codeigniter
$autoload['helper'] = array('common','security','url');
common is the name of my controller.
An example (axios_example.js) using Axios in Node.js:
const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get('/search', function(req, res) {
let query = req.query.queryStr;
let url = `https://your.service.org?query=${query}`;
axios({
method:'get',
url,
auth: {
username: 'the_username',
password: 'the_password'
}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});
var server = app.listen(port);
Be sure in your project directory you do:
npm init
npm install express
npm install axios
node axios_example.js
You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx
Similarly you can do post, such as:
axios({
method: 'post',
url: 'https://your.service.org/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
Similarly you can use SuperAgent.
superagent.get('https://your.service.org?query=xxxx')
.end((err, response) => {
if (err) { return console.log(err); }
res.send(JSON.stringify(response.body));
});
And if you want to do basic authentication:
superagent.get('https://your.service.org?query=xxxx')
.auth('the_username', 'the_password')
.end((err, response) => {
if (err) { return console.log(err); }
res.send(JSON.stringify(response.body));
});
Use the Stringify.Library nuget package
//Default delimiter is ,
var split = new StringConverter().ConvertTo<List<string>>(names);
//You can also have your custom delimiter for e.g. ;
var split = new StringConverter().ConvertTo<List<string>>(names, new ConverterOptions { Delimiter = ';' });
First thing I should have noticed is that charAt
is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt
method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.
If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.
Internally in SQL Server dates are stored as 2 integers. The first integer is the number of dates before or after the base date (1900/01/01). The second integer stores the number of clock ticks after midnight, each tick is 1/300 of a second.
Because of this, I often find the simplest way to compare dates is to simply substract them. This handles 90% of my use cases. E.g.,
select date1, date2, date2 - date1 as DifferenceInDays
from MyTable
...
When I need an answer in units other than days, I will use DateDiff.
In the official getting started example (https://docs.docker.com/compose/gettingstarted/) with the following docker-compose.yml
:
version: '3'
services:
web:
build: .
ports:
- "5000:5000"
redis:
image: "redis:alpine"
After you start this with docker-compose up
, you can easily shell into either your redis
container or your web
container with:
docker-compose exec redis sh
docker-compose exec web sh
The problem is that when redirecting a file into 'mail' like that, it's used for the message body only. Any headers you embed in the file will go into the body instead.
Try:
mail --append="Content-type: text/html" -s "Built notification" [email protected] < /var/www/report.csv
--append lets you add arbitrary headers to the mail, which is where you should specify the content-type and content-disposition. There's no need to embed the To
and Subject
headers in your file, or specify them with --append, since you're implicitly setting them on the command line already (-s is the subject, and [email protected] automatically becomes the To
).
My favorite example is "int Num = 5" here your variable is 1. defined as int 2. declared as Num and 3. instantiated with a value of five. We
A class or struct allows you to change how objects will be defined when it is later used. For example
When we learn programming these two terms are often confused because we often do both at the same time.
I have been using readlink -f works on linux
so
FULL_PATH=$(readlink -f filename)
DIR=$(dirname $FULL_PATH)
PWD=$(pwd)
cd $DIR
#<do more work>
cd $PWD
If you are using anaconda distribution, you can do the following to use python 3.5 on the new environnement "tensorflow":
conda create --name tensorflow python=3.5
activate tensorflow
conda install jupyter
conda install scipy
pip install tensorflow
# or
# pip install tensorflow-gpu
It is important to add python=3.5 at the end of the first line, because it will install Python 3.5.
Source: https://github.com/tensorflow/tensorflow/issues/6999#issuecomment-278459224
Judging from the error message the value of i was the empty string when you executed it, not 0.
Dummy data (you should supply this for us)
visual1 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
visual2 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
combine:
visuals = rbind(visual1,visual2)
visuals$vis=c(rep("visual1",100),rep("visual2",100)) # 100 points of each flavour
Now do:
ggplot(visuals, aes(ISSUE_DATE,COUNTED,group=vis,col=vis)) +
geom_point() + geom_smooth()
and adjust colours etc to taste.
Javascript dynamically adding table data.
SCRIPT
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var colCount = table.rows[0].cells.length;
var validate_Noof_columns = (colCount - 1); // •No Of Columns to be Validated on Text.
for(var j = 0; j < colCount; j++) {
var text = window.document.getElementById('input'+j).value;
if (j == validate_Noof_columns) {
row = table.insertRow(2); // •location of new row.
for(var i = 0; i < colCount; i++) {
var text = window.document.getElementById('input'+i).value;
var newcell = row.insertCell(i);
if(i == (colCount - 1)) { // Replace last column with delete button
newcell.innerHTML = "<INPUT type='button' value='X' onclick='removeRow(this)'/>"; break;
} else {
newcell.innerHTML = text;
window.document.getElementById('input'+i).value = '';
}
}
}else if (text != 'undefined' && text.trim() == ''){
alert('input'+j+' is EMPTY');break;
}
}
}
function removeRow(onclickTAG) {
// Iterate till we find TR tag.
while ( (onclickTAG = onclickTAG.parentElement) && onclickTAG.tagName != 'TR' );
onclickTAG.parentElement.removeChild(onclickTAG);
}
HTMl
<div align='center'>
<TABLE id='dataTable' border='1' >
<TBODY>
<TR><th align='center'><b>First Name:</b></th>
<th align='center' colspan='2'><b>Last Name:</b></th>
<th></th>
</TR>
<TR><TD ><INPUT id='input0' type="text"/></TD>
<TD ><INPUT id='input1' type='text'/></TD>
<TD>
<INPUT type='button' id='input2' value='+' onclick="addRow('dataTable')" />
</TD>
</TR>
</TBODY>
</TABLE>
</div>
Example : jsfiddle
I watched one of the presentations of Brian Goetz (Java Language Architect & specification lead for Lambda Expressions). He explains in detail the following 4 points to consider before going for parallelization:
Splitting / decomposition costs
– Sometimes splitting is more expensive than just doing the work!
Task dispatch / management costs
– Can do a lot of work in the time it takes to hand work to another thread.
Result combination costs
– Sometimes combination involves copying lots of data. For example, adding numbers is cheap whereas merging sets is expensive.
Locality
– The elephant in the room. This is an important point which everyone may miss. You should consider cache misses, if a CPU waits for data because of cache misses then you wouldn't gain anything by parallelization. That's why array-based sources parallelize the best as the next indices (near the current index) are cached and there are fewer chances that CPU would experience a cache miss.
He also mentions a relatively simple formula to determine a chance of parallel speedup.
NQ Model:
N x Q > 10000
where,
N = number of data items
Q = amount of work per item
To add okhttp as a dependency do as follows
now you have okhttp as a dependency
Now design a interface as below so we can have the callback to our activity once the network response received.
public interface NetworkCallback {
public void getResponse(String res);
}
I create a class named NetworkTask so i can use this class to handle all the network requests
public class NetworkTask extends AsyncTask<String , String, String>{
public NetworkCallback instance;
public String url ;
public String json;
public int task ;
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public NetworkTask(){
}
public NetworkTask(NetworkCallback ins, String url, String json, int task){
this.instance = ins;
this.url = url;
this.json = json;
this.task = task;
}
public String doGetRequest() throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String doPostRequest() throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
@Override
protected String doInBackground(String[] params) {
try {
String response = "";
switch(task){
case 1 :
response = doGetRequest();
break;
case 2:
response = doPostRequest();
break;
}
return response;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
instance.getResponse(s);
}
}
now let me show how to get the callback to an activity
public class MainActivity extends AppCompatActivity implements NetworkCallback{
String postUrl = "http://your-post-url-goes-here";
String getUrl = "http://your-get-url-goes-here";
Button doGetRq;
Button doPostRq;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
doGetRq = findViewById(R.id.button2);
doPostRq = findViewById(R.id.button1);
doPostRq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.sendPostRq();
}
});
doGetRq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.sendGetRq();
}
});
}
public void sendPostRq(){
JSONObject jo = new JSONObject();
try {
jo.put("email", "yourmail");
jo.put("password","password");
} catch (JSONException e) {
e.printStackTrace();
}
// 2 because post rq is for the case 2
NetworkTask t = new NetworkTask(this, postUrl, jo.toString(), 2);
t.execute(postUrl);
}
public void sendGetRq(){
// 1 because get rq is for the case 1
NetworkTask t = new NetworkTask(this, getUrl, jo.toString(), 1);
t.execute(getUrl);
}
@Override
public void getResponse(String res) {
// here is the response from NetworkTask class
System.out.println(res)
}
}
The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml
:
#!/usr/bin/env python
import yaml
with open("example.yaml", 'r') as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
And that's it. A plain yaml.load()
function also exists, but yaml.safe_load()
should always be preferred unless you explicitly need the arbitrary object serialization/deserialization provided in order to avoid introducing the possibility for arbitrary code execution.
Note the PyYaml project supports versions up through the YAML 1.1 specification. If YAML 1.2 specification support is needed, see ruamel.yaml as noted in this answer.
Two steps for a complete local development:
{ "name": "baz", "dependencies": { "bar": "file:../foo/bar" } }
cd ~/projects/node-redis # go into the package directory npm link # creates global link cd ~/projects/node-bloggy # go into some other package directory. npm link redis # link-install the package
Just change convert datetime to time that should do the trick:
SELECT timeEvent
FROM tbEvents
WHERE convert(time, startHour) >= convert(time, @startHour)
Search for [ ]{2,}
. This will find two or more adjacent spaces anywhere within the line. It will also match leading and trailing spaces as well as lines that consist entirely of spaces. If you don't want that, check out Alexander's answer.
Actually, you can leave out the brackets, they are just for clarity (otherwise the space character that is being repeated isn't that well visible :)).
The problem with \s{2,}
is that it will also match newlines on Windows files (where newlines are denoted by CRLF
or \r\n
which is matched by \s{2}
.
If you also want to find multiple tabs and spaces, use [ \t]{2,}
.
insert into EXCEPTION_CODES (CODE, MESSAGE)
select CODE, MESSAGE from Exception_code_tmp
What's happening here is the following: You create a new file on your trunk, then you merge it into your branch. In the merge commit this file will be created in your branch also.
When you merge your branch back into the trunk, SVN tries to do the same again: It sees that a file was created in your branch, and tries to create it in your trunk in the merge commit, but it already exists! This creates a tree conflict.
The way to avoid this, is to do a special merge, a reintegration. You can achieve this with the --reintegrate
switch.
You can read about this in the documentation: http://svnbook.red-bean.com/en/1.7/svn.branchmerge.basicmerging.html#svn.branchemerge.basicmerging.reintegrate
When merging your branch back to the trunk, however, the underlying mathematics are quite different. Your feature branch is now a mishmash of both duplicated trunk changes and private branch changes, so there's no simple contiguous range of revisions to copy over. By specifying the --reintegrate option, you're asking Subversion to carefully replicate only those changes unique to your branch. (And in fact, it does this by comparing the latest trunk tree with the latest branch tree: the resulting difference is exactly your branch changes!)
After reintegrating a branch it is highly advisable to remove it, otherwise you will keep getting treeconflicts whenever you merge in the other direction: from the trunk to your branch. (For exactly the same reason as described before.)
There is a way around this too, but I never tried it. You can read it in this post: Subversion branch reintegration in v1.6
A pure css solution : http://bavotasan.com/2011/style-select-box-using-only-css/
.styled-select select {_x000D_
background: transparent;_x000D_
width: 268px;_x000D_
padding: 5px;_x000D_
font-size: 16px;_x000D_
line-height: 1;_x000D_
border: 0;_x000D_
border-radius: 0;_x000D_
height: 34px;_x000D_
-webkit-appearance: none;_x000D_
}_x000D_
_x000D_
.styled-select {_x000D_
width: 240px;_x000D_
height: 34px;_x000D_
overflow: hidden;_x000D_
background: url(http://cdn.bavotasan.com/wp-content/uploads/2011/05/down_arrow_select.jpg) no-repeat right #ddd;_x000D_
border: 1px solid #ccc;_x000D_
}
_x000D_
<div class="styled-select">_x000D_
<select>_x000D_
<option>Here is the first option</option>_x000D_
<option>The second option</option>_x000D_
</select>_x000D_
</div>
_x000D_
fmt.Sprintf
, strconv.Itoa
and strconv.FormatInt
will do the job. But Sprintf
will use the package reflect
, and it will allocate one more object, so it's not an efficient choice.
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
hasOwnProperty() is a nice property to validate object keys. Example:
var obj = {a:1, b:2};
obj.hasOwnProperty('a') // true
I dont think you need regex to achieve this. I would look at the SubString method along with the indexOf method. If you need more help, add a comment showing what you have attempted and I will offer more help.
Unfortunately, no. In 2013, there is no way to do it with pure CSS.
Update: thanks to showdev for linking to the obsolete spec of CSS3 Hyperlinks, and yes, no browser has implemented it. So the answer still stands valid.
A DIV is by default a BLOCK display element, meaning it sits on its own line. If you add the CSS property display:inline it will behave the way you want. But perhaps you should be considering a SPAN instead?
I use a slight evolution of @hugo_leonardo 's solution:
<?php
return (object) array(
'host' => 'localhost',
'username' => 'root',
'pass' => 'password',
'database' => 'db'
);
?>
This allows you to use the object syntax when you include the php : $configs->host
instead of $configs['host']
.
Also, if your app has configs you need on the client side (like for an Angular app), you can have this config.php
file contain all your configs (centralized in one file instead of one for JavaScript and one for PHP). The trick would then be to have another PHP file that would echo
only the client side info (to avoid showing info you don't want to show like database connection string). Call it say get_app_info.php
:
<?php
$configs = include('config.php');
echo json_encode($configs->app_info);
?>
The above assuming your config.php
contains an app_info
parameter:
<?php
return (object) array(
'host' => 'localhost',
'username' => 'root',
'pass' => 'password',
'database' => 'db',
'app_info' => array(
'appName'=>"App Name",
'appURL'=> "http://yourURL/#/"
)
);
?>
So your database's info stays on the server side, but your app info is accessible from your JavaScript, with for example a $http.get('get_app_info.php').then(...);
type of call.
Use the ComboStyle property:
comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
$('elements-to-match').click(function(){
alert("The id is "+ this.id );
});
no need to wrap it in a jquery object
You can try using something like this. In this case I used one stored procedure to get more data tables and export all of them using CSV.
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace bo
{
class Program
{
static private void CreateCSVFile(DataTable dt, string strFilePath)
{
#region Export Grid to CSV
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
int iColCount = dt.Columns.Count;
// First we will write the headers.
//DataTable dt = m_dsProducts.Tables[0];
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(";");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount -1 )
{
sw.Write(";");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
#endregion
}
static void Main(string[] args)
{
string strConn = "connection string to sql";
string direktorij = @"d:";
SqlConnection conn = new SqlConnection(strConn);
SqlCommand command = new SqlCommand("sp_ado_pos_data", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add('@skl_id', SqlDbType.Int).Value = 158;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);
for (int i = 0; i < ds.Tables.Count; i++)
{
string datoteka = (string.Format(@"{0}tablea{1}.csv", direktorij, i));
DataTable tabela = ds.Tables[i];
CreateCSVFile(tabela,datoteka );
Console.WriteLine("Generišem tabelu {0}", datoteka);
}
Console.ReadKey();
}
}
}
I want to add that when using Npgsql (data provider for PostgreSQL), arrays and lists of primitive types are actually supported:
Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.
Android code - Main.java
package test12.tt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Test12Activity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TextView txt1 = (TextView) findViewById(R.id.sm);
new Thread(new Runnable() {
public void run(){
txt1.setText("Thread!!");
}
}).start();
}
}
Android application xml - main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id = "@+id/sm"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"/>
</LinearLayout>
Try this coding:
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(new LatLng(location.getLatitude(), location.getLongitude())) // Sets the center of the map to location user
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(40) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
I think that for simple HTTP requests like this it's better to use the request
module. You need to install it with npm (npm install request
) and then your code can look like this:
const request = require('request')
,url = 'http://graph.facebook.com/517267866/?fields=picture'
request(url, (error, response, body)=> {
if (!error && response.statusCode === 200) {
const fbResponse = JSON.parse(body)
console.log("Got a response: ", fbResponse.picture)
} else {
console.log("Got an error: ", error, ", status code: ", response.statusCode)
}
})
You are passing the address of the first element of the array
You can also use the matrix
command, to create a matrix with n lines and m columns, filled with zeros.
matrix(0, n, m)
You could also use the exclude option in tsconfig.json file like so:
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"declaration": false,
"noImplicitAny": false,
"removeComments": true,
"noLib": false,
"emitDecoratorMetadata": true,
"experimentalDecorators": true
},
"exclude": [
"node_modules"
]
}
I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS
div {
opacity:0;
transition:opacity 1s linear;*
}
div.SomeClass {
opacity:1;
}
For tomcat you can increase the permGem space by using
-XX:MaxPermSize=128m
For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it
export JAVA_OPTS="-XX:MaxPermSize=128m"
Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat
Run ---> Debug Configuration ---> YourConfiguration ---> Arguments tab
Another possibility is Boost.Format:
#include <boost/format.hpp>
#include <iostream>
#include <string>
int main() {
int i = 4;
std::string text = "Player";
std::cout << boost::format("%1% %2%\n") % text % i;
}
See What is the maximum length of a URL in different browsers?
The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.
You can either use the readonly
or the disabled
attribute. Note that when disabled, the input's value will not be submitted when submitting the form.
<input id="price_to" value="price to" readonly="readonly">
<input id="price_to" value="price to" disabled="disabled">
You want a proc object:
gaussian = Proc.new do |dist, *args|
sigma = args.first || 10.0
...
end
def weightedknn(data, vec1, k = 5, weightf = gaussian)
...
weight = weightf.call(dist)
...
end
Just note that you can't set a default argument in a block declaration like that. So you need to use a splat and setup the default in the proc code itself.
Or, depending on your scope of all this, it may be easier to pass in a method name instead.
def weightedknn(data, vec1, k = 5, weightf = :gaussian)
...
weight = self.send(weightf)
...
end
In this case you are just calling a method that is defined on an object rather than passing in a complete chunk of code. Depending on how you structure this you may need replace self.send
with object_that_has_the_these_math_methods.send
Last but not least, you can hang a block off the method.
def weightedknn(data, vec1, k = 5)
...
weight =
if block_given?
yield(dist)
else
gaussian.call(dist)
end
end
...
end
weightedknn(foo, bar) do |dist|
# square the dist
dist * dist
end
But it sounds like you would like more reusable chunks of code here.
Say the remote is origin
and the branch is master
, and say you already have master
checked out, might try the following:
git fetch origin
git reset --hard origin/master
This basically just takes the current branch and points it to the HEAD
of the remote branch.
WARNING: As stated in the comments, this will throw away your local changes and overwrite with whatever is on the origin.
Or you can use the plumbing commands to do essentially the same:
git fetch <remote>
git update-ref refs/heads/<branch> $(git rev-parse <remote>/<branch>)
git reset --hard
EDIT: I'd like to briefly explain why this works.
The .git
folder can hold the commits for any number of repositories. Since the commit hash is actually a verification method for the contents of the commit, and not just a randomly generated value, it is used to match commit sets between repositories.
A branch is just a named pointer to a given hash. Here's an example set:
$ find .git/refs -type f
.git/refs/tags/v3.8
.git/refs/heads/master
.git/refs/remotes/origin/HEAD
.git/refs/remotes/origin/master
Each of these files contains a hash pointing to a commit:
$ cat .git/refs/remotes/origin/master
d895cb1af15c04c522a25c79cc429076987c089b
These are all for the internal git storage mechanism, and work independently of the working directory. By doing the following:
git reset --hard origin/master
git will point the current branch at the same hash value that origin/master points to. Then it forcefully changes the working directory to match the file structure/contents at that hash.
To see this at work go ahead and try out the following:
git checkout -b test-branch
# see current commit and diff by the following
git show HEAD
# now point to another location
git reset --hard <remote>/<branch>
# see the changes again
git show HEAD
From the python documentation for fileinput.input():
This iterates over the lines of all files listed in
sys.argv[1:]
, defaulting tosys.stdin
if the list is empty
further, the definition of the function is:
fileinput.FileInput([files[, inplace[, backup[, mode[, openhook]]]]])
reading between the lines, this tells me that files
can be a list so you could have something like:
for each_line in fileinput.input([input_file, input_file]):
do_something(each_line)
See here for more information
Incase you don't want to use nextint, you can also use buffered reader, where using inputstream
and readline
function read the string.
For python version 3.7.3 in vscode with gitbash as the default terminal I was dealing with this for a while and then followed @Vitaliy Terziev advice of adding the alias to .bashrc but with the following specification:
alias python=’“/c/Users/my user name/AppData/Local/Programs/Python/Python37/python.exe”’
Notice the combination of single and double quotes because of “my user name” spaces.
For me, "winpty" couldn't resolve python path in vscode.
It prevents disclosure of the response through JSON hijacking.
In theory, the content of HTTP responses are protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).
An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...>
or <img>
tag, but it can't get any information about the result (headers, contents).
Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.
Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.
Note that this happens at the time the JSON is executed as JavaScript, not at the time it's parsed.
There are multiple countermeasures:
By placing a while(1);
statement before the JSON data, Google makes sure that the JSON data is never executed as JavaScript.
Only a legitimate page could actually get the whole content, strip the while(1);
, and parse the remainder as JSON.
Things like for(;;);
have been seen at Facebook for instance, with the same results.
Similarly, adding invalid tokens before the JSON, like &&&START&&&
, makes sure that it is never executed.
This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.
Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.
A valid JSON object, when not enclosed by anything, is not valid in JavaScript:
eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
This is however valid JSON:
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}
So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid JavaScript, while still being valid JSON.
As noted by @hvd in the comments, the empty object {}
is valid JavaScript, and knowing the object is empty may itself be valuable information.
The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by @oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).
Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.
Both methods require server side changes in order to avoid developers accidentally sending vulnerable JSON.
Maybe it's not using TCP/IP
Have a look at the SQL Server Configuration Manager to see what protocols it's using.
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
Basically http.antMatcher()
tells Spring to only configure HttpSecurity
if the path matches this pattern.
I faced the same problem when import C++ Dll in .Net Framework +4, I unchecked Project->Properties->Build->Prefer 32-bit and it solved for me.
if you are looking for a deleted directory.
git checkout ./pathToDir/*
You have to add THEN
IF EXISTS(SELECT * FROM component_psar WHERE tbl_id = '2' AND row_nr = '1')
THEN
UPDATE component_psar SET col_1 = '1', col_2 = '1', col_3 = '1', col_4 = '1', col_5 = '1', col_6 = '1', unit = '1', add_info = '1', fsar_lock = '1' WHERE tbl_id = '2' AND row_nr = '1'
ELSE
INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')
Try this.
ALTER PROCEDURE [dbo].[sp_ClientNotes_update]
@id uniqueidentifier,
@ordering smallint = NULL,
@title nvarchar(20) = NULL,
@content text = NULL
AS
BEGIN
SET NOCOUNT ON;
UPDATE tbl_ClientNotes
SET ordering=ISNULL(@ordering,ordering),
title=ISNULL(@title,title),
content=ISNULL(@content, content)
WHERE id=@id
END
It might also be worth adding an extra part to the WHERE
clause, if you use transactional replication then it will send another update to the subscriber if all are NULL, to prevent this.
WHERE id=@id AND (@ordering IS NOT NULL OR
@title IS NOT NULL OR
@content IS NOT NULL)
If you can use pandas
, then value_counts
is there for rescue.
>>> import pandas as pd
>>> a = [1, 2, 3, 4, 1, 4, 1]
>>> pd.Series(a).value_counts()
1 3
4 2
3 1
2 1
dtype: int64
It automatically sorts the result based on frequency as well.
If you want the result to be in a list of list, do as below
>>> pd.Series(a).value_counts().reset_index().values.tolist()
[[1, 3], [4, 2], [3, 1], [2, 1]]
Improving From @lnafziger answer
Save your Barbuttons in a strong outlet and do this to hide/show it:
-(void) hideBarButtonItem :(UIBarButtonItem *)myButton {
// Get the reference to the current toolbar buttons
NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];
// This is how you remove the button from the toolbar and animate it
[navBarBtns removeObject:myButton];
[self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
}
-(void) showBarButtonItem :(UIBarButtonItem *)myButton {
// Get the reference to the current toolbar buttons
NSMutableArray *navBarBtns = [self.navigationItem.rightBarButtonItems mutableCopy];
// This is how you add the button to the toolbar and animate it
if (![navBarBtns containsObject:myButton]) {
[navBarBtns addObject:myButton];
[self.navigationItem setRightBarButtonItems:navBarBtns animated:YES];
}
}
When ever required use below Function..
[self showBarButtonItem:self.rightBarBtn1];
[self hideBarButtonItem:self.rightBarBtn1];
Isn't neither localStorage or httpOnly cookie acceptable? In regards to a compromised 3rd party library, the only solution I know of that will reduce / prevent sensitive information from being stolen would be enforced Subresource Integrity.
Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.
As long as the compromised 3rd party library is active on your website, a keylogger can start collecting info like username, password, and whatever else you input into the site.
An httpOnly cookie will prevent access from another computer but will do nothing to prevent the hacker from manipulating the user's computer.
CSS:
form div {
padding: x; /*default div padding in the form e.g. 5px 0 5px 0*/
margin: y; /*default div padding in the form e.g. 5px 0 5px 0*/
}
.divForText { /*For Text line only*/
padding: a;
margin: b;
}
.divForLabelInput{ /*For Text and Input line */
padding: c;
margin: d;
}
.divForInput{ /*For Input line only*/
padding: e;
margin: f;
}
HTML:
<div class="divForText">some text</div>
<input ..... />
<div class="divForLabelInput">some label <input ... /></div>
<div class="divForInput"><input ... /></div>
Just for fun (I had some time to kill), a more sophisticated implementation which caches the zero-string:
pad.zeros = new Array(5).join('0');
function pad(num, len) {
var str = String(num),
diff = len - str.length;
if(diff <= 0) return str;
if(diff > pad.zeros.length)
pad.zeros = new Array(diff + 1).join('0');
return pad.zeros.substr(0, diff) + str;
}
If the padding count is large and the function is called often enough, it actually outperforms the other methods...
The Android Device Monitor application available under sdk/tools/monitor has a logcat option to filter 'by Application Name' where you enter the application package name.
Take a look also to the do { ... }
command since gnuplot 4.6 as it is very powerful:
do for [t=0:50] {
outfile = sprintf('animation/bessel%03.0f.png',t)
set output outfile
splot u*sin(v),u*cos(v),bessel(u,t/50.0) w pm3d ls 1
}
I like using (open source and gui friendly) Quantum GIS to convert the shapefile to kml.
Google Maps API supports only a subset of the KML standard. One limitation is file size.
To reduce your file size, you can Quantum GIS's "simplify geometries" function. This "smooths" polygons.
Then you can select your layer and do a "save as kml" on it.
If you need to process a bunch of files, the process can be batched with Quantum GIS's ogr2ogr command from osgeo4w shell.
Finally, I recommend zipping your kml (with your favorite compression program) for reduced file size and saving it as kmz.
Following looks very simple to me:
model.layers[idx].output
Above is a tensor object, so you can modify it using operations that can be applied to a tensor object.
For example, to get the shape model.layers[idx].output.get_shape()
idx
is the index of the layer and you can find it from model.summary()
I like more the "pythonic way"
List<string> lines = new List<string> {
"line1",
"line2",
String.Format("{0} - {1} | {2}",
someVar,
othervar,
thirdVar
)
};
if(foo)
lines.Add("line3");
return String.Join(Environment.NewLine, lines);
Using some of the knowledge from this and a couple of other posts, I found the method that worked the best for me was to:
adb shell 'stty raw; screencap -p'
I have posted a very simple Python script on GitHub that essentially mirrors the screen of a device connected over ADB:
See https://devcenter.heroku.com/articles/git#deploying-code
$ git push heroku yourbranch:master
Simple js solution:
queryStringParse = function(string) {
let parsed = {}
if(string != '') {
string = string.substring(string.indexOf('?')+1)
let p1 = string.split('&')
p1.map(function(value) {
let params = value.split('=')
parsed[params[0]] = params[1]
});
}
return parsed
}
And you can call it from anywhere using:
var params = this.queryStringParse(this.props.location.search);
Hope this helps.
You can easily return JSON
with String
in property response
as following
@RestController
public class TestController {
@RequestMapping(value = "/getString", produces = MediaType.APPLICATION_JSON_VALUE)
public Map getString() {
return Collections.singletonMap("response", "Hello World");
}
}