UPDATE: I modified my code using this fork
also instead of using $.each I changed to $.map as suggested by Tomislav Markovski
$('#manufacturer').typeahead({
source: function(typeahead, query){
$.ajax({
url: window.location.origin+"/bows/get_manufacturers.json",
type: "POST",
data: "",
dataType: "JSON",
async: false,
success: function(results){
var manufacturers = new Array;
$.map(results.data.manufacturers, function(data, item){
var group;
group = {
manufacturer_id: data.Manufacturer.id,
manufacturer: data.Manufacturer.manufacturer
};
manufacturers.push(group);
});
typeahead.process(manufacturers);
}
});
},
property: 'name',
items:11,
onselect: function (obj) {
}
});
However I am encountering some problems by getting
Uncaught TypeError: Cannot call method 'toLowerCase' of undefined
as you can see on a newer post I am trying to figure out here
hope this update is of any help to you...
This is my quick trick:
from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'
For more info Visit: https://humanfriendly.readthedocs.io/en/latest/#humanfriendly.format_timespan
Use this:
from c in dc.Organization
where SqlMethods.Like(c.Hierarchy, "%/12/%")
select *;
You should remove the &
(ampersand) symbol, so that line 4 will look like this:
$conn = ADONewConnection($config['db_type']);
This is because ADONewConnection already returns an object by reference. As per documentation, assigning the result of a reference to object by reference results in an E_DEPRECATED message as of PHP 5.3.0
Using nginx $is_args instead of ? For GET query Strings
location / { try_files $uri $uri/ /index.php$is_args$args; }
As we know there is no native support for private properties with ES6 classes.
Below is just what I use (might be helpful). Basically I'm wrapping a class inside the factory.
function Animal(name) {
const privateData = 'NO experiments on animals have been done!';
class Animal {
constructor(_name) {
this.name = _name;
}
getName() {
return this.name
}
getDisclamer() {
return `${privateData} Including ${this.name}`
}
}
return new Animal(name)
}
I'm a beginner so happy to hear if this is a bad approach.
I tried to do full compatible analog of javascript's encodeURIComponent for c# and after my 4 hour experiments I found this
c# CODE:
string a = "!@#$%^&*()_+ some text here ??? ??????? ????";
a = System.Web.HttpUtility.UrlEncode(a);
a = a.Replace("+", "%20");
the result is: !%40%23%24%25%5e%26*()_%2b%20some%20text%20here%20%d0%b0%d0%bb%d0%b8%20%d0%bc%d0%b0%d0%bc%d0%b5%d0%b4%d0%be%d0%b2%20%d0%b1%d0%b0%d0%ba%d1%83
After you decode It with Javascript's decodeURLComponent();
you will get this: !@#$%^&*()_+ some text here ??? ??????? ????
Thank You for attention
Empty website template creates an ASP.NET website that includes a Web.config file but no other files. Means you have not any default page to show on browse or run.
This error message simply means that you did not setup and configure the default document properly on your IIS.
Once this is configured, the error message will go away.
I just tried with with Eclipse Neon.1 and Gradle:
------------------------------------------------------------
Gradle 3.2.1
------------------------------------------------------------
Build time: 2016-11-22 15:19:54 UTC
Revision: 83b485b914fd4f335ad0e66af9d14aad458d2cc5
Groovy: 2.4.7
Ant: Apache Ant(TM) version 1.9.6 compiled on June 29 2015
JVM: 1.8.0_112 (Oracle Corporation 25.112-b15)
OS: Windows 10 10.0 amd64
On windows 10 with Java Version:
C:\FDriveKambiz\repo\gradle-gen-project>java -version
java version "1.8.0_112"
Java(TM) SE Runtime Environment (build 1.8.0_112-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.112-b15, mixed mode)
And it failed miserably as you can see in Eclipse. But sailed like a soaring eagle in Intellij...I dont know Intellij, and a huge fan of eclipse, but common dudes, this means NO ONE teste Neon.1 for the simplest of use cases...to import a gradle project. That is not good enough. I am switching to Intellij for gradle projects:
I've got a problem when configured Tomcat' server.xml
and added Context element.
He just doesn't want to use my config:
http://www.oreillynet.com/onjava/blog/2006/12/configuration_antipatterns_tom.html
If you're in a Unix-like
system:
mv $CATALINA_HOME/webapps/ROOT $CATALINA_HOME/webapps/___ROOT
ln -s $CATALINA_HOME/webapps/your_project $CATALINA_HOME/webapps/ROOT
Done.
Works for me.
not so elegant but you dont need to declare any variable:
for k in (select max(1) from table where 1 = 1) loop
update x where column = value;
end loop;
if you are using the old way of writting views, in the way of Function-Based-Views...
in your view, you are creating a new variable called usuario
to save the request.user probably...
but if you returning to the Template
a context_instance
, passing the value of the Context of the request, you will get the logged user, just by accessing the request
.
// In your views file
from django.shortcuts import render_to_response
from django.template import RequestContext
def your_view(request):
data = {
'formulario': Formulario()
# ...
}
return render_to_response('your_template.html',
data, context_instance=RequestContext(request))
// In your template
<form id='formulario' method='POST' action=''>
<h2>Publica tu tuit, {{ request.user.username.title }} </h2>
{% csrf_token %}
{{ formulario.as_p }}
<p><input type='submit' value='Confirmar' /></p>
</form>
The published responses are correct but incomplete.
Git to install the packages we first need to make sure git is installed.
$ sudo apt install git-core
Bower uses Node.js and npm to manage the programs so lets install these.
$ sudo apt install nodejs
Node will now be installed with the executable located in /etc/usr/nodejs
.
You should be able to execute Node.js by using the command below, but as ours are location in nodejs we will get an error No such file or directory.
$ /usr/bin/env node
We can manually fix this by creating a symlink.
$ sudo ln -s /usr/bin/nodejs /usr/bin/node
Now check Node.js is installed correctly by using.
$ /usr/bin/env node
>
Some users suggest installing legacy nodejs, this package just creates a symbolic link to binary nodejs.
$ sudo apt install nodejs-legacy
Now, you can install npm and bower
Install npm
$ sudo apt install npm
Install Bower
$ sudo npm install -g bower
Check bower is installed and what version you're running.
$ bower -v
1.8.0
Reference:
EDIT: According to the comments on the original post this is a C# question.
Short answer: yes, using the this
keyword.
Long answer: yes, using the this
keyword, and here's an example.
class MyClass
{
private object someData;
public MyClass(object data)
{
this.someData = data;
}
public MyClass() : this(new object())
{
// Calls the previous constructor with a new object,
// setting someData to that object
}
}
Off the top of my head, if the element is not a block element - make it so.
and then give it a width.
Notice that this line:
lol = document.getElementById('lolz').value;
is before the actual <input>
element on your markup:
<input type="text" name="enter" class="enter" value="" id="lolz"/>
Your code is parsed line by line, and the lol = ...
line is evaluated before the browser knows about the existance of an input with id lolz
. Thus, document.getElementById('lolz')
will return null
, and document.getElementById('lolz').value
should cause an error.
Move that line inside the function, and it should work. This way, that line will only run when the function is called. And use var
as others suggested, to avoid making it a global variable:
function kk(){
var lol = document.getElementById('lolz').value;
alert(lol);
}
You can also move the script to the end of the page. Moving all script blocks to the end of your HTML <body>
is the standard practice today to avoid this kind of reference problem. It also tends to speed up page load, since scripts that take long to load and parse are processed after the HTML has been (mostly) displayed.
You can use this function (I found it here: http://excelribbon.tips.net/T010780_Colors_in_an_IF_Function.html):
Function GetFillColor(Rng As Range) As Long
GetFillColor = Rng.Interior.ColorIndex
End Function
Here is an explanation, how to create user-defined functions: http://www.wikihow.com/Create-a-User-Defined-Function-in-Microsoft-Excel
In your worksheet, you can use the following: =GetFillColor(B5)
In my case I wanted to switch from http to https, so I had deleted http from IIS. In my .csproj.user file found that I still had:
<IISUrl>http://localhost/</IISUrl>
So I changed it to:
<IISUrl>https://localhost/</IISUrl>
You need to declare your clients variable as public, e.g.
public string clients;
but you should probably do it as a Property, e.g.
private string clients;
public string Clients{ get{ return clients; } set {clients = value;} }
And then you can call it in your .aspx page like this:
<%=Clients%>
Variables in C# are private by default. Read more on access modifiers in C# on MSDN and properties in C# on MSDN
Python's standard library has json
and urllib2
modules.
import json
import urllib2
data = json.load(urllib2.urlopen('http://someurl/path/to/json'))
As it was already mentioned: READONLY
does not work for <input type='checkbox'>
and <select>...</select>
.
If you have a Form
with disabled checkboxes / selects AND need them to be submitted, you can use jQuery:
$('form').submit(function(e) {
$(':disabled').each(function(e) {
$(this).removeAttr('disabled');
})
});
This code removes the disabled
attribute from all elements on submit.
You can use a shortcur, like this one:
noremap <F6> :%y+<CR>
It means, when you push F6 in normald mode, it will copy the whole file, and add it to the clipboard.
Or you just can type in normal mode :%y+
and then push Enter
.
The greater sign ( > ) selector in CSS means that the selector on the right is a direct descendant / child of whatever is on the left.
An example:
article > p { }
Means only style a paragraph that comes after an article.
Yet another multi-functional CSV (and not only) manipulation tool: Miller. From its own description, it is like awk, sed, cut, join, and sort for name-indexed data such as CSV, TSV, and tabular JSON. (link to github repository: https://github.com/johnkerl/miller)
I refer few writings.
reference:
This getMemorySize() method is returned MemorySize that has total and free memory size.
I don't believe this code perfectly.
This code is testing on LG G3 cat.6 (v5.0.1)
private MemorySize getMemorySize() {
final Pattern PATTERN = Pattern.compile("([a-zA-Z]+):\\s*(\\d+)");
MemorySize result = new MemorySize();
String line;
try {
RandomAccessFile reader = new RandomAccessFile("/proc/meminfo", "r");
while ((line = reader.readLine()) != null) {
Matcher m = PATTERN.matcher(line);
if (m.find()) {
String name = m.group(1);
String size = m.group(2);
if (name.equalsIgnoreCase("MemTotal")) {
result.total = Long.parseLong(size);
} else if (name.equalsIgnoreCase("MemFree") || name.equalsIgnoreCase("Buffers") ||
name.equalsIgnoreCase("Cached") || name.equalsIgnoreCase("SwapFree")) {
result.free += Long.parseLong(size);
}
}
}
reader.close();
result.total *= 1024;
result.free *= 1024;
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private static class MemorySize {
public long total = 0;
public long free = 0;
}
I know that Pattern.compile() is expensive cost so You may move its code to class member.
I know there is great answers here but I found no reference to handle filename extensions when adding suffix.
I needed to add '_en' suffix to all wav
files in a folder before the file extension.
The magic is here: %.*
for filename in *.wav; do mv $filename ${filename%.*}_en.wav; done;
If you need to handle different file extensions, check this answer. A bit less intuitive.
Unless I am misunderstanding the question, I would almost always use $this->get_species because the subclass (in this case dog) could overwrite that method since it does extend it. If the class dog doesn't redefine the method then both ways are functionally equivalent but if at some point in the future you decide you want the get_species method in dog should print "dog" then you would have to go back through all the code and change it.
When you use $this it is actually part of the object which you created and so will always be the most up-to-date as well (if the property being used has changed somehow in the lifetime of the object) whereas using the parent class is calling the static class method.
If you run mysql --verbose --help | less
it will tell you about line 11 which .cnf
files it will look for.
You can also do mysql --print-defaults
to show you how the configuration values it will use. This can also be useful in identifying just which config file it is loading.
You can simply use back()
function to redirect no need to use redirect()->back()
make sure you are using 5.2 or greater than 5.2 version.
You can replace your code to below code.
return back()->with('message', 'WORKS!');
In the view file replace below code.
@if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
@endif
For more detail, you can read here
back()
is just a helper function. It's doing the same thing as redirect()->back()
If using ES2016 you can use async
and await
and do something like:
(async () => {
const data = await fetch(url)
myFunc(data)
}())
If using ES2015 you can use Generators. If you don't like the syntax you can abstract it away using an async
utility function as explained here.
If using ES5 you'll probably want a library like Bluebird to give you more control.
Finally, if your runtime supports ES2015 already execution order may be preserved with parallelism using Fetch Injection.
I thought all of them were great but I had troubles actually getting them to work with javascript and c#. Here is what I did. Hope it helps someone else.
//put this at the top of the page
<script src="https://www.google.com/recaptcha/api.js"></script>
//put this under the script tag
<script>
var isCaptchaValid = false;
function doCaptchaValidate(source, args) {
args.IsValid = isCaptchaValid;
}
var verifyCallback = function (response) {
isCaptchaValid = true;
};
</script>
//retrieved from google and added callback
<div class="g-recaptcha" data-sitekey="sitekey" data-callback="verifyCallback">
//created a custom validator and added error message and ClientValidationFucntion
<asp:CustomValidator runat="server" ID="CustomValidator1" ValidationGroup="Initial" ErrorMessage="Captcha Required" ClientValidationFunction="doCaptchaValidate"/>
I fixed this programmatically in my software, using C++ Builder.
Before I assign the CHM help file, Application->HelpFile = HelpFileName
, I check to see if it contains the "Zone.Identifier" stream, and when it does, I simply remove it.
String ZIStream(HelpFileName + ":Zone.Identifier") ;
if (FileExists(ZIStream))
{ DeleteFile(ZIStream) ; }
Try this:
str.replace("\"", "\\\""); // (Escape backslashes and embedded double-quotes)
Or, use single-quotes to quote your search and replace strings:
str.replace('"', '\\"'); // (Still need to escape the backslash)
As pointed out by helmus, if the first parameter passed to .replace()
is a string it will only replace the first occurrence. To replace globally, you have to pass a regex with the g
(global) flag:
str.replace(/"/g, "\\\"");
// or
str.replace(/"/g, '\\"');
But why are you even doing this in JavaScript? It's OK to use these escape characters if you have a string literal like:
var str = "Dude, he totally said that \"You Rock!\"";
But this is necessary only in a string literal. That is, if your JavaScript variable is set to a value that a user typed in a form field you don't need to this escaping.
Regarding your question about storing such a string in an SQL database, again you only need to escape the characters if you're embedding a string literal in your SQL statement - and remember that the escape characters that apply in SQL aren't (usually) the same as for JavaScript. You'd do any SQL-related escaping server-side.
Just intall and enable Coffee-Bytes plugin (Eclipse)
SELECT * FROM Header WHERE userID LIKE '%' + CHAR(39) + '%'
We can do it in two different ways
Remove Windows Service via Registry
Its very easy to remove a service from registry if you know the right path. Here is how I did that:
Run Regedit or Regedt32
Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"
Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).
Delete Windows Service via Command Window
Alternatively, you can also use command prompt and delete a service using following command:
sc delete
You can also create service by using following command
sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"
Note: You may have to reboot the system to get the list updated in service manager.
$('tr').click(function(){
alert( $('tr').index(this) );
});
For first tr
, it alerts 0. If you want to alert 1, you can add 1 to index.
Declare the class containing the event:
class MyClass {
public event EventHandler MyEvent;
public void Method() {
OnEvent();
}
private void OnEvent() {
if (MyEvent != null) {
MyEvent(this, EventArgs.Empty);
}
}
}
Use it like this:
MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();
For N bins, the bin edges are specified by list of N+1 values where the first N give the lower bin edges and the +1 gives the upper edge of the last bin.
Code:
from numpy import np; from pylab import *
bin_size = 0.1; min_edge = 0; max_edge = 2.5
N = (max_edge-min_edge)/bin_size; Nplus1 = N + 1
bin_list = np.linspace(min_edge, max_edge, Nplus1)
Note that linspace produces array from min_edge to max_edge broken into N+1 values or N bins
It goes like ng-bind-html-unsafe="opt.text"
:
<div ng-app ng-controller="MyCtrl">
<ul>
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
{{ opt.text }}
</li>
</ul>
<p>{{opt}}</p>
</div>
Or you can define a function in scope:
$scope.getContent = function(obj){
return obj.value + " " + obj.text;
}
And use it this way:
<li ng-repeat=" opt in opts" ng-bind-html-unsafe="getContent(opt)" >
{{ opt.value }}
</li>
Note that you can not do it with an option
tag: Can I use HTML tags in the options for select elements?
Since you've labeled the question C++, you might be interested in using boost::asio, ACE, or some other cross-platform socket library for C++ or for C. Some other cross-platform libraries may be found in the answers to C++ sockets library for cross-platform and Cross platform Networking API.
Assuming that using a third party cross-platform sockets library is not an option for you...
The header <sys/socket.h> is defined in IEEE Std. 1003.1 (POSIX), but sadly Windows is non-compliant with the POSIX standard. The MinGW compiler is a port of GCC for compiling Windows applications, and therefore does not include these POSIX system headers. If you install GCC using Cygwin, then it will include these system headers to emulate a POSIX environment on Windows. Be aware, however, that if you use Cygwin for sockets that a.) you will need to put the cygwin DLL in a place where your application can read it and b.) Cygwin headers and Windows headers don't interact very well (so if you plan on including windows.h
, then you probably don't want to be including sys/socket.h
).
My personal recommendation would be to download a copy of VirtualBox, download a copy of Ubuntu, install Ubuntu into VirtualBox, and then do your coding and testing on Ubuntu. Alternatively, I am told that Microsoft sells a "UNIX subsystem" and that it is pre-installed on certain higher-end editions of Windows, although I have no idea how compliant this system is (and, if it is compliant, with which edition of the UNIX standard it is compliant). Winsockets are also an option, although they can behave in subtly different ways than their POSIX counterparts, even though the signatures may be similar.
You can always do
('0' + deg).slice(-2)
See slice()
:
You can also use negative numbers to select from the end of an array
Hence
('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2) // '04'
For ease of access, you could of course extract it to a function, or even extend Number
with it:
Number.prototype.pad = function(n) {
return new Array(n).join('0').slice((n || 2) * -1) + this;
}
Which will allow you to write:
c += deg.pad() + '° '; // "04° "
The above function pad
accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:
deg.pad(4) // "0045"
Note the obvious drawback that the value of n
cannot be higher than 11, as the string of 0's is currently just 10 characters long. This could of course be given a technical solution, but I did not want to introduce complexity in such a simple function. (Should you elect to, see alex's answer for an excellent approach to that).
Note also that you would not be able to write 2.pad()
. It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.
I stumbled upon this problem during attempt to dockerise Avahi which needs to be aware of its public IP to function properly. Assigning static IP to the container is tricky due to lack of support for static IP assignment in Docker.
This article describes technique how to assign static IP to the container on Debian:
Docker service should be started with DOCKER_OPTS="--bridge=br0 --ip-masq=false --iptables=false"
. I assume that br0
bridge is already configured.
Container should be started with --cap-add=NET_ADMIN --net=bridge
Inside container pre-up ip addr flush dev eth0
in /etc/network/interfaces
can be used to dismiss IP address assigned by Docker as in following example:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
pre-up ip addr flush dev eth0
address 192.168.0.249
netmask 255.255.255.0
gateway 192.168.0.1
/etc/init.d/networking start
. Also entry script needs to edit or populate /etc/hosts
file in order to remove references to Docker-assigned IP.For showing result of batch file in text file, you can use
this command
chdir > test.txt
This command will redirect result to test.txt.
When you open test.txt you will found current path of directory in test.txt
You can add HTML into an alert string, but it will not render as HTML. It will just be displayed as a plain string. Simple answer: no.
Since the previous answers were written, requests have changed. Have a look at the bug thread at Github for more detail and this comment for an example.
In short, the files parameter takes a dict
with the key being the name of the form field and the value being either a string or a 2, 3 or 4-length tuple, as described in the section POST a Multipart-Encoded File in the requests quickstart:
>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
In the above, the tuple is composed as follows:
(filename, data, content_type, headers)
If the value is just a string, the filename will be the same as the key, as in the following:
>>> files = {'obvius_session_id': '72c2b6f406cdabd578c5fd7598557c52'}
Content-Disposition: form-data; name="obvius_session_id"; filename="obvius_session_id"
Content-Type: application/octet-stream
72c2b6f406cdabd578c5fd7598557c52
If the value is a tuple and the first entry is None
the filename property will not be included:
>>> files = {'obvius_session_id': (None, '72c2b6f406cdabd578c5fd7598557c52')}
Content-Disposition: form-data; name="obvius_session_id"
Content-Type: application/octet-stream
72c2b6f406cdabd578c5fd7598557c52
Using the SSKeychain and code mentioned above. Here's code to copy/paste (add SSKeychain module):
+(NSString *) getUUID {
//Use the bundle name as the App identifier. No need to get the localized version.
NSString *Appname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
//Check if we have UUID already
NSString *retrieveuuid = [SSKeychain passwordForService:Appname account:@"user"];
if (retrieveuuid == NULL)
{
//Create new key for this app/device
CFUUIDRef newUniqueId = CFUUIDCreate(kCFAllocatorDefault);
retrieveuuid = (__bridge_transfer NSString*)CFUUIDCreateString(kCFAllocatorDefault, newUniqueId);
CFRelease(newUniqueId);
//Save key to Keychain
[SSKeychain setPassword:retrieveuuid forService:Appname account:@"user"];
}
return retrieveuuid;
}
If you are looking for a single result, rather than an array, may I suggest reduce?
Here is a solution in plain 'ole javascript that returns a matching object if one exists, or null if not.
var result = arr.reduce(function(prev, curr) { return (curr.b === 6) ? curr : prev; }, null);
Just create a new branch with git checkout -b ABC_1
; your uncommitted changes will be kept, and you then commit them to that branch.
This worked for me,
var loc = "abcdefghi".rangeOfString("c").location
NSLog("%d", loc);
this worked too,
var myRange: NSRange = "abcdefghi".rangeOfString("c")
var loc = myRange.location
NSLog("%d", loc);
using pymsql if it helps
import pymysql
import csv
db = pymysql.connect("localhost","root","12345678","data" )
cursor = db.cursor()
csv_data = csv.reader(open('test.csv'))
next(csv_data)
for row in csv_data:
cursor.execute('INSERT INTO PM(col1,col2) VALUES(%s, %s)',row)
db.commit()
cursor.close()
For any React Router v4 users arriving here following a search, optional parameters in a <Route>
are denoted with a ?
suffix.
Here's the relevant documentation:
https://reacttraining.com/react-router/web/api/Route/path-string
path: string
Any valid URL path that path-to-regexp understands.
<Route path="/users/:id" component={User}/>
https://www.npmjs.com/package/path-to-regexp#optional
Optional
<Route path="/section/:page?" component={Section} />
Yes. The VBA equivalent of AltEnter is to use a linebreak character:
ActiveCell.Value = "I am a " & Chr(10) & "test"
Note that this automatically sets WrapText
to True.
Proof:
Sub test()
Dim c As Range
Set c = ActiveCell
c.WrapText = False
MsgBox "Activcell WrapText is " & c.WrapText
c.Value = "I am a " & Chr(10) & "test"
MsgBox "Activcell WrapText is " & c.WrapText
End Sub
While it's not a batch process, Visual Studio can also add/edit file resources.
Just use File->Open->File on the .EXE or .DLL. This is handy for fixing version information post-build, or adding it to files that don't have these resources to begin with.
There's a much better solution for this problem.
Just take a normal Button
and use the drawableLeft
and the gravity
attributes.
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/my_btn_icon"
android:gravity="left|center_vertical" />
This way you get a button which displays a icon in the left side of the button and the text at the right site of the icon vertical centered.
http://www.pip-installer.org/en/latest/installing.html is really the canonical answer to this question.
Specifically, the systemwide instructions are:
$ curl -O http://python-distribute.org/distribute_setup.py
$ python distribute_setup.py
$ curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
$ python get-pip.py
The section quoted in the question is the virtualenv
instructions rather than the systemwide ones. The easy_install
instructions have been around for longer, but it isn't necessary to do it that way any more.
The best way to accomplish that is to use POST which is a method of Hypertext Transfer Protocol https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
index.php
<html>
<body>
<form action="site2.php" method="post">
Name: <input type="text" name="name">
Email: <input type="text" name="email">
<input type="submit">
</form>
</body>
</html>
site2.php
<html>
<body>
Hello <?php echo $_POST["name"]; ?>!<br>
Your mail is <?php echo $_POST["mail"]; ?>.
</body>
</html>
output
Hello "name" !
Your email is "[email protected]" .
Or (in VB.NET):
Function InstanceCount(ByVal StringToSearch As String,
ByVal StringToFind As String) As Long
If Len(StringToFind) Then
InstanceCount = UBound(Split(StringToSearch, StringToFind))
End If
End Function
First, it's always worth noting that git reset --hard
is a potentially dangerous command, since it throws away all your uncommitted changes. For safety, you should always check that the output of git status
is clean (that is, empty) before using it.
Initially you say the following:
So I know that Git tracks changes I make to my application, and it holds on to them until I commit the changes, but here's where I'm hung up:
That's incorrect. Git only records the state of the files when you stage them (with git add
) or when you create a commit. Once you've created a commit which has your project files in a particular state, they're very safe, but until then Git's not really "tracking changes" to your files. (for example, even if you do git add
to stage a new version of the file, that overwrites the previously staged version of that file in the staging area.)
In your question you then go on to ask the following:
When I want to revert to a previous commit I use: git reset --hard HEAD And git returns: HEAD is now at 820f417 micro
How do I then revert the files on my hard drive back to that previous commit?
If you do git reset --hard <SOME-COMMIT>
then Git will:
master
) back to point at <SOME-COMMIT>
.<SOME-COMMIT>
.HEAD
points to your current branch (or current commit), so all that git reset --hard HEAD
will do is to throw away any uncommitted changes you have.
So, suppose the good commit that you want to go back to is f414f31
. (You can find that via git log
or any history browser.) You then have a few different options depending on exactly what you want to do:
git reset --hard f414f31
. However, this is rewriting the history of your branch, so you should avoid it if you've shared this branch with anyone. Also, the commits you did after f414f31
will no longer be in the history of your master
branch.Create a new commit that represents exactly the same state of the project as f414f31
, but just adds that on to the history, so you don't lose any history. You can do that using the steps suggested in this answer - something like:
git reset --hard f414f31
git reset --soft HEAD@{1}
git commit -m "Reverting to the state of the project at f414f31"
I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.
Assuming your data is in ColumnA:C
and has column labels in Row 1, also that Month is formatted mmm
(this last for ease of sorting):
D2
=IF(AND(A2=A1,C2=C1),D1+1,1)
(One way to deal with what is the tricky issue of multiple entries for the same person for the same month).A1:D(last occupied row no.)
F1
.I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.
L1
.L1
and shift down.L1
.ColumnL
, select Row Labels
and numeric values.L2:L(last selected cell)
Happy to explain further/try again (I've not really tested this) if does not suit.
EDIT (To avoid second block of steps above and facilitate updating for source data changes)
.0. Before first step 2. add a blank row at the very top and move A2:D2
up.
.2. Adjust cell references accordingly (in D3
=IF(AND(A3=A2,C3=C2),D2+1,1)
.
.3. Create pivot table from A:D
.6. Overwrite Row Labels
with Name
.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1
, ColumnG
and rows and columns that show (blank)
.
Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).
Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank)
into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.
pygame
on any platformThe advantage of using pygame
is that it can be made to work on any OS platform. Below example code is for GNU/Linux though.
First install the pygame
module for python3
as explained in detail here.
$ sudo pip3 install pygame
The pygame
module can play .wav
and .ogg
files from any file location. Here is an example:
#!/usr/bin/env python3
import pygame
pygame.mixer.init()
sound = pygame.mixer.Sound('/usr/share/sounds/freedesktop/stereo/phone-incoming-call.oga')
sound.play()
Great answer of Josh, all credit to him, I slightly modified it to this however:
MyDialog Xaml
<StackPanel Margin="5,5,5,5">
<TextBlock Name="TitleTextBox" Margin="0,0,0,10" />
<TextBox Name="InputTextBox" Padding="3,3,3,3" />
<Grid Margin="0,10,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Name="BtnOk" Content="OK" Grid.Column="0" Margin="0,0,5,0" Padding="8" Click="BtnOk_Click" />
<Button Name="BtnCancel" Content="Cancel" Grid.Column="1" Margin="5,0,0,0" Padding="8" Click="BtnCancel_Click" />
</Grid>
</StackPanel>
MyDialog Code Behind
public MyDialog()
{
InitializeComponent();
}
public MyDialog(string title,string input)
{
InitializeComponent();
TitleText = title;
InputText = input;
}
public string TitleText
{
get { return TitleTextBox.Text; }
set { TitleTextBox.Text = value; }
}
public string InputText
{
get { return InputTextBox.Text; }
set { InputTextBox.Text = value; }
}
public bool Canceled { get; set; }
private void BtnCancel_Click(object sender, System.Windows.RoutedEventArgs e)
{
Canceled = true;
Close();
}
private void BtnOk_Click(object sender, System.Windows.RoutedEventArgs e)
{
Canceled = false;
Close();
}
And call it somewhere else
var dialog = new MyDialog("test", "hello");
dialog.Show();
dialog.Closing += (sender,e) =>
{
var d = sender as MyDialog;
if(!d.Canceled)
MessageBox.Show(d.InputText);
}
It might help you! demo
AngularJs Code-sample
var app = angular.module('urlApp', []);
app.controller('urlCtrl', function ($scope, $log, $window) {
$scope.ClickMeToRedirect = function () {
var url = "http://" + $window.location.host + "/Account/Login";
$log.log(url);
$window.location.href = url;
};
});
HTML Code-sample
<div ng-app="urlApp">
<div ng-controller="urlCtrl">
Redirect to <a href="#" ng-click="ClickMeToRedirect()">Click Me!</a>
</div>
</div>
try
ps |&
while read -p first second third fourth etc ; do
if [[ $first == '11383' ]]
then
echo got: $fourth
fi
done
The simplest solution I've found to the exact same problem is to use a multiple line table with one row and no header (there is an image in the first column and the text in the second):
----------------------- ------------------------------------
![Tip](images/tip.png)\ Table multiline text bla bla bla bla
bla bla bla bla bla bla bla ... the
blank line below is important
----------------------------------------------------------------
Another approach that might work (for PDF) is to use Latex default fbox directive :
\fbox{My text!}
Or FancyBox module for more advanced features (and better looking boxes) : http://www.ctan.org/tex-archive/macros/latex/contrib/fancybox.
You can take a look at InterpolatedUnivariateSpline
Here an example using it:
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline
# given values
xi = np.array([0.2, 0.5, 0.7, 0.9])
yi = np.array([0.3, -0.1, 0.2, 0.1])
# positions to inter/extrapolate
x = np.linspace(0, 1, 50)
# spline order: 1 linear, 2 quadratic, 3 cubic ...
order = 1
# do inter/extrapolation
s = InterpolatedUnivariateSpline(xi, yi, k=order)
y = s(x)
# example showing the interpolation for linear, quadratic and cubic interpolation
plt.figure()
plt.plot(xi, yi)
for order in range(1, 4):
s = InterpolatedUnivariateSpline(xi, yi, k=order)
y = s(x)
plt.plot(x, y)
plt.show()
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
nc or 'netcat' also has a scan mode which may be of use.
If you need a recursive function that will produce proper URL parameters based on the object given, try my Coffee-Script one.
@toParams = (params) ->
pairs = []
do proc = (object=params, prefix=null) ->
for own key, value of object
if value instanceof Array
for el, i in value
proc(el, if prefix? then "#{prefix}[#{key}][]" else "#{key}[]")
else if value instanceof Object
if prefix?
prefix += "[#{key}]"
else
prefix = key
proc(value, prefix)
else
pairs.push(if prefix? then "#{prefix}[#{key}]=#{value}" else "#{key}=#{value}")
pairs.join('&')
or the JavaScript compiled...
toParams = function(params) {
var pairs, proc;
pairs = [];
(proc = function(object, prefix) {
var el, i, key, value, _results;
if (object == null) object = params;
if (prefix == null) prefix = null;
_results = [];
for (key in object) {
if (!__hasProp.call(object, key)) continue;
value = object[key];
if (value instanceof Array) {
_results.push((function() {
var _len, _results2;
_results2 = [];
for (i = 0, _len = value.length; i < _len; i++) {
el = value[i];
_results2.push(proc(el, prefix != null ? "" + prefix + "[" + key + "][]" : "" + key + "[]"));
}
return _results2;
})());
} else if (value instanceof Object) {
if (prefix != null) {
prefix += "[" + key + "]";
} else {
prefix = key;
}
_results.push(proc(value, prefix));
} else {
_results.push(pairs.push(prefix != null ? "" + prefix + "[" + key + "]=" + value : "" + key + "=" + value));
}
}
return _results;
})();
return pairs.join('&');
};
This will construct strings like so:
toParams({a: 'one', b: 'two', c: {x: 'eight', y: ['g','h','j'], z: {asdf: 'fdsa'}}})
"a=one&b=two&c[x]=eight&c[y][0]=g&c[y][1]=h&c[y][2]=j&c[y][z][asdf]=fdsa"
If you just want the difference in years, there's:
SELECT EXTRACT(YEAR FROM date1) - EXTRACT(YEAR FROM date2) FROM mytable
Or do you want fractional years as well?
SELECT (date1 - date2) / 365.242199 FROM mytable
365.242199 is 1 year in days, according to Google.
nodeName
is the attribute you are looking for. For example:
var elt = document.getElementById('foo');
console.log(elt.nodeName);
Note that nodeName
returns the element name capitalized and without the angle brackets, which means that if you want to check if an element is an <div>
element you could do it as follows:
elt.nodeName == "DIV"
While this would not give you the expected results:
elt.nodeName == "<div>"
In my case I had to reference a C/C++ library using P/Invoke, but I had to ensure that the memory was allocated for the output array first using fixed
:
[DllImport("my_c_func_lib.dll", CharSet = CharSet.Ansi)]
public static extern unsafe int my_c_func(double input1, double input2, double pinput3, double *outData);
public unsafe double[] GetMyUnmanagedCodeValue(double input1, double input2, double input3)
{
double[] outData = new double[24];
fixed (double* returnValue = outData)
{
my_c_func(input1, input2, pinput3, returnValue);
}
return outData;
}
For details please see: https://www.c-sharpcorner.com/article/pointers-in-C-Sharp/
Switch -J
only works on newer systems. The universal command is:
To make .tar.xz archive
tar cf - directory/ | xz -z - > directory.tar.xz
Explanation
tar cf - directory
reads directory/ and starts putting it to TAR format. The output of this operation is generated on the standard output.
|
pipes standard output to the input of another program...
... which happens to be xz -z -
. XZ is configured to compress (-z
) the archive from standard input (-
).
You redirect the output from xz
to the tar.xz
file.
In my case git push
was trying to push more that just the current branch, therefore, I got this error since the other branches were not in sync.
To fix that you could use: git config --global push.default simple
That will make git to only push the current branch.
This will only work on more recent versions of git. i.e.: won't work on 1.7.9.5
Replacing the button to a custom one as suggested on another answer is possibly not a great idea as you will lose the default behavior and style.
One other option you have is to implement the viewWillDisappear method on the View Controller and check for a property named isMovingFromParentViewController. If that property is true, it means the View Controller is disappearing because it's being removed (popped).
Should look something like:
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if self.isMovingFromParentViewController {
// Your code...
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if self.isMovingFromParent {
// Your code...
}
}
Issue is with the Json.parse of empty array - scatterSeries , as you doing console log of scatterSeries before pushing ch
var data = { "results":[ _x000D_
[ _x000D_
{ _x000D_
"b":"0.110547334",_x000D_
"cost":"0.000000",_x000D_
"w":"1.998889"_x000D_
}_x000D_
],_x000D_
[ _x000D_
{ _x000D_
"x":0,_x000D_
"y":0_x000D_
},_x000D_
{ _x000D_
"x":1,_x000D_
"y":2_x000D_
},_x000D_
{ _x000D_
"x":2,_x000D_
"y":4_x000D_
},_x000D_
{ _x000D_
"x":3,_x000D_
"y":6_x000D_
},_x000D_
{ _x000D_
"x":4,_x000D_
"y":8_x000D_
},_x000D_
{ _x000D_
"x":5,_x000D_
"y":10_x000D_
},_x000D_
{ _x000D_
"x":6,_x000D_
"y":12_x000D_
},_x000D_
{ _x000D_
"x":7,_x000D_
"y":14_x000D_
},_x000D_
{ _x000D_
"x":8,_x000D_
"y":16_x000D_
},_x000D_
{ _x000D_
"x":9,_x000D_
"y":18_x000D_
},_x000D_
{ _x000D_
"x":10,_x000D_
"y":20_x000D_
},_x000D_
{ _x000D_
"x":11,_x000D_
"y":22_x000D_
},_x000D_
{ _x000D_
"x":12,_x000D_
"y":24_x000D_
},_x000D_
{ _x000D_
"x":13,_x000D_
"y":26_x000D_
},_x000D_
{ _x000D_
"x":14,_x000D_
"y":28_x000D_
},_x000D_
{ _x000D_
"x":15,_x000D_
"y":30_x000D_
},_x000D_
{ _x000D_
"x":16,_x000D_
"y":32_x000D_
},_x000D_
{ _x000D_
"x":17,_x000D_
"y":34_x000D_
},_x000D_
{ _x000D_
"x":18,_x000D_
"y":36_x000D_
},_x000D_
{ _x000D_
"x":19,_x000D_
"y":38_x000D_
},_x000D_
{ _x000D_
"x":20,_x000D_
"y":40_x000D_
},_x000D_
{ _x000D_
"x":21,_x000D_
"y":42_x000D_
},_x000D_
{ _x000D_
"x":22,_x000D_
"y":44_x000D_
},_x000D_
{ _x000D_
"x":23,_x000D_
"y":46_x000D_
},_x000D_
{ _x000D_
"x":24,_x000D_
"y":48_x000D_
},_x000D_
{ _x000D_
"x":25,_x000D_
"y":50_x000D_
},_x000D_
{ _x000D_
"x":26,_x000D_
"y":52_x000D_
},_x000D_
{ _x000D_
"x":27,_x000D_
"y":54_x000D_
},_x000D_
{ _x000D_
"x":28,_x000D_
"y":56_x000D_
},_x000D_
{ _x000D_
"x":29,_x000D_
"y":58_x000D_
},_x000D_
{ _x000D_
"x":30,_x000D_
"y":60_x000D_
},_x000D_
{ _x000D_
"x":31,_x000D_
"y":62_x000D_
},_x000D_
{ _x000D_
"x":32,_x000D_
"y":64_x000D_
},_x000D_
{ _x000D_
"x":33,_x000D_
"y":66_x000D_
},_x000D_
{ _x000D_
"x":34,_x000D_
"y":68_x000D_
},_x000D_
{ _x000D_
"x":35,_x000D_
"y":70_x000D_
},_x000D_
{ _x000D_
"x":36,_x000D_
"y":72_x000D_
},_x000D_
{ _x000D_
"x":37,_x000D_
"y":74_x000D_
},_x000D_
{ _x000D_
"x":38,_x000D_
"y":76_x000D_
},_x000D_
{ _x000D_
"x":39,_x000D_
"y":78_x000D_
},_x000D_
{ _x000D_
"x":40,_x000D_
"y":80_x000D_
},_x000D_
{ _x000D_
"x":41,_x000D_
"y":82_x000D_
},_x000D_
{ _x000D_
"x":42,_x000D_
"y":84_x000D_
},_x000D_
{ _x000D_
"x":43,_x000D_
"y":86_x000D_
},_x000D_
{ _x000D_
"x":44,_x000D_
"y":88_x000D_
},_x000D_
{ _x000D_
"x":45,_x000D_
"y":90_x000D_
},_x000D_
{ _x000D_
"x":46,_x000D_
"y":92_x000D_
},_x000D_
{ _x000D_
"x":47,_x000D_
"y":94_x000D_
},_x000D_
{ _x000D_
"x":48,_x000D_
"y":96_x000D_
},_x000D_
{ _x000D_
"x":49,_x000D_
"y":98_x000D_
},_x000D_
{ _x000D_
"x":50,_x000D_
"y":100_x000D_
},_x000D_
{ _x000D_
"x":51,_x000D_
"y":102_x000D_
},_x000D_
{ _x000D_
"x":52,_x000D_
"y":104_x000D_
},_x000D_
{ _x000D_
"x":53,_x000D_
"y":106_x000D_
},_x000D_
{ _x000D_
"x":54,_x000D_
"y":108_x000D_
},_x000D_
{ _x000D_
"x":55,_x000D_
"y":110_x000D_
},_x000D_
{ _x000D_
"x":56,_x000D_
"y":112_x000D_
},_x000D_
{ _x000D_
"x":57,_x000D_
"y":114_x000D_
},_x000D_
{ _x000D_
"x":58,_x000D_
"y":116_x000D_
},_x000D_
{ _x000D_
"x":59,_x000D_
"y":118_x000D_
},_x000D_
{ _x000D_
"x":60,_x000D_
"y":120_x000D_
},_x000D_
{ _x000D_
"x":61,_x000D_
"y":122_x000D_
},_x000D_
{ _x000D_
"x":62,_x000D_
"y":124_x000D_
},_x000D_
{ _x000D_
"x":63,_x000D_
"y":126_x000D_
},_x000D_
{ _x000D_
"x":64,_x000D_
"y":128_x000D_
},_x000D_
{ _x000D_
"x":65,_x000D_
"y":130_x000D_
},_x000D_
{ _x000D_
"x":66,_x000D_
"y":132_x000D_
},_x000D_
{ _x000D_
"x":67,_x000D_
"y":134_x000D_
},_x000D_
{ _x000D_
"x":68,_x000D_
"y":136_x000D_
},_x000D_
{ _x000D_
"x":69,_x000D_
"y":138_x000D_
},_x000D_
{ _x000D_
"x":70,_x000D_
"y":140_x000D_
},_x000D_
{ _x000D_
"x":71,_x000D_
"y":142_x000D_
},_x000D_
{ _x000D_
"x":72,_x000D_
"y":144_x000D_
},_x000D_
{ _x000D_
"x":73,_x000D_
"y":146_x000D_
},_x000D_
{ _x000D_
"x":74,_x000D_
"y":148_x000D_
},_x000D_
{ _x000D_
"x":75,_x000D_
"y":150_x000D_
},_x000D_
{ _x000D_
"x":76,_x000D_
"y":152_x000D_
},_x000D_
{ _x000D_
"x":77,_x000D_
"y":154_x000D_
},_x000D_
{ _x000D_
"x":78,_x000D_
"y":156_x000D_
},_x000D_
{ _x000D_
"x":79,_x000D_
"y":158_x000D_
},_x000D_
{ _x000D_
"x":80,_x000D_
"y":160_x000D_
},_x000D_
{ _x000D_
"x":81,_x000D_
"y":162_x000D_
},_x000D_
{ _x000D_
"x":82,_x000D_
"y":164_x000D_
},_x000D_
{ _x000D_
"x":83,_x000D_
"y":166_x000D_
},_x000D_
{ _x000D_
"x":84,_x000D_
"y":168_x000D_
},_x000D_
{ _x000D_
"x":85,_x000D_
"y":170_x000D_
},_x000D_
{ _x000D_
"x":86,_x000D_
"y":172_x000D_
},_x000D_
{ _x000D_
"x":87,_x000D_
"y":174_x000D_
},_x000D_
{ _x000D_
"x":88,_x000D_
"y":176_x000D_
},_x000D_
{ _x000D_
"x":89,_x000D_
"y":178_x000D_
},_x000D_
{ _x000D_
"x":90,_x000D_
"y":180_x000D_
},_x000D_
{ _x000D_
"x":91,_x000D_
"y":182_x000D_
},_x000D_
{ _x000D_
"x":92,_x000D_
"y":184_x000D_
},_x000D_
{ _x000D_
"x":93,_x000D_
"y":186_x000D_
},_x000D_
{ _x000D_
"x":94,_x000D_
"y":188_x000D_
},_x000D_
{ _x000D_
"x":95,_x000D_
"y":190_x000D_
},_x000D_
{ _x000D_
"x":96,_x000D_
"y":192_x000D_
},_x000D_
{ _x000D_
"x":97,_x000D_
"y":194_x000D_
},_x000D_
{ _x000D_
"x":98,_x000D_
"y":196_x000D_
},_x000D_
{ _x000D_
"x":99,_x000D_
"y":198_x000D_
}_x000D_
]]};_x000D_
_x000D_
var scatterSeries = []; _x000D_
_x000D_
var ch = '{"name":"graphe1","items":'+JSON.stringify(data.results[1])+ '}';_x000D_
console.info(ch);_x000D_
_x000D_
scatterSeries.push(JSON.parse(ch));_x000D_
console.info(scatterSeries);
_x000D_
code sample - https://codepen.io/nagasai/pen/GGzZVB
See this link. It shows you how to dynamically create variables in PowerShell.
Here is the basic idea:
Use New-Variable and Get-Variable,
for ($i=1; $i -le 5; $i++)
{
New-Variable -Name "var$i" -Value $i
Get-Variable -Name "var$i" -ValueOnly
}
(It is taken from the link provided, and I don't take credit for the code.)
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A // 'private' is default for classes
{
// x is private
// y is private
// z is not accessible from D
};
IMPORTANT NOTE: Classes B, C and D all contain the variables x, y and z. It is just question of access.
About usage of protected and private inheritance you could read here.
AWS EC2 install running python34:
sudo yum install python34-devel
import data from './data.json';
export class AppComponent {
json:any = data;
}
See this article for more details.
Sometimes, pprint()
in pprint
module works wonder, especially for dict
variables.
In addition to the solution with 'aaaaaaaa' LIKE '%' || tag_name || '%'
there
are position
(reversed order of args) and strpos
.
SELECT id FROM TAG_TABLE WHERE strpos('aaaaaaaa', tag_name) > 0
Besides what is more efficient (LIKE looks less efficient, but an index might change things), there is a very minor issue with LIKE: tag_name of course should not contain %
and especially _
(single char wildcard), to give no false positives.
You can set an ENV if you want your Time.now
and DateTime.now
to respond in UTC time.
require 'date'
Time.now #=> 2015-11-30 11:37:14 -0800
DateTime.now.to_s #=> "2015-11-30T11:37:25-08:00"
ENV['TZ'] = 'UTC'
Time.now #=> 2015-11-30 19:37:38 +0000
DateTime.now.to_s #=> "2015-11-30T19:37:36+00:00"
Had to debug a site for native Android browser and came here. So I tried weinre on an OS X 10.9 (as weinre server) with Firefox 30.0 (weinre client) and an Android 4.1.2 (target). I'm really, really surprised of the result.
sudo npm -g install weinre
weinre --boundHost YOUR.IP.ADDRESS.HERE
http://YOUR.IP.ADRESS.HERE:8080
<script src="http://YOUR.IP.ADDRESS.HERE:8080/target/target-script-min.js"></script>
Maybe 8080 isn't your default port. Then in step 4 you have to call weinre --httpPort YOURPORT --boundHost YOUR.IP.ADRESS.HERE
.
And I don't remember exactly when it was, maybe somewhere after step 5, I had to accept incoming connections prompt, of course.
Happy debugging
P.S. I'm still overwhelmed how good that works. Even elements-highlighting work
You have to do:
git branch <branch_name> <commit>
(you were interchanging the branch name and commit)
Or you can do:
git checkout -b <branch_name> <commit>
If in place of you use branch name, you get a branch out of tip of the branch.
One of the reasons for this error is the use of the jaxb implementation from the jdk. I am not sure why such a problem can appear in pretty simple xml parsing situations. You may use the latest version of the jaxb library from a public maven repository:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.12</version>
</dependency>
I inherited a bunch of .JAVA files from elsewhere and couldn't figure out how to get them to work in any IDE. Ultimately I had to go to the command line where the Main.JAVA file was and run javac Main.java
. This created a bunch of .CLASS files. The IDE's were then able to figure out what to do.
The tensorflow version can be checked either on terminal or console or in any IDE editer as well (like Spyder or Jupyter notebook, etc)
Simple command to check version:
(py36) C:\WINDOWS\system32>python
Python 3.6.8 |Anaconda custom (64-bit)
>>> import tensorflow as tf
>>> tf.__version__
'1.13.1'
Under normal conditions, at least 3379 MB of disk space is needed. If you do not have that much space, to lower this requirement;
mongod.exe --smallfiles
This is not the only requirement. But this may be your problem.
If fptr
is NULL
, then you don't have an open file. Therefore, you can't freopen
it, you should just fopen
it.
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
fptr = fopen("scores.dat", "wb");
}
note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.
int main()
{
FILE *fptr;
char there_was_error = 0;
char opened_in_read = 1;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
opened_in_read = 0;
fptr = fopen("scores.dat", "wb");
if (fptr == NULL)
there_was_error = 1;
}
if (there_was_error)
{
printf("Disc full or no permission\n");
return EXIT_FAILURE;
}
if (opened_in_read)
printf("The file is opened in read mode."
" Let's read some cached data\n");
else
printf("The file is opened in write mode."
" Let's do some processing and cache the results\n");
return EXIT_SUCCESS;
}
var mode = [];
$("input[name='mode[]']:checked").each(function(i) {
mode.push($(this).val());
})
if(mode.length == 0)
{
alert('Please select mode!')
};
upstream
defines a cluster that you can proxy requests to. It's commonly used for defining either a web server cluster for load balancing, or an app server cluster for routing / load balancing.
In the simple case you can do:
var user = cnn.Query<User>("spGetUser", new {Id = 1},
commandType: CommandType.StoredProcedure).First();
If you want something more fancy, you can do:
var p = new DynamicParameters();
p.Add("@a", 11);
p.Add("@b", dbType: DbType.Int32, direction: ParameterDirection.Output);
p.Add("@c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
cnn.Execute("spMagicProc", p, commandType: CommandType.StoredProcedure);
int b = p.Get<int>("@b");
int c = p.Get<int>("@c");
Additionally you can use exec in a batch, but that is more clunky.
Focus might be what your looking for. With tabbing or clicking I think u mean giving the element the focus. Same code as Russ (Sorry i stole it :P) but firing an other event.
// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");
if (element) element.focus();
In my case i use the replace method by testing every entity in every variable, my code looks like this:
text = text.replace("Ç", "Ç");
text = text.replace("ç", "ç");
text = text.replace("Á", "Á");
text = text.replace("Â", "Â");
text = text.replace("Ã", "Ã");
text = text.replace("É", "É");
text = text.replace("Ê", "Ê");
text = text.replace("Í", "Í");
text = text.replace("Ô", "Ô");
text = text.replace("Õ", "Õ");
text = text.replace("Ó", "Ó");
text = text.replace("Ú", "Ú");
text = text.replace("á", "á");
text = text.replace("â", "â");
text = text.replace("ã", "ã");
text = text.replace("é", "é");
text = text.replace("ê", "ê");
text = text.replace("í", "í");
text = text.replace("ô", "ô");
text = text.replace("õ", "õ");
text = text.replace("ó", "ó");
text = text.replace("ú", "ú");
In my case this worked very well.
Just use puttygen and load your private key into it. It offers different options, e.g. exporting the corresponding public key.
How about
SELECT EmailAddress, CustomerName FROM Customers a
WHERE Exists ( SELECT emailAddress FROM customers c WHERE a.customerName != c.customerName AND a.EmailAddress = c.EmailAddress)
I am trying to avoid using VBA. But if has to be, then it has to be:)
There is quite simple UDF for you:
Function myCountIf(rng As Range, criteria) As Long
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
Next ws
End Function
and call it like this: =myCountIf(I:I,A13)
P.S. if you'd like to exclude some sheets, you can add If
statement:
Function myCountIf(rng As Range, criteria) As Long
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.name <> "Sheet1" And ws.name <> "Sheet2" Then
myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
End If
Next ws
End Function
UPD:
I have four "reference" sheets that I need to exclude from being scanned/searched. They are currently the last four in the workbook
Function myCountIf(rng As Range, criteria) As Long
Dim i As Integer
For i = 1 To ThisWorkbook.Worksheets.Count - 4
myCountIf = myCountIf + WorksheetFunction.CountIf(ThisWorkbook.Worksheets(i).Range(rng.Address), criteria)
Next i
End Function
You can use max-height
in an inline style
attribute, as below:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
To use scrolling with content that overflows a given max-height
, you can alternatively try the following:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>
To restrict the height to a fixed value you can use something like this.
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
Specify the same value for both max-height
and min-height
(either in pixels or in points – as long as it’s consistent).
You can also put the same styles in css class in a stylesheet (or a style
tag as shown below) and then include the same in your tag. See below:
Style Code:
.fixed-panel {
min-height: 10;
max-height: 10;
overflow-y: scroll;
}
Apply Style :
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>
Hope this helps with your need.
You might want want to rethink the structure of you application, if you really, really want one method to return multiple values.
Either break things apart, so distinct methods return distinct values, or figure out a logical grouping and build an object to hold that data that can in turn be returned.
' this is the VB6/VBA equivalent of a struct
' data, no methods
Private Type settings
root As String
path As String
name_first As String
name_last As String
overwrite_prompt As Boolean
End Type
Public Sub Main()
Dim mySettings As settings
mySettings = getSettings()
End Sub
' if you want this to be public, you're better off with a class instead of a User-Defined-Type (UDT)
Private Function getSettings() As settings
Dim sets As settings
With sets ' retrieve values here
.root = "foo"
.path = "bar"
.name_first = "Don"
.name_last = "Knuth"
.overwrite_prompt = False
End With
' return a single struct, vb6/vba-style
getSettings = sets
End Function
Only changing the settings with the following command did not work in my environment:
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
I had to also ran the Force Merge API command:
curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"
ref: Force Merge API
The .git
at the end of the repository name is just a convention. Typically, on git servers repositories are kept in directories named project.git
. The git client and protocol honours this convention by testing for project.git
when only project
is specified.
git://[email protected]/peter/first_app.git
is not a valid git url. git repositories can be identified and accessed via various url schemes specified here. [email protected]:peter/first_app.git
is the ssh
url mentioned on that page.
git
is flexible. It allows you to track your local branch against almost any branch of any repository. While master
(your local default branch) tracking origin/master
(the remote default branch) is a popular situation, it is not universal. Many a times you may not want to do that. This is why the first git push
is so verbose. It tells git what to do with the local master
branch when you do a git pull
or a git push
.
The default for git push
and git pull
is to work with the current branch's remote. This is a better default than origin master. The way git push determines this is explained here.
git
is fairly elegant and comprehensible but there is a learning curve to walk through.
You can do it like this:
DataTable dt = new DataTable("MyTable");
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
if (row[column] != null) // This will check the null values also (if you want to check).
{
// Do whatever you want.
}
}
}
This should work for you. Infact the one which you are thinking will also work:-
.......
DECLARE @returnvalue INT
EXEC @returnvalue = SP_One
.....
Also You can use
$value = $("#txt").val();
if($value == "")
{
//Your Code Here
}
else
{
//Your code
}
Try it. It work.
Multiple questions require input for several integers on single line. The best way is to input the whole string of numbers one one line and then split them to integers. Here is a Python 3 version:
a = []
p = input()
p = p.split()
for i in p:
a.append(int(i))
Also a list comprehension can be used
p = input().split("whatever the seperator is")
And to convert all the inputs from string to int we do the following
x = [int(i) for i in p]
print(x, end=' ')
shall print the list elements in a straight line.
You should use modules, see http://modules.sourceforge.net/
EDIT: The modules package has not been updated since 2012 but still works ok for the basics. All the new features, bells and whistles happen in lmod this day (which I like it more): https://www.tacc.utexas.edu/research-development/tacc-projects/lmod
Select a range of cells (the entire column in this case), type in your formula, and hold down Ctrl while you press Enter. This places the formula in all selected cells.
You first must install python. Mac comes with python 2.7 installed to install Python 3 you can follow this tutorial: http://docs.python-guide.org/en/latest/starting/install3/osx/.
To run the program you can then copy and paste in this code:
python /Users/luca/Documents/python/gameover.py
Or you can go to the directory of the file with cd
followed by the folder. When you are in the folder you can then python YourFile.py
.
I just finished writing my own optimised implementation of normalized cross-correlation for N-dimensional arrays. You can get it from here.
It will calculate cross-correlation either directly, using scipy.ndimage.correlate
, or in the frequency domain, using scipy.fftpack.fftn
/ifftn
depending on whichever will be quickest.
Mark, this is already answered in your previous topic. But OK, here it is again:
Suppose ${list}
points to a List<Object>
, then the following
<c:forEach items="${list}" var="item">
${item}<br>
</c:forEach>
does basically the same as as following in "normal Java":
for (Object item : list) {
System.out.println(item);
}
If you have a List<Map<K, V>>
instead, then the following
<c:forEach items="${list}" var="map">
<c:forEach items="${map}" var="entry">
${entry.key}<br>
${entry.value}<br>
</c:forEach>
</c:forEach>
does basically the same as as following in "normal Java":
for (Map<K, V> map : list) {
for (Entry<K, V> entry : map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
The key
and value
are here not special methods or so. They are actually getter methods of Map.Entry
object (click at the blue Map.Entry
link to see the API doc). In EL (Expression Language) you can use the .
dot operator to access getter methods using "property name" (the getter method name without the get
prefix), all just according the Javabean specification.
That said, you really need to cleanup the "answers" in your previous topic as they adds noise to the question. Also read the comments I posted in your "answers".
With Swift 5 and iOS 12.3, you can use one the 4 following implementations in order to set the number of items per row in your UICollectionView
while managing insets and size changes (including rotation).
UICollectionViewFlowLayout
and using UICollectionViewFlowLayout
's itemSize
propertyColumnFlowLayout.swift:
import UIKit
class ColumnFlowLayout: UICollectionViewFlowLayout {
let cellsPerRow: Int
init(cellsPerRow: Int, minimumInteritemSpacing: CGFloat = 0, minimumLineSpacing: CGFloat = 0, sectionInset: UIEdgeInsets = .zero) {
self.cellsPerRow = cellsPerRow
super.init()
self.minimumInteritemSpacing = minimumInteritemSpacing
self.minimumLineSpacing = minimumLineSpacing
self.sectionInset = sectionInset
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepare() {
super.prepare()
guard let collectionView = collectionView else { return }
let marginsAndInsets = sectionInset.left + sectionInset.right + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
itemSize = CGSize(width: itemWidth, height: itemWidth)
}
override func invalidationContext(forBoundsChange newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext {
let context = super.invalidationContext(forBoundsChange: newBounds) as! UICollectionViewFlowLayoutInvalidationContext
context.invalidateFlowLayoutDelegateMetrics = newBounds.size != collectionView?.bounds.size
return context
}
}
CollectionViewController.swift:
import UIKit
class CollectionViewController: UICollectionViewController {
let columnLayout = ColumnFlowLayout(
cellsPerRow: 5,
minimumInteritemSpacing: 10,
minimumLineSpacing: 10,
sectionInset: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
)
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.collectionViewLayout = columnLayout
collectionView?.contentInsetAdjustmentBehavior = .always
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 59
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = UIColor.orange
return cell
}
}
UICollectionViewFlowLayout
's itemSize
methodimport UIKit
class CollectionViewController: UICollectionViewController {
let margin: CGFloat = 10
let cellsPerRow = 5
override func viewDidLoad() {
super.viewDidLoad()
guard let collectionView = collectionView, let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else { return }
flowLayout.minimumInteritemSpacing = margin
flowLayout.minimumLineSpacing = margin
flowLayout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
collectionView.contentInsetAdjustmentBehavior = .always
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
}
override func viewWillLayoutSubviews() {
guard let collectionView = collectionView, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
let marginsAndInsets = flowLayout.sectionInset.left + flowLayout.sectionInset.right + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + flowLayout.minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 59
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = UIColor.orange
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
}
UICollectionViewDelegateFlowLayout
's collectionView(_:layout:sizeForItemAt:)
methodimport UIKit
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
let inset: CGFloat = 10
let minimumLineSpacing: CGFloat = 10
let minimumInteritemSpacing: CGFloat = 10
let cellsPerRow = 5
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.contentInsetAdjustmentBehavior = .always
collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return minimumLineSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return minimumInteritemSpacing
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let marginsAndInsets = inset * 2 + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
return CGSize(width: itemWidth, height: itemWidth)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 59
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
cell.backgroundColor = UIColor.orange
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
}
UICollectionViewFlowLayout
and using UICollectionViewFlowLayout
's estimatedItemSize
propertyCollectionViewController.swift:
import UIKit
class CollectionViewController: UICollectionViewController {
let items = [
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Lorem ipsum dolor sit amet, consectetur.",
"Lorem ipsum dolor sit amet.",
"Lorem ipsum dolor sit amet, consectetur.",
"Lorem ipsum dolor sit amet, consectetur adipiscing.",
"Lorem ipsum.",
"Lorem ipsum dolor sit amet.",
"Lorem ipsum dolor sit.",
"Lorem ipsum dolor sit amet, consectetur adipiscing.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor.",
"Lorem ipsum dolor sit amet, consectetur."
]
let columnLayout = FlowLayout(
cellsPerRow: 3,
minimumInteritemSpacing: 10,
minimumLineSpacing: 10,
sectionInset: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
)
override func viewDidLoad() {
super.viewDidLoad()
collectionView?.collectionViewLayout = columnLayout
collectionView?.contentInsetAdjustmentBehavior = .always
collectionView?.register(Cell.self, forCellWithReuseIdentifier: "Cell")
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! Cell
cell.label.text = items[indexPath.row]
return cell
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView?.collectionViewLayout.invalidateLayout()
super.viewWillTransition(to: size, with: coordinator)
}
}
FlowLayout.swift:
import UIKit
class FlowLayout: UICollectionViewFlowLayout {
let cellsPerRow: Int
required init(cellsPerRow: Int = 1, minimumInteritemSpacing: CGFloat = 0, minimumLineSpacing: CGFloat = 0, sectionInset: UIEdgeInsets = .zero) {
self.cellsPerRow = cellsPerRow
super.init()
self.minimumInteritemSpacing = minimumInteritemSpacing
self.minimumLineSpacing = minimumLineSpacing
self.sectionInset = sectionInset
estimatedItemSize = UICollectionViewFlowLayout.automaticSize
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
guard let layoutAttributes = super.layoutAttributesForItem(at: indexPath) else { return nil }
guard let collectionView = collectionView else { return layoutAttributes }
let marginsAndInsets = collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + sectionInset.left + sectionInset.right + minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
layoutAttributes.bounds.size.width = ((collectionView.bounds.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
return layoutAttributes
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let superLayoutAttributes = super.layoutAttributesForElements(in: rect)!.map { $0.copy() as! UICollectionViewLayoutAttributes }
guard scrollDirection == .vertical else { return superLayoutAttributes }
let layoutAttributes = superLayoutAttributes.compactMap { layoutAttribute in
return layoutAttribute.representedElementCategory == .cell ? layoutAttributesForItem(at: layoutAttribute.indexPath) : layoutAttribute
}
// (optional) Uncomment to top align cells that are on the same line
/*
let cellAttributes = layoutAttributes.filter({ $0.representedElementCategory == .cell })
for (_, attributes) in Dictionary(grouping: cellAttributes, by: { ($0.center.y / 10).rounded(.up) * 10 }) {
guard let max = attributes.max(by: { $0.size.height < $1.size.height }) else { continue }
for attribute in attributes where attribute.size.height != max.size.height {
attribute.frame.origin.y = max.frame.origin.y
}
}
*/
// (optional) Uncomment to bottom align cells that are on the same line
/*
let cellAttributes = layoutAttributes.filter({ $0.representedElementCategory == .cell })
for (_, attributes) in Dictionary(grouping: cellAttributes, by: { ($0.center.y / 10).rounded(.up) * 10 }) {
guard let max = attributes.max(by: { $0.size.height < $1.size.height }) else { continue }
for attribute in attributes where attribute.size.height != max.size.height {
attribute.frame.origin.y += max.frame.maxY - attribute.frame.maxY
}
}
*/
return layoutAttributes
}
}
Cell.swift:
import UIKit
class Cell: UICollectionViewCell {
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
label.numberOfLines = 0
backgroundColor = .orange
contentView.addSubview(label)
label.translatesAutoresizingMaskIntoConstraints = false
label.topAnchor.constraint(equalTo: contentView.layoutMarginsGuide.topAnchor).isActive = true
label.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor).isActive = true
label.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor).isActive = true
label.bottomAnchor.constraint(equalTo: contentView.layoutMarginsGuide.bottomAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
layoutIfNeeded()
label.preferredMaxLayoutWidth = label.bounds.size.width
layoutAttributes.bounds.size.height = contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
return layoutAttributes
}
// Alternative implementation
/*
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
label.preferredMaxLayoutWidth = layoutAttributes.size.width - contentView.layoutMargins.left - contentView.layoutMargins.right
layoutAttributes.bounds.size.height = contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
return layoutAttributes
}
*/
}
Looks like TaskCache registry data is in ...
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Schedule\TaskCache
... on my Windows 10 PC (i.e. add Schedule before TaskCache and TaskCache has an upper case C).
The following should return a boolean:
callable(x)
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
import org.apache.commons.lang.math.NumberUtils;
This will handle null
NumberUtils.createLong(String)
The easiest way I have found to do this is to just use require
and the path to your JSON file.
For example, suppose you have the following JSON file.
test.json
{
"firstName": "Joe",
"lastName": "Smith"
}
You can then easily load this in your node.js application using require
var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);
For kotlin, it's not possible for now but they've considered to add it: Source
But for now, just a little trick:
try {
// code
} catch(ex:Exception) {
when(ex) {
is SomeException,
is AnotherException -> {
// handle
}
else -> throw ex
}
}
Another option may be to have your fragment implement View.OnClickListener and override onClick(View v) within your fragment. If you need to have your fragment talk to the activity simply add an interface with desired method(s) and have the activity implement the interface and override its method(s).
public class FragName extends Fragment implements View.OnClickListener {
public FragmentCommunicator fComm;
public ImageButton res1, res2;
int c;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_test, container, false);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
fComm = (FragmentCommunicator) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement FragmentCommunicator");
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
res1 = (ImageButton) getActivity().findViewById(R.id.responseButton1);
res1.setOnClickListener(this);
res2 = (ImageButton) getActivity().findViewById(R.id.responseButton2);
res2.setOnClickListener(this);
}
public void onClick(final View v) { //check for what button is pressed
switch (v.getId()) {
case R.id.responseButton1:
c *= fComm.fragmentContactActivity(2);
break;
case R.id.responseButton2:
c *= fComm.fragmentContactActivity(4);
break;
default:
c *= fComm.fragmentContactActivity(100);
break;
}
public interface FragmentCommunicator{
public int fragmentContactActivity(int b);
}
public class MainActivity extends FragmentActivity implements FragName.FragmentCommunicator{
int a = 10;
//variable a is update by fragment. ex. use to change textview or whatever else you'd like.
public int fragmentContactActivity(int b) {
//update info on activity here
a += b;
return a;
}
}
http://developer.android.com/training/basics/firstapp/starting-activity.html http://developer.android.com/training/basics/fragments/communicating.html
Based on ni-ko-o-kin's answer:
meassurements = ["years", "months", "weeks", "days", "hours", "minutes", "seconds"];
withPadding = (duration) => {
var step = null;
return meassurements.map((m) => duration[m]()).filter((n,i,a) => {
var nonEmpty = Boolean(n);
if (nonEmpty || step || i >= a.length - 2) {
step = true;
}
return step;
}).map((n) => ('0' + n).slice(-2)).join(':')
}
duration1 = moment.duration(1, 'seconds');
duration2 = moment.duration(7200, 'seconds');
duration3 = moment.duration(604800, 'seconds');
withPadding(duration1); // 00:01
withPadding(duration2); // 02:00:00
withPadding(duration3); // 01:07:00:00:00
var lastname = "Hi";
if(typeof lastname !== "undefined")
{
alert("Hi. Variable is defined.");
}
Apache Tika offers in tika-core a mime type detection based based on magic markers in the stream prefix. tika-core
does not fetch other dependencies, which makes it as lightweight as the currently unmaintained Mime Type Detection Utility.
Simple code example (Java 7), using the variables theInputStream
and theFileName
try (InputStream is = theInputStream;
BufferedInputStream bis = new BufferedInputStream(is);) {
AutoDetectParser parser = new AutoDetectParser();
Detector detector = parser.getDetector();
Metadata md = new Metadata();
md.add(Metadata.RESOURCE_NAME_KEY, theFileName);
MediaType mediaType = detector.detect(bis, md);
return mediaType.toString();
}
Please note that MediaType.detect(...)
cannot be used directly (TIKA-1120). More hints are provided at https://tika.apache.org/1.24/detection.html.
Another option might be node-querystring.
It's available in both npm
and bower
, which is why I have been using it.
The simple answer is just to take the blob of it and set the img src to a new object URL of that blob, then add that image to a PDF using some library, like
var ok = document.createElement("canvas")
ok.width = 400
ok.height = 140
var ctx = ok.getContext("2d");
for(let k = 0; k < ok.height; k++)
(
k
%
Math.floor(
(
Math.random()
) *
10
)
==
0
) && (y => {
for(var i = 0; i < ok.width; i++) {
if(i % 25 == 0) {
ctx.globalAlpha = Math.random()
ctx.fillStyle = (
"rgb(" +
Math.random() * 255 + "," +
Math.random() * 255 + "," +
Math.random() * 255 + ")"
);
(wdth =>
ctx.fillRect(
Math.sin(
i * Math.PI / 180
) *
Math.random() *
ok.width,
Math.cos(
i * Math.PI / 180,
) * wdth + y,
wdth,
wdth
)
)(15)
}
}
})(k)
ok.toBlob(blob => {
k.src = URL.createObjectURL(blob)
})
_x000D_
<img id=k>
_x000D_
Alternatively, if you wanted to work with low-level byte data, you can get the raw bytes of the canvas, then, depending on the file spec, write the raw image data into the necessary bytes of the data. you just need to call ctx.getImageData(0, 0, ctx.canvas.widht, ctx.canvas.height)
to get the raw image data, then based on the file specification, write it to that
Hi you can use Renderer2 and elementRef with just a few lines of code:
constructor(private readonly elementRef: ElementRef,
private renderer: Renderer2) {
}
ngOnInit() {
const script = this.renderer.createElement('script');
script.src = 'http://iknow.com/this/does/not/work/either/file.js';
script.onload = () => {
console.log('script loaded');
initFile();
};
this.renderer.appendChild(this.elementRef.nativeElement, script);
}
the onload
function can be used to call the script functions after the script is loaded, this is very useful if you have to do the calls in the ngOnInit()
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
Since this post is ranking high in Google for "Create Directory Tree", I am going to post an answer that will work for Windows — this will work using Win32 API compiled for UNICODE or MBCS. This is ported from Mark's code above.
Since this is Windows we are working with, directory separators are BACK-slashes, not forward slashes. If you would rather have forward slashes, change '\\'
to '/'
It will work with:
c:\foo\bar\hello\world
and
c:\foo\bar\hellp\world\
(i.e.: does not need trailing slash, so you don't have to check for it.)
Before saying "Just use SHCreateDirectoryEx() in Windows", note that SHCreateDirectoryEx() is deprecated and could be removed at any time from future versions of Windows.
bool CreateDirectoryTree(LPCTSTR szPathTree, LPSECURITY_ATTRIBUTES lpSecurityAttributes = NULL){
bool bSuccess = false;
const BOOL bCD = CreateDirectory(szPathTree, lpSecurityAttributes);
DWORD dwLastError = 0;
if(!bCD){
dwLastError = GetLastError();
}else{
return true;
}
switch(dwLastError){
case ERROR_ALREADY_EXISTS:
bSuccess = true;
break;
case ERROR_PATH_NOT_FOUND:
{
TCHAR szPrev[MAX_PATH] = {0};
LPCTSTR szLast = _tcsrchr(szPathTree,'\\');
_tcsnccpy(szPrev,szPathTree,(int)(szLast-szPathTree));
if(CreateDirectoryTree(szPrev,lpSecurityAttributes)){
bSuccess = CreateDirectory(szPathTree,lpSecurityAttributes)!=0;
if(!bSuccess){
bSuccess = (GetLastError()==ERROR_ALREADY_EXISTS);
}
}else{
bSuccess = false;
}
}
break;
default:
bSuccess = false;
break;
}
return bSuccess;
}
This line
<h2>{{hero.name}} details!</h2>
is outside *ngFor
and there is no hero
therefore hero.name
fails.
Append the sheet name to the formula which makes the reference absolute. For example, if the cell reference is =T7 make it =Sheet1!T7. Paste-link would have done the same thing except only when pasting to another sheet. Paste-link does not work as expected if you are pasting in to the same sheet.
A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}
-block can throw (or a super class of that).
try {
//do something that throws ExceptionA, e.g.
throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
//do something to handle the exception, e.g.
System.out.println("Message: " + e.getMessage());
}
What you are trying to do is this:
try {
throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
System.out.println("Message: " + e.getMessage());
}
This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement
.
Yes.. It is possible using css
<a class="disable-me" href="page.html">page link</a>
.disable-me {
pointer-events: none;
}
You can also use your intuition.
The area of a circle is pi*r^2
For r=1
This give us an area of pi
. Let us assume that we have some kind of function f
that would uniformly distrubute N=10
points inside a circle. The ratio here is 10 / pi
Now we double the area and the number of points
For r=2
and N=20
This gives an area of 4pi
and the ratio is now 20/4pi
or 10/2pi
. The ratio will get smaller and smaller the bigger the radius is, because its growth is quadratic and the N
scales linearly.
To fix this we can just say
x = r^2
sqrt(x) = r
If you would generate a vector in polar coordinates like this
length = random_0_1();
angle = random_0_2pi();
More points would land around the center.
length = sqrt(random_0_1());
angle = random_0_2pi();
length
is not uniformly distributed anymore, but the vector will now be uniformly distributed.
You'll first need to separate your numpy array into two separate arrays containing x and y values.
x = [1, 2, 3, 9]
y = [1, 4, 1, 3]
curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like
def func(x, a, b):
return a*x + b
scipy.optimize.curve_fit(func, x, y)
will return a numpy array containing two arrays: the first will contain values for a
and b
that best fit your data, and the second will be the covariance of the optimal fit parameters.
Here's an example for a linear fit with the data you provided.
import numpy as np
from scipy.optimize import curve_fit
x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])
def fit_func(x, a, b):
return a*x + b
params = curve_fit(fit_func, x, y)
[a, b] = params[0]
This code will return a = 0.135483870968
and b = 1.74193548387
Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.
Kind of a mix:
Set it in your layout file :-
<CheckBox android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="new checkbox"
android:background="@drawable/checkbox_background"
android:button="@drawable/checkbox" />
where the @drawable/checkbox will look like:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/checkbox_on_background_focus_yellow" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/checkbox_off_background_focus_yellow" />
<item android:state_checked="false"
android:drawable="@drawable/checkbox_off_background" />
<item android:state_checked="true"
android:drawable="@drawable/checkbox_on_background" />
</selector>
@zdan. Good answer. I'd improve it like this...
I think that the closest you can come to a true return value in PowerShell is to use a local variable to pass the value and never to use return
as it may be 'corrupted' by any manner of output situations
function CheckRestart([REF]$retval)
{
# Some logic
$retval.Value = $true
}
[bool]$restart = $false
CheckRestart( [REF]$restart)
if ( $restart )
{
Restart-Computer -Force
}
The $restart
variable is used either side of the call to the function CheckRestart
making clear the scope of the variable. The return value can by convention be either the first or last parameter declared. I prefer last.
$subscription_key ='';
$host = '';
$request_headers = array(
"X-Mashape-Key:" . $subscription_key,
"X-Mashape-Host:" . $host
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
$season_data = curl_exec($ch);
if (curl_errno($ch)) {
print "Error: " . curl_error($ch);
exit();
}
// Show me the result
curl_close($ch);
$json= json_decode($season_data, true);
hr
{
background-color: #123455;
}
the background is the one you should try to change
You can also work with the borders color. i am not sure i think there are crossbrowser issues with this. you should test it in differrent browsers
You can use nircmd.exe's elevate command
NirCmd Command Reference - elevate
elevate [Program] {Command-Line Parameters}
For Windows Vista/7/2008 only: Run a program with administrator rights. When the [Program] contains one or more space characters, you must put it in quotes.
Examples:
elevate notepad.exe
elevate notepad.exe C:\Windows\System32\Drivers\etc\HOSTS
elevate "c:\program files\my software\abc.exe"
PS: I use it on win 10 and it works
JavaScript's dates can be compared using the same comparison operators the rest of the data types use: >, <, <=, >=, ==, !=, ===, !==.
If you have two dates A and B, then A < B if A is further back into the past than B.
But it sounds like what you're having trouble with is turning a string into a date. You do that by simply passing the string as an argument for a new Date:
var someDate = new Date("12/03/2008");
or, if the string you want is the value of a form field, as it seems it might be:
var someDate = new Date(document.form1.Textbox2.value);
Should that string not be something that JavaScript recognizes as a date, you will still get a Date object, but it will be "invalid". Any comparison with another date will return false. When converted to a string it will become "Invalid Date". Its getTime() function will return NaN, and calling isNaN() on the date itself will return true; that's the easy way to check if a string is a valid date.
Window -> Show View -> Other -> Studio/Remote
(Drag this tabbed window wherever)
Click the add FTP button (see below); #profit
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
What you are trying should work according to the MSDN doc's for .Net 2.0. You could also try a try/catch right in main around your entry point for the console app.
static void Main(string[] args)
{
try
{
// Start Working
}
catch (Exception ex)
{
// Output/Log Exception
}
finally
{
// Clean Up If Needed
}
}
And now your catch will handle anything not caught (in the main thread). It can be graceful and even restart where it was if you want, or you can just let the app die and log the exception. You woul add a finally if you wanted to do any clean up. Each thread will require its own high level exception handling similar to the main.
Edited to clarify the point about threads as pointed out by BlueMonkMN and shown in detail in his answer.
Use an ANSI-C quoted string $'string'
You need a backslash-escaped literal newline to get to sed.
In bash at least, $''
strings will replace \n
with a real newline, but then you have to double the backslash that sed will see to escape the newline, e.g.
echo "a,b" | sed -e $'s/,/\\\n/g'
Note this will not work on all shells, but will work on the most common ones.
#include <iostream>
using std::cout;
using std::endl;
enum TEnum
{
EOne,
ETwo,
EThree,
ELast
};
#define VAR_NAME_HELPER(name) #name
#define VAR_NAME(x) VAR_NAME_HELPER(x)
#define CHECK_STATE_STR(x) case(x):return VAR_NAME(x);
const char *State2Str(const TEnum state)
{
switch(state)
{
CHECK_STATE_STR(EOne);
CHECK_STATE_STR(ETwo);
CHECK_STATE_STR(EThree);
CHECK_STATE_STR(ELast);
default:
return "Invalid";
}
}
int main()
{
int myInt=12345;
cout << VAR_NAME(EOne) " " << VAR_NAME(myInt) << endl;
for(int i = -1; i < 5; i)
cout << i << " " << State2Str((TEnum)i) << endl;
return 0;
}
If there is a piece of code that you repeat all the time according to Don't Repeat Yourself you should put it in your own library and call that. With that in mind there are 2 aspects to getting the right answer here. The first is clarity and brevity in the code that calls the library function. The second is the performance implications of foreach.
First let's think about the clarity and brevity in the calling code.
You can do foreach in a number of ways:
Out of all the ways to do a foreach List.ForEach with a lamba is the clearest and briefest.
list.ForEach(i => Console.Write("{0}\t", i));
So at this stage it may look like the List.ForEach is the way to go. However what's the performance of this? It's true that in this case the time to write to the console will govern the performance of the code. When we know something about performance of a particular language feature we should certainly at least consider it.
According to Duston Campbell's performance measurements of foreach the fastest way of iterating the list under optimised code is using a for loop without a call to List.Count.
The for loop however is a verbose construct. It's also seen as a very iterative way of doing things which doesn't match with the current trend towards functional idioms.
So can we get brevity, clarity and performance? We can by using an extension method. In an ideal world we would create an extension method on Console that takes a list and writes it with a delimiter. We can't do this because Console is a static class and extension methods only work on instances of classes. Instead we need to put the extension method on the list itself (as per David B's suggestion):
public static void WriteLine(this List<int> theList)
{
foreach (int i in list)
{
Console.Write("{0}\t", t.ToString());
}
Console.WriteLine();
}
This code is going to used in many places so we should carry out the following improvements:
Here's how the code for the function would look:
public static void WriteToConsole<T>(this IList<T> collection)
{
int count = collection.Count();
for(int i = 0; i < count; ++i)
{
Console.Write("{0}\t", collection[i].ToString(), delimiter);
}
Console.WriteLine();
}
We can improve this even further by allowing the client to pass in the delimiter. We could then provide a second function that writes to console with the standard delimiter like this:
public static void WriteToConsole<T>(this IList<T> collection)
{
WriteToConsole<T>(collection, "\t");
}
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
int count = collection.Count();
for(int i = 0; i < count; ++i)
{
Console.Write("{0}{1}", collection[i].ToString(), delimiter);
}
Console.WriteLine();
}
So now, given that we want a brief, clear performant way of writing lists to the console we have one. Here is entire source code including a demonstration of using the the library function:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleWritelineTest
{
public static class Extensions
{
public static void WriteToConsole<T>(this IList<T> collection)
{
WriteToConsole<T>(collection, "\t");
}
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
int count = collection.Count();
for(int i = 0; i < count; ++i)
{
Console.Write("{0}{1}", collection[i].ToString(), delimiter);
}
Console.WriteLine();
}
}
internal class Foo
{
override public string ToString()
{
return "FooClass";
}
}
internal class Program
{
static void Main(string[] args)
{
var myIntList = new List<int> {1, 2, 3, 4, 5};
var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};
// Using the standard delimiter /t
myIntList.WriteToConsole();
myDoubleList.WriteToConsole();
myDoubleArray.WriteToConsole();
myFooList.WriteToConsole();
// Using our own delimiter ~
myIntList.WriteToConsole("~");
Console.Read();
}
}
}
=======================================================
You might think that this should be the end of the answer. However there is a further piece of generalisation that can be done. It's not clear from fatcat's question if he is always writing to the console. Perhaps something else is to be done in the foreach. In that case Jason Bunting's answer is going to give that generality. Here is his answer again:
list.ForEach(i => Console.Write("{0}\t", i));
That is unless we make one more refinement to our extension methods and add FastForEach as below:
public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
{
int count = collection.Count();
for (int i = 0; i < count; ++i)
{
actionToPerform(collection[i]);
}
Console.WriteLine();
}
This allows us to execute any arbitrary code against every element in the collection using the fastest possible iteration method.
We can even change the WriteToConsole function to use FastForEach
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
}
So now the entire source code, including an example usage of FastForEach is:
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleWritelineTest
{
public static class Extensions
{
public static void WriteToConsole<T>(this IList<T> collection)
{
WriteToConsole<T>(collection, "\t");
}
public static void WriteToConsole<T>(this IList<T> collection, string delimiter)
{
collection.FastForEach(item => Console.Write("{0}{1}", item.ToString(), delimiter));
}
public static void FastForEach<T>(this IList<T> collection, Action<T> actionToPerform)
{
int count = collection.Count();
for (int i = 0; i < count; ++i)
{
actionToPerform(collection[i]);
}
Console.WriteLine();
}
}
internal class Foo
{
override public string ToString()
{
return "FooClass";
}
}
internal class Program
{
static void Main(string[] args)
{
var myIntList = new List<int> {1, 2, 3, 4, 5};
var myDoubleList = new List<double> {1.1, 2.2, 3.3, 4.4};
var myDoubleArray = new Double[] {12.3, 12.4, 12.5, 12.6};
var myFooList = new List<Foo> {new Foo(), new Foo(), new Foo()};
// Using the standard delimiter /t
myIntList.WriteToConsole();
myDoubleList.WriteToConsole();
myDoubleArray.WriteToConsole();
myFooList.WriteToConsole();
// Using our own delimiter ~
myIntList.WriteToConsole("~");
// What if we want to write them to separate lines?
myIntList.FastForEach(item => Console.WriteLine(item.ToString()));
Console.Read();
}
}
}
Try passing width=200
as additional paramater when creating the Label.
This should work in creating label with specified width.
If you want to change it later, you can use:
label.config(width=200)
As you want to change the size of font itself you can try:
label.config(font=("Courier", 44))
You can use the /s
switch for del
to delete in subfolders as well.
Example
del D:\test\*.* /s
Would delete all files under test including all files in all subfolders.
To remove folders use rd
, same switch applies.
rd D:\test\folder /s /q
rd
doesn't support wildcards *
though so if you want to recursively delete all subfolders under the test
directory you can use a for
loop.
for /r /d D:\test %a in (*) do rd %a /s /q
If you are using the for
option in a batch file remember to use 2 %
's instead of 1.
Put the following to your .bashrc
shopt -s extglob
It extends regexes. You can then move all files except one by
mv !(fileOne) ~/path/newFolder
Note that, in copying directories, the forward-flash cannot be used in the name as noticed in the thread Why extglob except breaking except condition?:
cp -r !(Backups.backupdb) /home/masi/Documents/
so Backups.backupdb/
is wrong here before the negation and I would not use it neither in moving directories because of the risk of using wrongly then globs with other commands and possible other exceptions.
JE
and JZ
are just different names for exactly the same thing: a
conditional jump when ZF
(the "zero" flag) is equal to 1.
(Similarly, JNE
and JNZ
are just different names for a conditional jump
when ZF
is equal to 0.)
You could use them interchangeably, but you should use them depending on what you are doing:
JZ
/JNZ
are more appropriate when you are explicitly testing
for something being equal to zero:
dec ecx
jz counter_is_now_zero
JE
and JNE
are more appropriate after a CMP
instruction:
cmp edx, 42
je the_answer_is_42
(A CMP
instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1
when the operands are equal
and ZF=0
when they're not.)
Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.
You have to decide if:
If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc. In this case, formatting is dealt by the browser (and/or browser plugins)
If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:
If you give more details about your stack, it's easier to provide examples or resources.
EDIT: For client side JS highlighting you can try higlight.js, for instance.
one way;
var = count("find me", Range("A1:A100"))
function count(find as string, lookin as range) As Long
dim cell As Range
for each cell in lookin
if (cell.Value = find) then count = count + 1 '//case sens
next
end function
To my knowledge, there isn't a built-in then()
method in javascript
(at the time of this writing).
It appears that whatever it is that doSome("task")
is returning has a method called then
.
If you log the return result of doSome()
to the console, you should be able to see the properties of what was returned.
console.log( myObj.doSome("task") ); // Expand the returned object in the
// console to see its properties.
UPDATE (As of ECMAScript6) :-
The .then()
function has been included to pure javascript.
From the Mozilla documentation here,
The then() method returns a Promise. It takes two arguments: callback functions for the success and failure cases of the Promise.
The Promise object, in turn, is defined as
The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected in the future.
That is, the Promise
acts as a placeholder for a value that is not yet computed, but shall be resolved in the future. And the .then()
function is used to associate the functions to be invoked on the Promise when it is resolved - either as a success or a failure.
If it is a Windows DLL file and your OS is Linux then use winedump:
$ winedump -j export pcre.dll
Contents of pcre.dll: 229888 bytes
Exports table:
Name: pcre.dll
Characteristics: 00000000
TimeDateStamp: 53BBA519 Tue Jul 8 10:00:25 2014
Version: 0.00
Ordinal base: 1
# of functions: 31
# of Names: 31
Addresses of functions: 000375C8
Addresses of name ordinals: 000376C0
Addresses of names: 00037644
Entry Pt Ordn Name
0001FDA0 1 pcre_assign_jit_stack
000380B8 2 pcre_callout
00009030 3 pcre_compile
...
You should define source code encoding, add this to the top of your script:
# -*- coding: utf-8 -*-
The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:
import sys
print sys.getdefaultencoding()
Also see:
System.Diagnostics.Process.Start("http://www.example.com")
It is possible to code even the solution like this for example :
var loop = function(i, data, callback) {
if (i < data.length) {
//TODO("SELECT * FROM stackoverflowUsers;", function(res) {
//data[i].meta = res;
console.log(i, data[i].title);
return loop(i+1, data, errors, callback);
//});
} else {
return callback(data);
}
};
loop(0, [{"title": "hello"}, {"title": "world"}], function(data) {
console.log("DONE\n"+data);
});
On the other hand, it is much slower than a "for".
Otherwise, the excellent Async library can do this: https://caolan.github.io/async/docs.html#each
I'd consider using a nullable types.
DateTime? myDate
instead of DateTime myDate
.
You can use "track by" to increase the performance:
<div ng-repeat="a in arr track by a.trackingKey">
Faster than:
<div ng-repeat="a in arr">
ref:https://www.airpair.com/angularjs/posts/angularjs-performance-large-applications
I know this is an old topic, but I managed to do it in this simple way:
select count(*) from `tablename`
where date(`datecolumn`) = '2021-02-17';
June 2014:
This is the configuration I used and it working fine after banging my head on the wall for some days. I use Express 3.4 (I think is the same for Express 4.0)
var privateKey = fs.readFileSync('helpers/sslcert/key.pem', 'utf8');
var certificate = fs.readFileSync('helpers/sslcert/csr.pem', 'utf8');
files = ["COMODORSADomainValidationSecureServerCA.crt",
"COMODORSAAddTrustCA.crt",
"AddTrustExternalCARoot.crt"
];
ca = (function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
_results.push(fs.readFileSync("helpers/sslcert/" + file));
}
return _results;
})();
var credentials = {ca:ca, key: privateKey, cert: certificate};
// process.env.PORT : Heroku Config environment
var port = process.env.PORT || 4000;
var app = express();
var server = http.createServer(app).listen(port, function() {
console.log('Express HTTP server listening on port ' + server.address().port);
});
https.createServer(credentials, app).listen(3000, function() {
console.log('Express HTTPS server listening on port ' + server.address().port);
});
// redirect all http requests to https
app.use(function(req, res, next) {
if(!req.secure) {
return res.redirect(['https://mydomain.com', req.url].join(''));
}
next();
});
Then I redirected the 80 and 443 ports:
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 4000
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 3000
As you can see after checking my certifications I have 4 [0,1,2,3]:
openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "
ubuntu@ip-172-31-5-134:~$ openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify error:num=19:self signed certificate in certificate chain
verify return:0
0 s:/OU=Domain Control Validated/OU=PositiveSSL/CN=mydomain.com
i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
1 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
2 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
3 s:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
Protocol : TLSv1.1
Cipher : AES256-SHA
Session-ID: 8FDEAEE92ED20742.....3E7D80F93226142DD
Session-ID-ctx:
Master-Key: C9E4AB966E41A85EEB7....4D73C67088E1503C52A9353C8584E94
Key-Arg : None
PSK identity: None
PSK identity hint: None
SRP username: None
TLS session ticket lifetime hint: 300 (seconds)
TLS session ticket:
0000 - 7c c8 36 80 95 4d 4c 47-d8 e3 ca 2e 70 a5 8f ac |.6..MLG....p...
0010 - 90 bd 4a 26 ef f7 d6 bc-4a b3 dd 8f f6 13 53 e9 ..J&..........S.
0020 - f7 49 c6 48 44 26 8d ab-a8 72 29 c8 15 73 f5 79 .I.HD&.......s.y
0030 - ca 79 6a ed f6 b1 7f 8a-d2 68 0a 52 03 c5 84 32 .yj........R...2
0040 - be c5 c8 12 d8 f4 36 fa-28 4f 0e 00 eb d1 04 ce ........(.......
0050 - a7 2b d2 73 df a1 8b 83-23 a6 f7 ef 6e 9e c4 4c .+.s...........L
0060 - 50 22 60 e8 93 cc d8 ee-42 22 56 a7 10 7b db 1e P"`.....B.V..{..
0070 - 0a ad 4a 91 a4 68 7a b0-9e 34 01 ec b8 7b b2 2f ..J......4...{./
0080 - e8 33 f5 a9 48 11 36 f8-69 a6 7a a6 22 52 b1 da .3..H...i....R..
0090 - 51 18 ed c4 d9 3d c4 cc-5b d7 ff 92 4e 91 02 9e .....=......N...
Start Time: 140...549
Timeout : 300 (sec)
Verify return code: 19 (self signed certificate in certificate chain)
Good luck! PD: if u want more answers please check: http://www.benjiegillam.com/2012/06/node-dot-js-ssl-certificate-chain/
It's actually pretty easy. (If you're using Angular 2+ anyway.)
Simply add
declare var myGlobalVarName;
Somewhere in the top of your component file (such as after the "import" statements), and you'll be able to access "myGlobalVarName" anywhere inside your component.
how about
var top = $('html').scrollTop() || $('body').scrollTop();
Do you have a bean declared in your context file that has an id of "articleService"? I believe that autowiring matches the id of a bean in your context files with the variable name that you are attempting to Autowire.
//the parsed time zone offset:
DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String fromDateTimeObj = "2011-01-03T12:00:00.000-0800";
DateTime fromDatetime = dateFormat.withOffsetParsed().parseDateTime(fromDateTimeObj);
It's simple while cloning please take the git URL with your username.While committing it will ask your new user password.
Eg:
I modified the script by Nicolay77 to output the database to stdout (the usual way of unix scripts) so that I could output the data to text file or pipe it to any program I want. The resulting script is a bit simpler and works well.
Some examples:
./mdb_to_mysql.sh database.mdb > data.sql
./mdb_to_mysql.sh database.mdb | mysql destination-db -u user -p
Here is the modified script (save to mdb_to_mysql.sh)
#!/bin/bash
TABLES=$(mdb-tables -1 $1)
for t in $TABLES
do
echo "DROP TABLE IF EXISTS $t;"
done
mdb-schema $1 mysql
for t in $TABLES
do
mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t
done
Depending on your needs, like if you want to allow the data to eventually expire or set limitations on how many records to store, you could also look at https://github.com/jmdobry/angular-cache which allows you to define if the cache sits in memory, localStorage, or sessionStorage.
You can put your servers in the default_step
group and those vars will apply to it:
# inventory file
[default_step]
prod2
web_v2
Then just move your default_step.yml
file to group_vars/default_step.yml
.
Given a data setup like this:
The formula in cell D2 and copied down is:
=INDEX($B$2:$B$28,MATCH(1,INDEX(($A$2:$A$28=LARGE($A$2:$A$28,ROWS(D$1:D1)))*(COUNTIF(D$1:D1,$B$2:$B$28)=0),),0))
This formula will work even if there are tied OPS scores among players.
since your form has a field called 'q', leaving it blank still sends an empty string.
try
if 'q' in request.GET and request.GET['q'] != "" :
message
else
error message
If you work in Eclipse, just make a cleanup (project\clean..
clean all projects
) of the project.
You can use ORDER BY
clause to sort data rows by values in columns. Something like
=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C, D")
If you’d like to order by some columns descending, others ascending, you can add desc
/asc
, ie:
=QUERY(responses!A1:K; "Select C, D, E where B contains '2nd Web Design' Order By C desc, D")
Yes, this is a common aggregation problem. Before SQL3 (1999), the selected fields must appear in the GROUP BY
clause[*].
To workaround this issue, you must calculate the aggregate in a sub-query and then join it with itself to get the additional columns you'd need to show:
SELECT m.cname, m.wmname, t.mx
FROM (
SELECT cname, MAX(avg) AS mx
FROM makerar
GROUP BY cname
) t JOIN makerar m ON m.cname = t.cname AND t.mx = m.avg
;
cname | wmname | mx
--------+--------+------------------------
canada | zoro | 2.0000000000000000
spain | usopp | 5.0000000000000000
But you may also use window functions, which looks simpler:
SELECT cname, wmname, MAX(avg) OVER (PARTITION BY cname) AS mx
FROM makerar
;
The only thing with this method is that it will show all records (window functions do not group). But it will show the correct (i.e. maxed at cname
level) MAX
for the country in each row, so it's up to you:
cname | wmname | mx
--------+--------+------------------------
canada | zoro | 2.0000000000000000
spain | luffy | 5.0000000000000000
spain | usopp | 5.0000000000000000
The solution, arguably less elegant, to show the only (cname, wmname)
tuples matching the max value, is:
SELECT DISTINCT /* distinct here matters, because maybe there are various tuples for the same max value */
m.cname, m.wmname, t.avg AS mx
FROM (
SELECT cname, wmname, avg, ROW_NUMBER() OVER (PARTITION BY avg DESC) AS rn
FROM makerar
) t JOIN makerar m ON m.cname = t.cname AND m.wmname = t.wmname AND t.rn = 1
;
cname | wmname | mx
--------+--------+------------------------
canada | zoro | 2.0000000000000000
spain | usopp | 5.0000000000000000
[*]: Interestingly enough, even though the spec sort of allows to select non-grouped fields, major engines seem to not really like it. Oracle and SQLServer just don't allow this at all. Mysql used to allow it by default, but now since 5.7 the administrator needs to enable this option (ONLY_FULL_GROUP_BY
) manually in the server configuration for this feature to be supported...
/stop([a-zA-Z])+/
Will match any stop word (stop, stopped, stopping, etc)
However, if you just want to match "stop" at the start of a string
/^stop/
will do :D
The newest, most recent, up to date answer
This post is really old (it's 7 years old when I answered it), so no one of the other answers used the new and recommended way, which is HttpClient
class.
HttpClient
is considered the new API and it should replace the old ones (WebClient
and WebRequest
)
string url = "page url";
HttpClient client = new HttpClient();
using (HttpResponseMessage response = client.GetAsync(url).Result)
{
using (HttpContent content = response.Content)
{
string result = content.ReadAsStringAsync().Result;
}
}
for more information about how to use the HttpClient
class (especially in async cases), you can refer this question
NOTE 1: If you want to use async/await
string url = "page url";
HttpClient client = new HttpClient(); // actually only one object should be created by Application
using (HttpResponseMessage response = await client.GetAsync(url))
{
using (HttpContent content = response.Content)
{
string result = await content.ReadAsStringAsync();
}
}
NOTE 2: If use C# 8 features
string url = "page url";
HttpClient client = new HttpClient();
using HttpResponseMessage response = await client.GetAsync(url);
using HttpContent content = response.Content;
string result = await content.ReadAsStringAsync();
In addition to the above answers, it could be due to a missing SQL stored-procedure or SQL function. For example, this could be due to the function not migrating from a non-prod region to the production (prod) region.
You are looking for the jQuery extend method. This will allow you to add other members to your already created JS object.
Try to add auth method explicitly as below, because sometimes it is required:
session.setConfig("PreferredAuthentications", "password");
For whatever reason, for me, the tmp file created by git diff was being deleted before it opened in beyond compare. I had to copy it out to another location first.
cp -r $2 "/cygdrive/c/temp$2"
cygstart /cygdrive/c/Program\ Files\ \(x86\)/Beyond\ Compare\ 3/BCompare.exe "C:/temp$2" "$5"
I would like to add that in my case (My OS is Linux Mint and using IntelliJ IDEA). My compiler complaining about these annotations I was using: @Data @RequiredArgsConstructor, even though I had installed and activated the Lombok plugin.Install Lombok in IntelliJ Idea. I am using Maven. So I had to add this dependency in my configuration file (pom.xml file):
dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
On OS X you can use:
ls -lead
The e option shows ACLs. And ACLs are very important to knowing what the exact permissions on your system are.
eval
is not an acceptable practice if your directory names can be generated by untrusted sources. See BashFAQ #48 for more on why eval
should not be used, and BashFAQ #50 for more on the root cause of this problem and its proper solutions, some of which are touched on below:
If you need to build up your commands over time, use arrays:
tar_cmd=( tar cv "$directory" )
split_cmd=( split -b 1024m - "$backup_file" )
encrypt_cmd=( openssl des3 -salt )
"${tar_cmd[@]}" | "${encrypt_cmd[@]}" | "${split_cmd[@]}"
Alternately, if this is just about defining your commands in one central place, use functions:
tar_cmd() { tar cv "$directory"; }
split_cmd() { split -b 1024m - "$backup_file"; }
encrypt_cmd() { openssl des3 -salt; }
tar_cmd | split_cmd | encrypt_cmd
If you use Sass, there are Bootstrap variables are defined with !default
, among which you'll find font families. You can just set the variables in your own .scss
file before including the Bootstrap Sass file and !default
will not overwrite yours. Here's a good explanation of how !default
works: https://thoughtbot.com/blog/sass-default.
Here's an untested example using Bootstrap 4, npm, Gulp, gulp-sass and gulp-cssmin to give you an idea how you could hook this up together.
package.json
{
"devDependencies": {
"bootstrap": "4.0.0-alpha.6",
"gulp": "3.9.1",
"gulp-sass": "3.1.0",
"gulp-cssmin": "0.2.0"
}
}
mysite.scss
@import "./myvariables";
// Bootstrap
@import "bootstrap/scss/variables";
// ... need to include other bootstrap files here. Check node_modules\bootstrap\scss\bootstrap.scss for a list
_myvariables.scss
// For a list of Bootstrap variables you can override, look at node_modules\bootstrap\scss\_variables.scss
// These are the defaults, but you can override any values
$font-family-sans-serif: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !default;
$font-family-serif: Georgia, "Times New Roman", Times, serif !default;
$font-family-monospace: Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !default;
$font-family-base: $font-family-sans-serif !default;
gulpfile.js
var gulp = require("gulp"),
sass = require("gulp-sass"),
cssmin = require("gulp-cssmin");
gulp.task("transpile:sass", function() {
return gulp.src("./mysite.scss")
.pipe(sass({ includePaths: "./node_modules" }).on("error", sass.logError))
.pipe(cssmin())
.pipe(gulp.dest("./css/"));
});
index.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="mysite.css" />
</head>
<body>
...
</body>
</html>
Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.
[Gray] introduced the ACD properties for a transaction in 1981. In 1983 [Haerder] added the Isolation property. In my opinion, the ACD properties would be have a more useful set of properties to discuss. One interpretation of Atomicity (that the transaction should be atomic as seen from any client any time) would actually imply the isolation property. The "isolation" property is useful when the transaction is not isolated; when the isolation property is relaxed. In ANSI SQL speak: if the isolation level is weaker then SERIALIZABLE. But when the isolation level is SERIALIZABLE, the isolation property is not really of interest.
I have written more about this in a blog post: "ACID Does Not Make Sense".
http://blog.franslundberg.com/2013/12/acid-does-not-make-sense.html
[Gray] The Transaction Concept, Jim Gray, 1981. http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
[Haerder] Principles of Transaction-Oriented Database Recovery, Haerder and Reuter, 1983. http://www.stanford.edu/class/cs340v/papers/recovery.pdf
All you need to do is to put arp into diferrent group.
Default:
-rwxr-xr-x 1 root root 48K 2008-11-11 18:11 /usr/sbin/arp*
With command:
sudo chown root:www-data /usr/sbin/arp
you will get:
-rwxr-xr-x 1 root www-data 48K 2008-11-11 18:11 /usr/sbin/arp*
And because apache is a daemon running under the user www-data, it's now able to execute this command.
So if you now use a PHP script, e.g.:
<?php
$mac = system('arp -an');
echo $mac;
?>
you will get the output of linux arp -an
command.
This is actually pretty easy in Excel (or any spreadsheet application).
You'll want to use the =CONCATENATE()
function as shown in the formula bar in the following screenshot:
Step 1 involves adding quotes in column B,
Step 2 involves specifying the function and then copying it down column C (by now your spreadsheet should look like the screenshot),
Step 3 (if you need the text outside of the formula) involves copying column C, right-clicking on column D, choosing Paste Special >> Paste Values. Column D should then contain the text that was calculated in column C.
I have found a useful article that also explains the topic quite clearly and easy language. Link is JSONP
Some of the worth noting points are:
Working is as follows:
<script src="url?callback=function_name">
is included in the html codeYou can view the filesystem of the container at
/var/lib/docker/devicemapper/mnt/$CONTAINER_ID/rootfs/
and you can just
tail -f mylogfile.log
The problem is that your ui
property uses a forward declaration of class Ui::MainWindowClass
, hence the "incomplete type" error.
Including the header file in which this class is declared will fix the problem.
EDIT
Based on your comment, the following code:
namespace Ui
{
class MainWindowClass;
}
does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.
But the class has to be defined somewhere.
Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.
So either you actually want an incomplete type, and then you should declare your ui
member as a pointer:
namespace Ui
{
// Forward declaration - Class will have to exist at link time
class MainWindowClass;
}
class MainWindow : public QMainWindow
{
private:
// Member needs to be a pointer, as it's an incomplete type
Ui::MainWindowClass * ui;
};
Or you want a statically allocated instance of Ui::MainWindowClass
, and then it needs to be declared.
You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:
namespace Ui
{
// Real class declaration - May/Should be in a specific header file
class MainWindowClass
{};
}
class MainWindow : public QMainWindow
{
private:
// Member can be statically allocated, as the type is complete
Ui::MainWindowClass ui;
};
will also work.
Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).
string uriPath =
"file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
string localPath = new Uri(uriPath).LocalPath;
A much simpler yet generalised way just like apple does by takes keypads's height into consideration which is greatly helpful when we are using custom toolbar on top of keyboard. though apple's approach here has got few issues.
Here is my approach (Slightly modified apple's way) -
// UIKeyboardDidShowNotification
- (void)keyboardWasShown:(NSNotification*)aNotification
{
NSDictionary* info = [aNotification userInfo];
CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0);
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
// UIKeyboardWillHideNotification
- (void)keyboardWillBeHidden:(NSNotification*)aNotification
{
UIEdgeInsets contentInsets = UIEdgeInsetsZero;
self.scrollView.contentInset = contentInsets;
self.scrollView.scrollIndicatorInsets = contentInsets;
}
require 'json'
out=JSON.parse(input)
This will return a Hash
Google updated play store two months before. This is the solution working right now for me..
class GetVersionCode extends AsyncTask<Void, String, String> {
@Override
protected String doInBackground(Void... voids) {
String newVersion = null;
try {
Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get();
if (document != null) {
Elements element = document.getElementsContainingOwnText("Current Version");
for (Element ele : element) {
if (ele.siblingElements() != null) {
Elements sibElemets = ele.siblingElements();
for (Element sibElemet : sibElemets) {
newVersion = sibElemet.text();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return newVersion;
}
@Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
if (onlineVersion != null && !onlineVersion.isEmpty()) {
if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
//show anything
}
}
Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);
}
}
and don't forget to add JSoup library
dependencies {
compile 'org.jsoup:jsoup:1.8.3'}
and on Oncreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String currentVersion;
try {
currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
new GetVersionCode().execute();
}
that's it.. Thanks to this link
Using Linq you have many possibilities, here one without using lambdas:
//assuming list is a List<Customer> or something queryable...
var hasJohn = (from customer in list
where customer.FirstName == "John"
select customer).Any();