static void InsertSettings(IEnumerable<Entry> settings) {
using (SqlConnection oConnection = new SqlConnection("Data Source=(local);Initial Catalog=Wip;Integrated Security=True")) {
oConnection.Open();
using (SqlTransaction oTransaction = oConnection.BeginTransaction()) {
using (SqlCommand oCommand = oConnection.CreateCommand()) {
oCommand.Transaction = oTransaction;
oCommand.CommandType = CommandType.Text;
oCommand.CommandText = "INSERT INTO [Setting] ([Key], [Value]) VALUES (@key, @value);";
oCommand.Parameters.Add(new SqlParameter("@key", SqlDbType.NChar));
oCommand.Parameters.Add(new SqlParameter("@value", SqlDbType.NChar));
try {
foreach (var oSetting in settings) {
oCommand.Parameters[0].Value = oSetting.Key;
oCommand.Parameters[1].Value = oSetting.Value;
if (oCommand.ExecuteNonQuery() != 1) {
//'handled as needed,
//' but this snippet will throw an exception to force a rollback
throw new InvalidProgramException();
}
}
oTransaction.Commit();
} catch (Exception) {
oTransaction.Rollback();
throw;
}
}
}
}
}
I used back.png image in the project menifest.xml file. it is fine working in project.
<activity
android:name=".YourActivity"
android:icon="@drawable/back"
android:label="@string/app_name" >
</activity>
You can try this. This will store last item. Here need to convert obj into array. Then use array pop()
function that will return last item from converted array.
var obj = { 'a' : 'apple', 'b' : 'banana', 'c' : 'carrot' };_x000D_
var last = Object.keys(obj).pop();_x000D_
console.log(last);_x000D_
console.log(obj[last]);
_x000D_
Here is an approach where Inkscape is called by Python.
Note that it suppresses certain crufty output that Inkscape writes to the console (specifically, stderr and stdout) during normal error-free operation. The output is captured in two string variables, out
and err
.
import subprocess # May want to use subprocess32 instead
cmd_list = [ '/full/path/to/inkscape', '-z',
'--export-png', '/path/to/output.png',
'--export-width', 100,
'--export-height', 100,
'/path/to/input.svg' ]
# Invoke the command. Divert output that normally goes to stdout or stderr.
p = subprocess.Popen( cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE )
# Below, < out > and < err > are strings or < None >, derived from stdout and stderr.
out, err = p.communicate() # Waits for process to terminate
# Maybe do something with stdout output that is in < out >
# Maybe do something with stderr output that is in < err >
if p.returncode:
raise Exception( 'Inkscape error: ' + (err or '?') )
For example, when running a particular job on my Mac OS system, out
ended up being:
Background RRGGBBAA: ffffff00
Area 0:0:339:339 exported to 100 x 100 pixels (72.4584 dpi)
Bitmap saved as: /path/to/output.png
(The input svg file had a size of 339 by 339 pixels.)
If you are here to copy-paste code:
This is an example which removes node_modules
from history
git filter-branch --tree-filter "rm -rf node_modules" --prune-empty HEAD
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d
echo node_modules/ >> .gitignore
git add .gitignore
git commit -m 'Removing node_modules from git history'
git gc
git push origin master --force
What git actually does:
The first line iterates through all references on the same tree (--tree-filter
) as HEAD (your current branch), running the command rm -rf node_modules
. This command deletes the node_modules folder (-r
, without -r
, rm
won't delete folders), with no prompt given to the user (-f
). The added --prune-empty
deletes useless (not changing anything) commits recursively.
The second line deletes the reference to that old branch.
The rest of the commands are relatively straightforward.
I start versioning at the lowest (non hotfix) segement. I do not limit this segment to 10. Unless you are tracking builds then you just need to decide when you want to apply an increment. If you have a QA phase then that might be where you apply an increment to the lowest segment and then the next segement up when it passes QA and is released. Leave the topmost segment for Major behavior/UI changes.
If you are like me you will make it a hybrid of the methods so as to match the pace of your software's progression.
I think the most accepted pattern a.b.c. or a.b.c.d especially if you have QA/Compliance in the mix. I have had so much flack around date being a regular part of versions that I gave it up for mainstream.
I do not track builds so I like to use the a.b.c pattern unless a hotfix is involved. When I have to apply a hotfix then I apply parameter d as a date with time. I adopted the time parameter as d because there is always the potential of several in a day when things really blow up in production. I only apply the d segment (YYYYMMDDHHNN) when I'm diverging for a production fix.
I personally wouldn't be opposed to a software scheme of va.b revc where c is YYYYMMDDHHMM or YYYYMMDD.
All that said. If you can just snag a tool to configure and run with it will keep you from the headache having to marshall the opinion facet of versioning and you can just say "use the tool"... because everyone in the development process is typically so compliant.
Use
myString = myString.replace( /\&/g, '&' );
It is easiest to do it on the server side because apparently JavaScript has no native library for handling entities, nor did I find any near the top of search results for the various frameworks that extend JavaScript.
Search for "JavaScript HTML entities", and you might find a few libraries for just that purpose, but they'll probably all be built around the above logic - replace, entity by entity.
class Person:
def init(self,name,age,weight,sex,mob_no,place):
self.name = str(name)
self.age = int(age)
self.weight = int(weight)
self.sex = str(sex)
self.mob_no = int(mob_no)
self.place = str(place)
p1 = Person(Muthuswamy,50,70,Male,94*****23,India)
print(p1.name)
print(p1.place)
Muthuswamy
India
in your code, at line
map.setCenter(new GLatLng(lat, lon), 5);
the setCenter method takes just one parameter, for the lat:long location. Why are you passing two parameters there ?
I suggest you should change it to,
map.setCenter(new GLatLng(lat, lon));
use like this your inline css
<td width="178" rowspan="3" valign="top"
align="right" background="images/left.jpg"
style="background-repeat:background-position: right top;">
</td>
Math.round(number*100.0)/100.0;
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
If you want to center map onto a marker and you have the cordinate, something like click on a list item and the map should center on that coordinate then the following code will work:
In HTML:
<ul class="locationList" ng-repeat="LocationDetail in coordinateArray| orderBy:'LocationName'">
<li>
<div ng-click="focusMarker(LocationDetail)">
<strong><div ng-bind="locationDetail.LocationName"></div></strong>
<div ng-bind="locationDetail.AddressLine"></div>
<div ng-bind="locationDetail.State"></div>
<div ng-bind="locationDetail.City"></div>
<div>
</li>
</ul>
In Controller:
$scope.focusMarker = function (coords) {
map.setCenter(new google.maps.LatLng(coords.Latitude, coords.Longitude));
map.setZoom(14);
}
Location Object:
{
"Name": "Taj Mahal",
"AddressLine": "Tajganj",
"City": "Agra",
"State": "Uttar Pradesh",
"PhoneNumber": "1234 12344",
"Latitude": "27.173891",
"Longitude": "78.042068"
}
Make sure you are following the Same Origin Policy. This means same domain, same subdomain, same protocol (http vs https) and same port.
How does pushState protect against potential content forgeries?
EDIT: As @robertc aptly pointed out in his comment, some browsers actually implement slightly different security policies when the origin is file:///
. Not to mention you can encounter problems when testing locally with file:///
when the page expects it is running from a different origin (and so your pushState
assumes production origin scenarios, not localhost scenarios)
In Intent, you can directly put Uri. You don't need to convert the Uri to string and convert back again to Uri.
Look at this simple approach.
// put uri to intent
intent.setData(imageUri);
And to get Uri back from intent:
// Get Uri from Intent
Uri imageUri=getIntent().getData();
The problem is what happens when you get NumberFormatexception
thrown? You print it and return nothing.
Note: You don't need to catch and throw an Exception back. Usually it is done to wrap it or print stack trace and ignore for example.
catch(RangeException e) {
throw e;
}
All the posted answers rightfully discuss this from a strictly maven perspective. My issues was in doing this install for maven using Netbeans as my primary IDE. I found the below article helpful.
Credit to the following netbeans forum article: http://forums.netbeans.org/topic22907.html
In standard SQL syntax, you would use:
WHERE mydate <= DATE '2008-11-20'
That is, the keyword DATE should precede the string. In some DBMS, however, you don't need to be that explicit; the system will convert the DATE column into a string, or the string into a DATE value, automatically. There are nominally some interesting implications if the DATE is converted into a string - if you happen to have dates in the first millennium (0001-01-01 .. 0999-12-31) and the leading zero(es) are omitted by the formatting system.
In my case this very same error was caused by the way I was importing my custom component from the caller class i.e. I was doing
import {MyComponent} from './components/MyComponent'
instead of
import MyComponent from './components/MyComponent'
using the latter solved the issue.
I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?
You should be able to create a custom exception class that extends the Exception
class, for example:
class WordContainsException extends Exception
{
// Parameterless Constructor
public WordContainsException() {}
// Constructor that accepts a message
public WordContainsException(String message)
{
super(message);
}
}
Usage:
try
{
if(word.contains(" "))
{
throw new WordContainsException();
}
}
catch(WordContainsException ex)
{
// Process message however you would like
}
type in Windows cmd.exe
cd %userprofile%\.android
dir
copy adbkey.pub adb_keys
dir
copy the file adb_keys to your phone folder /data/misc/adb. Reboot the phone. RSA Key is now authorized.
from: How to solve ADB device unauthorized in Android ADB host device?
now follow the instructions for adb connect, or use any app for preparing. i prefer ADB over WIFI Widget from Mehdy Bohlool, it works without root.
When using the for loop, the value of s is a Map.Entry element, meaning that you can get the key from s.key and the value from s.value
If you're testing/debugging a bash script, and simply want to skip forwards past one or more sections of code, here is a very simple way to do it that is also very easy to find and remove later (unlike most of the methods described above).
#!/bin/bash
echo "Run this"
cat >/dev/null <<GOTO_1
echo "Don't run this"
GOTO_1
echo "Also run this"
cat >/dev/null <<GOTO_2
echo "Don't run this either"
GOTO_2
echo "Yet more code I want to run"
To put your script back to normal, just delete any lines with GOTO
.
We can also prettify this solution, by adding a goto
command as an alias:
#!/bin/bash
shopt -s expand_aliases
alias goto="cat >/dev/null <<"
goto GOTO_1
echo "Don't run this"
GOTO_1
echo "Run this"
goto GOTO_2
echo "Don't run this either"
GOTO_2
echo "All done"
Aliases don't usually work in bash scripts, so we need the shopt
command to fix that.
If you want to be able to enable/disable your goto
's, we need a little bit more:
#!/bin/bash
shopt -s expand_aliases
if [ -n "$DEBUG" ] ; then
alias goto="cat >/dev/null <<"
else
alias goto=":"
fi
goto '#GOTO_1'
echo "Don't run this"
#GOTO1
echo "Run this"
goto '#GOTO_2'
echo "Don't run this either"
#GOTO_2
echo "All done"
Then you can do export DEBUG=TRUE
before running the script.
The labels are comments, so won't cause syntax errors if disable our goto
's (by setting goto
to the ':
' no-op), but this means we need to quote them in our goto
statements.
Whenever using any kind of goto
solution, you need to be careful that the code you're jumping past doesn't set any variables that you rely on later - you may need to move those definitions to the top of your script, or just above one of your goto
statements.
@Swapnil Godambe It works for me if JSON.stringfy is removed. That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
I didn't find it easy to understand what is required even after reading all the answers until I executed this. TensofFlow is new to me too.
def printtest():
x = tf.constant([1.0, 3.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
sess.run(init)
print(sess.run(b))
sess.close()
But still you may need the value returned by executing the session.
def printtest():
x = tf.constant([100.0])
x = tf.Print(x,[x],message="Test")
init = (tf.global_variables_initializer(), tf.local_variables_initializer())
b = tf.add(x, x)
with tf.Session() as sess:
sess.run(init)
c = sess.run(b)
print(c)
sess.close()
It the case of HashSet, it does NOT replace it.
From the docs:
http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add(E)
"Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false."
There are multiple Gzip middlewares for Express, KOA and others. For example: https://www.npmjs.com/package/express-static-gzip
However, Node is awfully bad at doing CPU intensive tasks like gzipping, SSL termination, etc. Instead, use a ‘real’ middleware services like nginx or HAproxy, see bullet 3 here: http://goldbergyoni.com/checklist-best-practice-of-node-js-in-production/
You have to change
loadNavItems() {
this.navItems = this.http.get("../data/navItems.json");
console.log(this.navItems);
}
for
loadNavItems() {
this.navItems = this.http.get("../data/navItems.json")
.map(res => res.json())
.do(data => console.log(data));
//This is optional, you can remove the last line
// if you don't want to log loaded json in
// console.
}
Because this.http.get
returns an Observable<Response>
and you don't want the response, you want its content.
The console.log
shows you an observable, which is correct because navItems contains an Observable<Response>
.
In order to get data properly in your template, you should use async
pipe.
<app-nav-item-comp *ngFor="let item of navItems | async" [item]="item"></app-nav-item-comp>
This should work well, for more informations, please refer to HTTP Client documentation
If you wish to use canvas only, the best result will be with multiple downsteps. But that's not good enougth yet. For better quality you need pure js implementation. We just released pica - high speed downscaler with variable quality/speed. In short, it resizes 1280*1024px in ~0.1s, and 5000*3000px image in 1s, with highest quality (lanczos filter with 3 lobes). Pica has demo, where you can play with your images, quality levels, and even try it on mobile devices.
Pica does not have unsharp mask yet, but that will be added very soon. That's much more easy than implement high speed convolution filter for resize.
The absolute simplest way to accomplish this, is with basename()
echo basename('http://domain.com/artist/song/music-videos/song-title/9393903');
Which will print
9393903
Of course, if there is a query string at the end it will be included in the returned value, in which case the accepted answer is a better solution.
To use getSingleResult on a TypedQuery you can use
query.setFirstResult(0);
query.setMaxResults(1);
result = query.getSingleResult();
Typically, a script is a lightweight, quickly constructed, possibly single-use tool. It's usually interpreted, not compiled. Python and bash are examples of languages used to build scripts.
A program is constructed in a compiled language, like C or C++, and usually runs more quickly than a script for that reason. Larger tools are often written as "programs" rather than scripts - smaller tools are more easily developed as scripts, but scripts can get unwieldy as they get larger. Application and system languages (those used to build programs/applications) have tools to make that growth easier to manage.
You can usually view a script in a text editor to see what it does. You can't do that with an executable program - the latter's instructions have been compiled into bytecode or machine language that makes it very difficult for humans to understand, without specialized tools.
Note the number of "oftens" and "usuallys" above - the terms are nebulous, and cross over sometimes.
Since I don't have a high enough reputation to comment I'll answer liang question on Feb 20 at 10:01 as an answer to the original question.
In order for the for the line labels to show you need to add plt.legend to your code. to build on the previous example above that also includes title, ylabel and xlabel:
import matplotlib.pyplot as plt
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.plot(<X AXIS VALUES HERE>, <Y AXIS VALUES HERE>, 'line type', label='label here')
plt.title('title')
plt.ylabel('ylabel')
plt.xlabel('xlabel')
plt.legend()
plt.show()
You'll need to find the URI of the message. But once you do I think you should be able to android.content.ContentResolver.delete(...) it.
Here's some more info.
A list comprehension is likely the cleanest way:
>>> L = [0, 23, 234, 89, None, 0, 35, 9
>>> [x for x in L if x is not None]
[0, 23, 234, 89, 0, 35, 9]
There is also a functional programming approach but it is more involved:
>>> from operator import is_not
>>> from functools import partial
>>> L = [0, 23, 234, 89, None, 0, 35, 9]
>>> list(filter(partial(is_not, None), L))
[0, 23, 234, 89, 0, 35, 9]
This link should get you started. Long story short, a div that has been styled to look like a scrollbar is used to catch click-and-drag events. Wired up to these events are methods that scroll the contents of another div which is set to an arbitrary height and typically has a css rule of overflow:scroll (there are variants on the css rules but you get the idea).
I'm all about the learning experience -- but after you've learned how it works, I recommend using a library (of which there are many) to do it. It's one of those "don't reinvent" things...
This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery
SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )
You need to make TestGetMethod async
too and attach await in front of GetIdList();
will unwrap the task to List<int>
, So if your helper function is returning Task make sure you have await as you are calling the function async
too.
public Task<List<int>> TestGetMethod()
{
return GetIdList();
}
async Task<List<int>> GetIdList()
{
using (HttpClient proxy = new HttpClient())
{
string response = await proxy.GetStringAsync("www.test.com");
List<int> idList = JsonConvert.DeserializeObject<List<int>>();
return idList;
}
}
Another option
public async void TestGetMethod(List<int> results)
{
results = await GetIdList(); // await will unwrap the List<int>
}
You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...
<input type="text" id="@strElementID" class="@strCSSClass" />
If strCSSClass is null then the class attribute won't render at all.
SSSHHH...don't tell. :)
Use: "%.2f"
or variations on that.
See the POSIX spec for an authoritative specification of the printf()
format strings. Note that it separates POSIX extras from the core C99 specification. There are some C++ sites which show up in a Google search, but some at least have a dubious reputation, judging from comments seen elsewhere on SO.
Since you're coding in C++, you should probably be avoiding printf()
and its relatives.
awk '{ sum += $2; n++ } END { if (n > 0) print sum / n; }'
Add the numbers in $2
(second column) in sum
(variables are auto-initialized to zero by awk
) and increment the number of rows (which could also be handled via built-in variable NR). At the end, if there was at least one value read, print the average.
awk '{ sum += $2 } END { if (NR > 0) print sum / NR }'
If you want to use the shebang notation, you could write:
#!/bin/awk
{ sum += $2 }
END { if (NR > 0) print sum / NR }
You can also control the format of the average with printf()
and a suitable format ("%13.6e\n"
, for example).
You can also generalize the code to average the Nth column (with N=2
in this sample) using:
awk -v N=2 '{ sum += $N } END { if (NR > 0) print sum / NR }'
SQL Injection can be done on any input the user can influence that isn't properly escaped before used in a query.
One example would be a get variable like this:
http//www.example.com/user.php?userid=5
Now, if the accompanying PHP code goes something like this:
$query = "SELECT username, password FROM users WHERE userid=" . $_GET['userid'];
// ...
You can easily use SQL injection here too:
http//www.example.com/user.php?userid=5 AND 1=2 UNION SELECT password,username FROM users WHERE usertype='admin'
(of course, the spaces will have to be replaced by %20
, but this is more readable. Additionally, this is just an example making some more assumptions, but the idea should be clear.)
It's also important to realize that simply moving the program break pointer around with brk
and sbrk
doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.
Basic and not very extensive testing comparing the execution time of the five supplied answers:
def numpyIndexValues(a, b):
na = np.array(a)
nb = np.array(b)
out = list(na[nb])
return out
def mapIndexValues(a, b):
out = map(a.__getitem__, b)
return list(out)
def getIndexValues(a, b):
out = operator.itemgetter(*b)(a)
return out
def pythonLoopOverlap(a, b):
c = [ a[i] for i in b]
return c
multipleListItemValues = lambda searchList, ind: [searchList[i] for i in ind]
using the following input:
a = range(0, 10000000)
b = range(500, 500000)
simple python loop was the quickest with lambda operation a close second, mapIndexValues and getIndexValues were consistently pretty similar with numpy method significantly slower after converting lists to numpy arrays.If data is already in numpy arrays the numpyIndexValues method with the numpy.array conversion removed is quickest.
numpyIndexValues -> time:1.38940598 (when converted the lists to numpy arrays)
numpyIndexValues -> time:0.0193445 (using numpy array instead of python list as input, and conversion code removed)
mapIndexValues -> time:0.06477512099999999
getIndexValues -> time:0.06391049500000001
multipleListItemValues -> time:0.043773591
pythonLoopOverlap -> time:0.043021754999999995
I also noticed that you can provide a group of coroutines in wait() by simply specifying the list:
result=loop.run_until_complete(asyncio.wait([
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
]))
Whereas grouping in gather() is done by just specifying multiple coroutines:
result=loop.run_until_complete(asyncio.gather(
say('first hello', 2),
say('second hello', 1),
say('third hello', 4)
))
<?
ob_start(); // ensures anything dumped out will be caught
// do stuff here
$url = 'http://example.com/thankyou.php'; // this can be set based on whatever
// clear out the output buffer
while (ob_get_status())
{
ob_end_clean();
}
// no redirect
header( "Location: $url" );
?>
@hexacyanide's answer is almost a complete one.
On Windows command prince
could be prince.exe
, prince.cmd
, prince.bat
or just prince
(I'm no aware of how gems are bundled, but npm bins come with a sh script and a batch script - npm
and npm.cmd
).
If you want to write a portable script that would run on Unix and Windows, you have to spawn the right executable.
Here is a simple yet portable spawn function:
function spawn(cmd, args, opt) {
var isWindows = /win/.test(process.platform);
if ( isWindows ) {
if ( !args ) args = [];
args.unshift(cmd);
args.unshift('/c');
cmd = process.env.comspec;
}
return child_process.spawn(cmd, args, opt);
}
var cmd = spawn("prince", ["-v", "builds/pdf/book.html", "-o", "builds/pdf/book.pdf"])
// Use these props to get execution results:
// cmd.stdin;
// cmd.stdout;
// cmd.stderr;
parseInt()
with radix is a best solution (as was told by many):
But if you want to implement it without parseInt, here is an implementation:
function bin2dec(num){
return num.split('').reverse().reduce(function(x, y, i){
return (y === '1') ? x + Math.pow(2, i) : x;
}, 0);
}
If you're already running a php page then
php bit:
$json = json_encode($_REQUEST, JSON_FORCE_OBJECT);
print "<script>var getVars = $json;</script>";
js bit:
var param1var = getVars.param1var;
But for Html pages Jose Basilio's solution looks good to me.
Good luck!
It seems you cannot have your project root, with the AndroidManifest.xml deeper than one directory level below your workspace root. I struggled for an hour with this before I just gave up and rearranged my repo.
If you want to use jQuery. I found this:
http://www.jquerysdk.com/api/jQuery.htmlspecialchars
(part of jquery.string plugin offered by jQuery SDK)
The problem with Prototype I believe is that it extends base objects in JavaScript and will be incompatible with any jQuery you may have used. Of course, if you are already using Prototype and not jQuery, it won't be a problem.
EDIT: Also there is this, which is a port of Prototype's string utilities for jQuery:
A simpler solution is git rebase <SHA1 of B> topic
. This works irrespective of where your HEAD
is.
We can confirm this behaviour from git rebase doc
<upstream>
Upstream branch to compare against. May be any valid commit, not just an existing branch name. Defaults to the configured upstream for the current branch.
topic
too in the above command ?
git rebase <SHA1 of B> <SHA1 of topic>
This will also work but rebase then won't make Topic
point to new branch so created and HEAD
will be in detached state. So from here you have to manually delete old Topic
and create a new branch reference on new branch created by rebase.
Change http to https of the marked error or all the URL ending with *.xsd extension.
You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.
Sorting a list in ascending order can be performed as default operation on this way:
Collections.sort(list);
Sorting a list in descending order can be performed on this way:
Collections.reverse(list);
According to these facts, your solution has to be written like this:
public class tes
{
public static void main(String args[])
{
List<Integer> lList = new ArrayList<Integer>();
lList.add(4);
lList.add(1);
lList.add(7);
lList.add(2);
lList.add(9);
lList.add(1);
lList.add(5);
Collections.sort(lList);
for(int i=0; i<lList.size();i++ )
{
System.out.println(lList.get(i));
}
}
}
More about Collections you can read here.
If you want to change buttons text color (positive, negative, neutral) just add to your custom dialog style:
<item name="colorAccent">@color/accent_color</item>
So, your dialog style must looks like this:
<style name="AlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:textColor">@android:color/black</item>
<item name="colorAccent">@color/topeka_accent</item>
</style>
:last
is not part of the css spec, this is jQuery specific.
you should be looking for last-child
var first = div.querySelector('[move_id]:first-child');
var last = div.querySelector('[move_id]:last-child');
I could be wrong, but I thought that slashes only appeared in branch names when they related to a remote repo, for example origin/master
.
Here is a code that works for me, which is a part from the website above combined with my early trials: http://www.codeproject.com/KB/system/DriveDetector.aspx
This basically makes your form listen to windows messages, filters for usb drives and (cd-dvds), grabs the lparam structure of the message and extracts the drive letter.
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_DEVICECHANGE)
{
DEV_BROADCAST_VOLUME vol = (DEV_BROADCAST_VOLUME)Marshal.PtrToStructure(m.LParam, typeof(DEV_BROADCAST_VOLUME));
if ((m.WParam.ToInt32() == DBT_DEVICEARRIVAL) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME) )
{
MessageBox.Show(DriveMaskToLetter(vol.dbcv_unitmask).ToString());
}
if ((m.WParam.ToInt32() == DBT_DEVICEREMOVALCOMPLETE) && (vol.dbcv_devicetype == DBT_DEVTYPVOLUME))
{
MessageBox.Show("usb out");
}
}
base.WndProc(ref m);
}
[StructLayout(LayoutKind.Sequential)] //Same layout in mem
public struct DEV_BROADCAST_VOLUME
{
public int dbcv_size;
public int dbcv_devicetype;
public int dbcv_reserved;
public int dbcv_unitmask;
}
private static char DriveMaskToLetter(int mask)
{
char letter;
string drives = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //1 = A, 2 = B, 3 = C
int cnt = 0;
int pom = mask / 2;
while (pom != 0) // while there is any bit set in the mask shift it right
{
pom = pom / 2;
cnt++;
}
if (cnt < drives.Length)
letter = drives[cnt];
else
letter = '?';
return letter;
}
Do not forget to add this:
using System.Runtime.InteropServices;
and the following constants:
const int WM_DEVICECHANGE = 0x0219; //see msdn site
const int DBT_DEVICEARRIVAL = 0x8000;
const int DBT_DEVICEREMOVALCOMPLETE = 0x8004;
const int DBT_DEVTYPVOLUME = 0x00000002;
For Windows, first install the git base from here: https://git-scm.com/downloads
Next, set the environment variable:
C:\Program Files\Git\git-bash.exe
To test it, open the command window: press Windows+R, type cmd and then type ssh.
It turns out that the problem really was that the address was busy - the busyness was caused by some other problems in how we are handling network communications. Your inputs have helped me figure this out. Thank you.
EDIT: to be specific, the problems in handling our network communications were that these status updates would be constantly re-sent if the first failed. It was only a matter of time until we had every distributed slave trying to send its status update at the same time, which was over-saturating our network.
Use the enumerate
built-in function: http://docs.python.org/library/functions.html#enumerate
I believe what you are looking for is "git restore".
The easiest way is to remove the file locally, and then execute the git restore command for that file:
$ rm file.txt
$ git restore file.txt
How about?
while BoolIter(N, default=True, falseIndex=N-1):
print 'some thing'
or in a more ugly way:
for _ in BoolIter(N):
print 'doing somthing'
or if you want to catch the last time through:
for lastIteration in BoolIter(N, default=False, trueIndex=N-1):
if not lastIteration:
print 'still going'
else:
print 'last time'
where:
class BoolIter(object):
def __init__(self, n, default=False, falseIndex=None, trueIndex=None, falseIndexes=[], trueIndexes=[], emitObject=False):
self.n = n
self.i = None
self._default = default
self._falseIndexes=set(falseIndexes)
self._trueIndexes=set(trueIndexes)
if falseIndex is not None:
self._falseIndexes.add(falseIndex)
if trueIndex is not None:
self._trueIndexes.add(trueIndex)
self._emitObject = emitObject
def __iter__(self):
return self
def next(self):
if self.i is None:
self.i = 0
else:
self.i += 1
if self.i == self.n:
raise StopIteration
if self._emitObject:
return self
else:
return self.__nonzero__()
def __nonzero__(self):
i = self.i
if i in self._trueIndexes:
return True
if i in self._falseIndexes:
return False
return self._default
def __bool__(self):
return self.__nonzero__()
For VB.Net is
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + "database path")
Dim cmd As New OleDb.OleDbCommand
Dim dt As New DataTable
Dim da As New OleDb.OleDbDataAdapter
con.Open()
cmd.Connection = con
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
For i As Integer = 0 To dt.Rows.Count
someVar = dt.Rows(i)("fieldName")
Next
It'll be because response[0]
itself is undefined.
In my opinion, the easiest way to setup the local locale in python{,3} is:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, '')
'de_DE.UTF-8'
Then, locale aware stuff just works, if you're on a decent linux distro, and should work on binary distributions of the other OSes as well (or that's a bug IMHO).
>>> import datetime as dt
>>> print(dt.date.today().strftime("%A %d. %B %Y"))
Sonntag 11. Dezember 2016
Note that if you rely on sleep taking exactly 50 ms, you won't get that. It will just be about it.
Within the environment align
from the package amsmath
it is possible to combine the use of \label
and \tag
for each equation or line. For example, the code:
\documentclass{article}
\usepackage{amsmath}
\begin{document}
Write
\begin{align}
x+y\label{eq:eq1}\tag{Aa}\\
x+z\label{eq:eq2}\tag{Bb}\\
y-z\label{eq:eq3}\tag{Cc}\\
y-2z\nonumber
\end{align}
then cite \eqref{eq:eq1} and \eqref{eq:eq2} or \eqref{eq:eq3} separately.
\end{document}
produces:
First is you have to understand the difference between MyISAM
and InnoDB
Engines. And this is clearly stated on this link. You can use this sql statement if you want to convert InnoDB to MyISAM:
ALTER TABLE t1 ENGINE=MyISAM;
If you only want the tag names, it should be possible to do this via a regular expression.
<([a-zA-Z]+)(?:[^>]*[^/] *)?>
should do what you need. But I think the solution of "moritz" is already fine. I didn't see it in the beginning.
For all downvoters: In some cases it just makes sense to use a regular expression, because it can be the easiest and quickest solution. I agree that in general you should not parse HTML with regular expressions.
But regular expressions can be a very powerful tool when you have a subset of HTML where you know the format and you just want to extract some values. I did that hundreds of times and almost always achieved what I wanted.
From http://readableweb.com/mo-bulletproofer-font-face-css-syntax/
Now that web fonts are supported in Firefox 3.5 and 3.6, Internet Explorer, Safari, Opera 10.5, and Chrome, web authors face new questions: How do these implementations differ? What CSS techniques will accommodate all? Firefox developer John Daggett recently posted a little roundup about these issues and the workarounds that are being explored. In response to that post, and in response to, particularly, Paul Irish’s work, I came up with the following @font-face CSS syntax. It’s been tested in all of the above named browsers including IE 8, 7, and 6. So far, so good. The following is a test page that declares the free Droid font as a complete font-family with Regular, Italic, Bold, and Bold Italic. View source for details. Alert: Be aware that Readable Web has released it’s first @font-face related software utility for creating natively compressed EOT files quickly and easily. It has it’s own web site and, in addition to the utility itself, the download package contains helpful documentation, a test font, and an EOT test page. It’s called EOTFAST If you’re working with @font-face, it’s a must-have.
Here’s The Mo’ Bulletproofer Code:
@font-face{ /* for IE */
font-family:FishyFont;
src:url(fishy.eot);
}
@font-face { /* for non-IE */
font-family:FishyFont;
src:url(http://:/) format("No-IE-404"),url(fishy.ttf) format("truetype");
}
Based on Kiril V. Lyadvinsky answer, I made a new version. This snippet use template and overloading. With it, you can write vector3 = vector1 + vector2
and vector4 += vector3
. Hope it can help.
template <typename T>
std::vector<T> operator+(const std::vector<T> &A, const std::vector<T> &B)
{
std::vector<T> AB;
AB.reserve(A.size() + B.size()); // preallocate memory
AB.insert(AB.end(), A.begin(), A.end()); // add A;
AB.insert(AB.end(), B.begin(), B.end()); // add B;
return AB;
}
template <typename T>
std::vector<T> &operator+=(std::vector<T> &A, const std::vector<T> &B)
{
A.reserve(A.size() + B.size()); // preallocate memory without erase original data
A.insert(A.end(), B.begin(), B.end()); // add B;
return A; // here A could be named AB
}
For swift 4 and you can adjust imageView size
let logoContainer = UIView(frame: CGRect(x: 0, y: 0, width: 270, height: 30))
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 270, height: 30))
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "your_image")
imageView.image = image
logoContainer.addSubview(imageView)
navigationItem.titleView = logoContainer
I don't know for how long this post has been here. But I stumbled upon similar problem now. Hence posting the solution so that it might help others.
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use GD::Graph::pie;
use MIME::Base64;
my @data = (['A','O','S','I'],[3,16,12,47]);
my $mygraph = GD::Graph::pie->new(200, 200);
my $myimage = $mygraph->plot(\@data)->png;
print <<end_html;
<html><head><title>Current Stats</title></head>
<body>
<p align="center">
<img src="data:image/png;base64,
end_html
print encode_base64($myimage);
print <<end_html;
" style="width: 888px; height: 598px; border-width: 2px; border-style: solid;" /></p>
</body>
</html>
end_html
.
(dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess
files, then they are probably in the root folder for the website.
If you are using a command line (terminal) to access, then they will only show up if you use:
ls -a
If you are using a GUI application, look for a setting to "show hidden files" or something similar.
If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):
cd /
find . -name ".htaccess"
This will list out any files it finds with that name.
Set/change your product name, I had this issue until I created a product name as same as project name.
The product name can be set in the Consent screen section of the Google Developers Console for your project. Look under APIs & auth in the left navigation and select Consent screen. You need also to set your email address in the box above the product name.
The best way is to use spyOnProperty
. It expects 3 parameters and you need to pass get
or set
as a third param.
const div = fixture.debugElement.query(By.css('.ellipsis-overflow'));
// now mock properties
spyOnProperty(div.nativeElement, 'clientWidth', 'get').and.returnValue(1400);
spyOnProperty(div.nativeElement, 'scrollWidth', 'get').and.returnValue(2400);
Here I am setting the get
of clientWidth
of div.nativeElement
object.
If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.
This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):
public class MyAshxClass : IHttpHandler, IRequiresSessionState
First of all install nodejs:
sudo apt-get install nodejs
Then install npm:
sudo apt-get install npm
Then install bower:
npm install -g bower
For any of the npm package tutorial visit: https://www.npmjs.com/
Here just search the package and you can find how to install, documentation and tutorials as well.
P.S. This is just a very common solution. If your problem still exists you can try the advanced one.
I would use
\b[A-Za-z]*Id\b
The \b matches the beginning and end of a word i.e. space, tab or newline, or the beginning or end of a string.
The [A-Za-z] will match any letter, and the * means that 0+ get matched. Finally there is the Id.
Note that this will match words that have capital letters in the middle such as 'teStId'.
I use http://www.regular-expressions.info/ for regex reference
You can't set the input value in most browsers, but what you can do is create a new element, copy the attributes from the old element, and swap the two.
Given a form like:
<form>
<input id="fileInput" name="fileInput" type="file" />
</form>
The straight DOM way:
function clearFileInput(id)
{
var oldInput = document.getElementById(id);
var newInput = document.createElement("input");
newInput.type = "file";
newInput.id = oldInput.id;
newInput.name = oldInput.name;
newInput.className = oldInput.className;
newInput.style.cssText = oldInput.style.cssText;
// TODO: copy any other relevant attributes
oldInput.parentNode.replaceChild(newInput, oldInput);
}
clearFileInput("fileInput");
Simple DOM way. This may not work in older browsers that don't like file inputs:
oldInput.parentNode.replaceChild(oldInput.cloneNode(), oldInput);
The jQuery way:
$("#fileInput").replaceWith($("#fileInput").val('').clone(true));
// .val('') required for FF compatibility as per @nmit026
Resetting the whole form via jQuery: https://stackoverflow.com/a/13351234/1091947
You should use an Android emulator with the same api level as the compileSdkVersion. In your case you should use Android emulator with api level 21.
Or, if you are a fan of functional programming:
>>> a = [133, 53, 234, 241]
>>> "".join(map(lambda b: format(b, "02x"), a))
8535eaf1
>>>
Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.
<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
<li class = "ui-divider">
{{ meter.DESCRIPTION }}
{{ htmlgeneration() }}
</li>
</ul>
In Swift3, I have used in this way
var hasAddedGeofencesAtleastOnce: Bool {
get {
return UserDefaults.standard.object(forKey: "hasAddedGeofencesAtleastOnce") != nil
}
}
The answer is great if you are to use that multiple times.
I hope it helps :)
If you are using Swift, the Just library does this for you. Example from it's readme file:
// talk to registration end point
Just.post(
"http://justiceleauge.org/member/register",
data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
if (r.ok) { /* success! */ }
}
It's even simpler than that.
A hashtable is nothing more than an array (usually sparse one) of vectors which contain key/value pairs. The maximum size of this array is typically smaller than the number of items in the set of possible values for the type of data being stored in the hashtable.
The hash algorithm is used to generate an index into that array based on the values of the item that will be stored in the array.
This is where storing vectors of key/value pairs in the array come in. Because the set of values that can be indexes in the array is typically smaller than the number of all possible values that the type can have, it is possible that your hash algorithm is going to generate the same value for two separate keys. A good hash algorithm will prevent this as much as possible (which is why it is relegated to the type usually because it has specific information which a general hash algorithm can't possibly know), but it's impossible to prevent.
Because of this, you can have multiple keys that will generate the same hash code. When that happens, the items in the vector are iterated through, and a direct comparison is done between the key in the vector and the key that is being looked up. If it is found, great and the value associated with the key is returned, otherwise, nothing is returned.
Your /home/gnu/bin/c++
seem to require additional flag to link things properly and CMake doesn't know about that.
To use /usr/bin/c++
as your compiler run cmake
with -DCMAKE_CXX_COMPILER=/usr/bin/c++
.
Also, CMAKE_PREFIX_PATH
variable sets destination dir where your project' files should be installed. It has nothing to do with CMake installation prefix and CMake itself already know this.
In your Activity you can tint your PNG image resources with a single colour:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myColorTint();
setContentView(R.layout.activity_main);
}
private void myColorTint() {
int tint = Color.parseColor("#0000FF"); // R.color.blue;
PorterDuff.Mode mode = PorterDuff.Mode.SRC_ATOP;
// add your drawable resources you wish to tint to the drawables array...
int drawables[] = { R.drawable.ic_action_edit, R.drawable.ic_action_refresh };
for (int id : drawables) {
Drawable icon = getResources().getDrawable(id);
icon.setColorFilter(tint,mode);
}
}
Now when you use the R.drawable.* it should be coloured with the desired tint. If you need additional colours then you should be able to .mutate() the drawable.
You need to decide exactly what you want to do - and preferably explain it a bit more clearly.
If you know which file you want the output of the executed command to go to, then:
If you want the parent to read the output from the child, arrange for the child to pipe its output back to the parent.
@IronMensan's format method answer is the way to go. But in the interest of answering your question about ljust:
>>> def printit():
... print 'Location: 10-10-10-10'.ljust(40) + 'Revision: 1'
... print 'District: Tower'.ljust(40) + 'Date: May 16, 2012'
... print 'User: LOD'.ljust(40) + 'Time: 10:15'
...
>>> printit()
Location: 10-10-10-10 Revision: 1
District: Tower Date: May 16, 2012
User: LOD Time: 10:15
Edit to note this method doesn't require you to know how long your strings are. .format() may also, but I'm not familiar enough with it to say.
>>> uname='LOD'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: LOD Time: 10:15'
>>> uname='Tiddlywinks'
>>> 'User: {}'.format(uname).ljust(40) + 'Time: 10:15'
'User: Tiddlywinks Time: 10:15'
Here are different options for this:
First: without jQuery:
var lis = document.querySelectorAll('ul > li');
var contents = [].map.call(lis, function (li) {
return li.innerHTML;
}).reverse().forEach(function (content, i) {
lis[i].innerHTML = content;
});
... and with jQuery:
You can use this:
$($("ul > li").get().reverse()).each(function (i) {
$(this).text( 'Item ' + (++i));
});
Demo here
Another way, using also jQuery with reverse is:
$.fn.reverse = [].reverse;
$("ul > li").reverse().each(function (i) {
$(this).text( 'Item ' + (++i));
});
This demo here.
One more alternative is to use the length
(count of elements matching that selector) and go down from there using the index
of each iteration. Then you can use this:
var $li = $("ul > li");
$li.each(function (i) {
$(this).text( 'Item ' + ($li.length - i));
});
This demo here
One more, kind of related to the one above:
var $li = $("ul > li");
$li.text(function (i) {
return 'Item ' + ($li.length - i);
});
Demo here
It is also (Transact-SQL) ... according to BOL.
-- exec sp_serveroption 'SERVER NAME', 'data access', 'true' --execute once
EXEC sp_primarykeys @table_server = N'server_name',
@table_name = N'table_name',
@table_catalog = N'db_name',
@table_schema = N'schema_name'; --frequently 'dbo'
Anyway, here is how to fix it:
Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System Variables->New:
Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M
taken from this link
I created this extension for save a screen shot from UIView
extension UIView {
func saveImageFromView(path path:String) {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
}}
call:
let pathDocuments = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!
let pathImage = "\(pathDocuments)/\(user!.usuarioID.integerValue).jpg"
reportView.saveImageFromView(path: pathImage)
If you want to create a png must change:
UIImageJPEGRepresentation(image, 0.4)?.writeToFile(path, atomically: true)
by
UIImagePNGRepresentation(image)?.writeToFile(path, atomically: true)
A singleton in JavaScript is achieved using the module pattern and closures.
Below is the code which is pretty much self-explanatory -
// Singleton example.
var singleton = (function() {
var instance;
function init() {
var privateVar1 = "this is a private variable";
var privateVar2 = "another var";
function pubMethod() {
// Accessing private variables from inside.
console.log(this.privateVar1);
console.log(this.privateVar2);
console.log("inside of a public method");
};
}
function getInstance() {
if (!instance) {
instance = init();
}
return instance;
};
return {
getInstance: getInstance
}
})();
var obj1 = singleton.getInstance();
var obj2 = singleton.getInstance();
console.log(obj1 === obj2); // Check for type and value.
when new props or states being received (like you call setState
here), React will invoked some functions, which are called componentWillUpdate
and componentDidUpdate
in your case, just simply add a componentDidUpdate
function to call this.drawGrid()
here is working code in JS Bin
as I mentioned, in the code, componentDidUpdate
will be invoked after this.setState(...)
then componentDidUpdate
inside is going to call this.drawGrid()
read more about component Lifecycle in React https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate
here is a simple code for printing all the prime numbers until given number n,
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n,i,j,k;
cout<<"Enter n\n";
cin>>n;
for(i=1;i<=n;i++)
{ k=0;
for(j=1;j<=i;j++)
{
if((i%j)==0)
k++;
}
if(k==2)
cout<<i<<endl;
}
getch();
}
You can create a new blank solution and add your different projects to it.
Once the page is rendered to the client you have only two ways of forcing a refresh. One is Javascript
setTimeout("location.reload(true);", timeout);
The second is a Meta tag:
<meta http-equiv="refresh" content="600">
You can set the refresh intervals on the server side.
Here we can use urllib's Legacy interface in Python3:
The following functions and classes are ported from the Python 2 module urllib (as opposed to urllib2). They might become deprecated at some point in the future.
Example (2 lines code):
import urllib.request
url = 'https://www.python.org/static/img/python-logo.png'
urllib.request.urlretrieve(url, "logo.png")
try this below
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
C++20 std::popcount
The following proposal has been merged http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0553r4.html and should add it to a the <bit>
header.
I expect the usage to be like:
#include <bit>
#include <iostream>
int main() {
std::cout << std::popcount(0x55) << std::endl;
}
I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a
still doesn't support it.
The proposal says:
Header:
<bit>
namespace std { // 25.5.6, counting template<class T> constexpr int popcount(T x) noexcept;
and:
template<class T> constexpr int popcount(T x) noexcept;
Constraints: T is an unsigned integer type (3.9.1 [basic.fundamental]).
Returns: The number of 1 bits in the value of x.
std::rotl
and std::rotr
were also added to do circular bit rotations: Best practices for circular shift (rotate) operations in C++
If you completely want to clear the session you can use this:
session_unset();
session_destroy();
Actually both are not neccessary but it does not hurt.
If you want to clear only a specific part I think you need this:
unset($_SESSION['Products']);
//or
$_SESSION['Products'] = "";
depending on what you need.
It converts the suffix to a Boolean value.
It is not possible to resize an array. However, it is possible change the size of an array through copying the original array to the newly sized one and keep the current elements. The array can also be reduced in size by removing an element and resizing.
import java.util.Arrays
public class ResizingArray {
public static void main(String[] args) {
String[] stringArray = new String[2] //A string array with 2 strings
stringArray[0] = "string1";
stringArray[1] = "string2";
// increase size and add string to array by copying to a temporary array
String[] tempStringArray = Arrays.copyOf(stringArray, stringArray.length + 1);
// Add in the new string
tempStringArray[2] = "string3";
// Copy temp array to original array
stringArray = tempStringArray;
// decrease size by removing certain string from array (string1 for example)
for(int i = 0; i < stringArray.length; i++) {
if(stringArray[i] == string1) {
stringArray[i] = stringArray[stringArray.length - 1];
// This replaces the string to be removed with the last string in the array
// When the array is resized by -1, The last string is removed
// Which is why we copied the last string to the position of the string we wanted to remove
String[] tempStringArray2 = Arrays.copyOf(arrayString, arrayString.length - 1);
// Set the original array to the new array
stringArray = tempStringArray2;
}
}
}
}
This example may help:
Controller class:
@RestController
@RequestMapping("/abc/dev")
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class MyController {
//Setter Injection
@Resource(name="configBlack")
public void setColor(Color c) {
System.out.println("Injecting setter");
this.blackColor = c;
}
public Color getColor() {
return this.blackColor;
}
public MyController() {
super();
}
Color nred;
Color nblack;
//Constructor injection
@Autowired
public MyController(@Qualifier("constBlack")Color b, @Qualifier("constRed")Color r) {
this.nred = r;
this.nblack = b;
}
private Color blackColor;
//Field injection
@Autowired
private Color black;
//Field injection
@Resource(name="configRed")
private Color red;
@RequestMapping(value = "/customers", produces = { "application/text" }, method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.CREATED)
public String createCustomer() {
System.out.println("Field injection red: " + red.getName());
System.out.println("Field injection: " + black.getName());
System.out.println("Setter injection black: " + blackColor.getName());
System.out.println("Constructor inject nred: " + nred.getName());
System.out.println("Constructor inject nblack: " + nblack.getName());
MyController mc = new MyController();
mc.setColor(new Red("No injection red"));
System.out.println("No injection : " + mc.getColor().getName());
return "Hello";
}
}
Interface Color:
public interface Color {
public String getName();
}
Class Red:
@Component
public class Red implements Color{
private String name;
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Red(String name) {
System.out.println("Red color: "+ name);
this.name = name;
}
public Red() {
System.out.println("Red color default constructor");
}
}
Class Black:
@Component
public class Black implements Color{
private String name;
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Black(String name) {
System.out.println("Black color: "+ name);
this.name = name;
}
public Black() {
System.out.println("Black color default constructor");
}
}
Config class for creating Beans:
@Configuration
public class Config {
@Bean(name = "configRed")
public Red getRedInstance() {
Red red = new Red();
red.setName("Config red");
return red;
}
@Bean(name = "configBlack")
public Black getBlackInstance() {
Black black = new Black();
black.setName("config Black");
return black;
}
@Bean(name = "constRed")
public Red getConstRedInstance() {
Red red = new Red();
red.setName("Config const red");
return red;
}
@Bean(name = "constBlack")
public Black getConstBlackInstance() {
Black black = new Black();
black.setName("config const Black");
return black;
}
}
BootApplication (main class):
@SpringBootApplication
@ComponentScan(basePackages = {"com"})
public class BootApplication {
public static void main(String[] args) {
SpringApplication.run(BootApplication.class, args);
}
}
Run Application and hit URL: GET 127.0.0.1:8080/abc/dev/customers/
Output:
Injecting setter
Field injection red: Config red
Field injection: null
Setter injection black: config Black
Constructor inject nred: Config const red
Constructor inject nblack: config const Black
Red color: No injection red
Injecting setter
No injection : No injection red
My two cents showing how to use the Google Charts API to solve this problem.
You can use sudo ip link delete
to remove the interface.
Single quote must be there, since date converted to character.
Select employee_id, count(*) From Employee Where to_char(employee_date_hired, 'DD-MON-YY') > '31-DEC-95';
In my rails (rails 4.2)
project, I use
Model.last(10) # get the last 10 record order by id
and it works.
Try my favorite: put in
~/.zshrc
this line:
PROMPT='%F{240}%n%F{red}@%F{green}%m:%F{141}%d$ %F{reset}'
don't forget
source ~/.zshrc
to test the changes
you can change the colors/color codes, of course :-)
I tend to put any
on the other side i.e. var foo:IFoo = <any>{};
So something like this is still typesafe:
interface IFoo{
bar:string;
baz:string;
boo:string;
}
// How I tend to intialize
var foo:IFoo = <any>{};
foo.bar = "asdf";
foo.baz = "boo";
foo.boo = "boo";
// the following is an error,
// so you haven't lost type safety
foo.bar = 123;
Alternatively you can mark these properties as optional:
interface IFoo{
bar?:string;
baz?:string;
boo?:string;
}
// Now your simple initialization works
var foo:IFoo = {};
to load a KeyStore, you'll need to tell it the type of keystore it is (probably jceks), provide an inputstream, and a password. then, you can load it like so:
KeyStore ks = KeyStore.getInstance(TYPE_OF_KEYSTORE);
ks.load(new FileInputStream(PATH_TO_KEYSTORE), PASSWORD);
this can throw a KeyStoreException, so you can surround in a try block if you like, or re-throw. Keep in mind a keystore can contain multiple keys, so you'll need to look up your key with an alias, here's an example with a symmetric key:
SecretKeyEntry entry = (KeyStore.SecretKeyEntry)ks.getEntry(SOME_ALIAS,new KeyStore.PasswordProtection(SOME_PASSWORD));
SecretKey someKey = entry.getSecretKey();
You can also set it in the [ServiceBehavior] tag above your class declaration that inherits the interface
[ServiceBehavior(IncludeExceptionDetailInFaults = true)]
public class MyClass:IMyService
{
...
}
Immortal Blue is correct in not disclosing the exeption details to a publicly released version, but for testing purposes this is a handy tool. Always turn back off when releasing.
Take a look at PEP-238: Changing the Division Operator
The // operator will be available to request floor division unambiguously.
if you still getting this error try this.
Two of them always produce the same answer:
COUNT(*)
counts the number of rowsCOUNT(1)
also counts the number of rowsAssuming the pk
is a primary key and that no nulls are allowed in the values, then
COUNT(pk)
also counts the number of rowsHowever, if pk
is not constrained to be not null, then it produces a different answer:
COUNT(possibly_null)
counts the number of rows with non-null values in the column possibly_null
.
COUNT(DISTINCT pk)
also counts the number of rows (because a primary key does not allow duplicates).
COUNT(DISTINCT possibly_null_or_dup)
counts the number of distinct non-null values in the column possibly_null_or_dup
.
COUNT(DISTINCT possibly_duplicated)
counts the number of distinct (necessarily non-null) values in the column possibly_duplicated
when that has the NOT NULL
clause on it.
Normally, I write COUNT(*)
; it is the original recommended notation for SQL. Similarly, with the EXISTS
clause, I normally write WHERE EXISTS(SELECT * FROM ...)
because that was the original recommend notation. There should be no benefit to the alternatives; the optimizer should see through the more obscure notations.
#0000ffff
- that is the code that you need for transparent. I just did it and it worked.
You could walk up through the parents, noting their position within their parent, until you arrive at the Form.
Edit: Something like (untested):
public Point GetPositionInForm(Control ctrl)
{
Point p = ctrl.Location;
Control parent = ctrl.Parent;
while (! (parent is Form))
{
p.Offset(parent.Location.X, parent.Location.Y);
parent = parent.Parent;
}
return p;
}
Password Strength Algorithm:
Password Length:
5 Points: Less than 4 characters
10 Points: 5 to 7 characters
25 Points: 8 or more
Letters:
0 Points: No letters
10 Points: Letters are all lower case
20 Points: Letters are upper case and lower case
Numbers:
0 Points: No numbers
10 Points: 1 number
20 Points: 3 or more numbers
Characters:
0 Points: No characters
10 Points: 1 character
25 Points: More than 1 character
Bonus:
2 Points: Letters and numbers
3 Points: Letters, numbers, and characters
5 Points: Mixed case letters, numbers, and characters
Password Text Range:
>= 90: Very Secure
>= 80: Secure
>= 70: Very Strong
>= 60: Strong
>= 50: Average
>= 25: Weak
>= 0: Very Weak
Settings Toggle to true or false, if you want to change what is checked in the password
var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"
Check password
function checkPassword(strPassword)
{
// Reset combination count
var nScore = 0;
// Password length
// -- Less than 4 characters
if (strPassword.length < 5)
{
nScore += 5;
}
// -- 5 to 7 characters
else if (strPassword.length > 4 && strPassword.length < 8)
{
nScore += 10;
}
// -- 8 or more
else if (strPassword.length > 7)
{
nScore += 25;
}
// Letters
var nUpperCount = countContain(strPassword, m_strUpperCase);
var nLowerCount = countContain(strPassword, m_strLowerCase);
var nLowerUpperCount = nUpperCount + nLowerCount;
// -- Letters are all lower case
if (nUpperCount == 0 && nLowerCount != 0)
{
nScore += 10;
}
// -- Letters are upper case and lower case
else if (nUpperCount != 0 && nLowerCount != 0)
{
nScore += 20;
}
// Numbers
var nNumberCount = countContain(strPassword, m_strNumber);
// -- 1 number
if (nNumberCount == 1)
{
nScore += 10;
}
// -- 3 or more numbers
if (nNumberCount >= 3)
{
nScore += 20;
}
// Characters
var nCharacterCount = countContain(strPassword, m_strCharacters);
// -- 1 character
if (nCharacterCount == 1)
{
nScore += 10;
}
// -- More than 1 character
if (nCharacterCount > 1)
{
nScore += 25;
}
// Bonus
// -- Letters and numbers
if (nNumberCount != 0 && nLowerUpperCount != 0)
{
nScore += 2;
}
// -- Letters, numbers, and characters
if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
{
nScore += 3;
}
// -- Mixed case letters, numbers, and characters
if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
{
nScore += 5;
}
return nScore;
}
// Runs password through check and then updates GUI
function runPassword(strPassword, strFieldID)
{
// Check password
var nScore = checkPassword(strPassword);
// Get controls
var ctlBar = document.getElementById(strFieldID + "_bar");
var ctlText = document.getElementById(strFieldID + "_text");
if (!ctlBar || !ctlText)
return;
// Set new width
ctlBar.style.width = (nScore*1.25>100)?100:nScore*1.25 + "%";
// Color and text
// -- Very Secure
/*if (nScore >= 90)
{
var strText = "Very Secure";
var strColor = "#0ca908";
}
// -- Secure
else if (nScore >= 80)
{
var strText = "Secure";
vstrColor = "#7ff67c";
}
// -- Very Strong
else
*/
if (nScore >= 80)
{
var strText = "Very Strong";
var strColor = "#008000";
}
// -- Strong
else if (nScore >= 60)
{
var strText = "Strong";
var strColor = "#006000";
}
// -- Average
else if (nScore >= 40)
{
var strText = "Average";
var strColor = "#e3cb00";
}
// -- Weak
else if (nScore >= 20)
{
var strText = "Weak";
var strColor = "#Fe3d1a";
}
// -- Very Weak
else
{
var strText = "Very Weak";
var strColor = "#e71a1a";
}
if(strPassword.length == 0)
{
ctlBar.style.backgroundColor = "";
ctlText.innerHTML = "";
}
else
{
ctlBar.style.backgroundColor = strColor;
ctlText.innerHTML = strText;
}
}
// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{
// Declare variables
var nCount = 0;
for (i = 0; i < strPassword.length; i++)
{
if (strCheck.indexOf(strPassword.charAt(i)) > -1)
{
nCount++;
}
}
return nCount;
}
You can customize by yourself according to your requirement.
This is possibly unrelated directly to the question; but one mistake I just made myself, and I see in the OP, is the URL specification ssh://user@server:/GitRepos/myproject.git
- namely, you have both a colon :
, and a forward slash /
after it signifying an absolute path.
I then found Git clone, ssh: Could not resolve hostname – git , development – Nicolas Kuttler (as that was the error I was getting, on git
version 1.7.9.5), noting:
The problem with the command I used initially was that I tried to use an scp-like syntax.
... which was also my problem! So basically in git
with ssh
, you either use
ssh://[email protected]/absolute/path/to/repo.git/
- just a forward slash for absolute path on server[email protected]:relative/path/to/repo.git/
- just a colon (it mustn't have the ssh://
for relative path on server (relative to home dir of username
on server machine)Hope this helps someone,
Cheers!
If you have problems with accessing to the path, maybe you need to put this:
$root = $_SERVER['DOCUMENT_ROOT'];
$path = "/cv/";
// Open the folder
$dir_handle = @opendir($root . $path) or die("Unable to open $path");
You need convert list
to numpy array
and then reshape
:
df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
a b c
0 1 2 3
1 4 5 6
2 7 8 9
I just been for 3 days looking for a jquery UI and CSS solution, I merge some code I saw, fix a little, and finally (along the other codes) I could make it work!
http://jsfiddle.net/Moatilliatta/97m6ty1a/
<ul id="nav" class="testnav">
<li><a class="clk" href="#">Item 1</a></li>
<li><a class="clk" href="#">Item 2</a></li>
<li><a class="clk" href="#">Item 3</a>
<ul class="sub-menu">
<li><a href="#">Item 3-1</a>
<ul class="sub-menu">
<li><a href="#">Item 3-11</a></li>
<li><a href="#">Item 3-12</a>
<ul>
<li><a href="#">Item 3-111</a></li>
<li><a href="#">Item 3-112</a>
<ul>
<li><a href="#">Item 3-1111</a></li>
<li><a href="#">Item 3-1112</a></li>
<li><a href="#">Item 3-1113</a>
<ul>
<li><a href="#">Item 3-11131</a></li>
<li><a href="#">Item 3-11132</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Item 3-113</a></li>
</ul>
</li>
<li><a href="#">Item 3-13</a></li>
</ul>
</li>
<li><a href="#">Item 3-2</a>
<ul>
<li><a href="#."> Item 3-21 </a></li>
<li><a href="#."> Item 3-22 </a></li>
<li><a href="#."> Item 3-23 </a></li>
</ul>
</li>
<li><a href="#">Item 3-3</a></li>
<li><a href="#">Item 3-4</a></li>
<li><a href="#">Item 3-5</a></li>
</ul>
</li>
<li><a class="clk" href="#">Item 4</a>
<ul class="sub-menu">
<li><a href="#">Item 4-1</a>
<ul class="sub-menu">
<li><a href="#."> Item 4-11 </a></li>
<li><a href="#."> Item 4-12 </a></li>
<li><a href="#."> Item 4-13 </a>
<ul>
<li><a href="#."> Item 4-131 </a></li>
<li><a href="#."> Item 4-132 </a></li>
<li><a href="#."> Item 4-133 </a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#">Item 4-2</a></li>
<li><a href="#">Item 4-3</a></li>
</ul>
</li>
<li><a class="clk" href="#">Item 5</a></li>
</ul>
javascript
$(document).ready(function(){
var menu = "#nav";
var position = {my: "left top", at: "left bottom"};
$(menu).menu({
position: position,
blur: function() {
$(this).menu("option", "position", position);
},
focus: function(e, ui) {
if ($(menu).get(0) !== $(ui).get(0).item.parent().get(0)) {
$(this).menu("option", "position", {my: "left top", at: "right top"});
}
}
}); });
CSS
.ui-menu {width: auto;}.ui-menu:after {content: ".";display: block;clear: both;visibility: hidden;line-height: 0;height: 0;}.ui-menu .ui-menu-item {display: inline-block;margin: 0;padding: 0;width: auto;}#nav{text-align: center;font-size: 12px;}#nav li {display: inline-block;}#nav li a span.ui-icon-carat-1-e {float:right;position:static;margin-top:2px;width:16px;height:16px;background:url(https://www.drupal.org/files/issues/ui-icons-222222-256x240.png) no-repeat -64px -16px;}#nav li ul li {width: 120px;border-bottom: 1px solid #ccc;}#nav li ul {width: 120px; }.ui-menu .ui-menu-item li a span.ui-icon-carat-1-e {background:url(https://www.drupal.org/files/issues/ui-icons-222222-256x240.png) no-repeat -32px -16px !important;
if key in array:
# do something
Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.
I think what you're trying to do should be done with multiple Activities. If you're learning Android, understanding Activities is something you're going to have to tackle. Trying to write a whole app with just one Activity will end up being a lot more difficult. Read this article to get yourself started, then you should end up with something more like this:
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.DownloadView:
// doStuff
startActivity(new Intent(ThisActivity.this, DownloadActivity.class));
break;
case R.id.AppView:
// doStuff
startActivity(new Intent(ThisActivity.this, AppActivity.class));
break;
}
}
};
findViewById(R.id.DownloadView).setOnClickListener(handler);
findViewById(R.id.AppView).setOnClickListener(handler);
Here is bitmap extension .convertToByteArray
wrote in Kotlin.
/**
* Convert bitmap to byte array using ByteBuffer.
*/
fun Bitmap.convertToByteArray(): ByteArray {
//minimum number of bytes that can be used to store this bitmap's pixels
val size = this.byteCount
//allocate new instances which will hold bitmap
val buffer = ByteBuffer.allocate(size)
val bytes = ByteArray(size)
//copy the bitmap's pixels into the specified buffer
this.copyPixelsToBuffer(buffer)
//rewinds buffer (buffer position is set to zero and the mark is discarded)
buffer.rewind()
//transfer bytes from buffer into the given destination array
buffer.get(bytes)
//return bitmap's pixels
return bytes
}
Another way (currently showing 25MB free on my G1):
MemoryInfo mi = new MemoryInfo();
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(mi);
long availableMegs = mi.availMem / 1048576L;
Just do it with a simple filestream.
var sr1 = new FileStream(FilePath, FileMode.Create);
sr1.Write(_UploadFile.File, 0, _UploadFile.File.Length);
sr1.Close();
sr1.Dispose();
_UploadFile.File is a byte[], and in the FilePath you get to specify the file extention.
If you want to get the latest changes in a directory without entering it, you can do:
$ git -C <Path to directory> pull
I use the following way to handle the many-to-many relationship where only foreign keys are involved.
So for inserting:
public void InsertStudentClass (long studentId, long classId)
{
using (var context = new DatabaseContext())
{
Student student = new Student { StudentID = studentId };
context.Students.Add(student);
context.Students.Attach(student);
Class class = new Class { ClassID = classId };
context.Classes.Add(class);
context.Classes.Attach(class);
student.Classes = new List<Class>();
student.Classes.Add(class);
context.SaveChanges();
}
}
For deleting,
public void DeleteStudentClass(long studentId, long classId)
{
Student student = context.Students.Include(x => x.Classes).Single(x => x.StudentID == studentId);
using (var context = new DatabaseContext())
{
context.Students.Attach(student);
Class classToDelete = student.Classes.Find(x => x.ClassID == classId);
if (classToDelete != null)
{
student.Classes.Remove(classToDelete);
context.SaveChanges();
}
}
}
with O(n log(n))
int[] arr1; // your given array
int[] arr2 = new int[arr1.length];
Arrays.sort(arr1);
for (int i = 0; i < arr1.length; i++) {
arr2[i]++;
if (i+1 < arr1.length)
{
if (arr1[i] == arr1[i + 1]) {
arr2[i]++;
i++;
}
}
}
for (int i = 0; i < arr1.length; i++) {
if(arr2[i]>0)
System.out.println(arr1[i] + ":" + arr2[i]);
}
I often use following command to spin my PHP Laravel framework :
$ php artisan serve --port=8080
or
$ php -S localhost:8080 -t public/
In above command : - Artisan is command-line interface included with Laravel which use serve to call built in php server
To Run with built-in web server.
php -S <addr>:<port> -T
Here,
-S : Switch to Run with built-in web server.
-T : Switch to specify document root for built-in web server.
The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.
public static Method[] getAccessibleMethods(Class clazz) {
List<Method> result = new ArrayList<Method>();
while (clazz != null) {
for (Method method : clazz.getDeclaredMethods()) {
int modifiers = method.getModifiers();
if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
result.add(method);
}
}
clazz = clazz.getSuperclass();
}
return result.toArray(new Method[result.size()]);
}
You can use Decode
as well:
SELECT DISTINCT a.item, decode(b.salesman,'VIKKIE','ICKY',Else),NVL(a.manufacturer,'Not Set')Manufacturer
FROM inv_items a, arv_sales b
WHERE a.co = b.co
AND A.ITEM_KEY = b.item_key
AND a.co = '100'
AND a.item LIKE 'BX%'
AND b.salesman in ('01','15')
AND trans_date BETWEEN to_date('010113','mmddrr')
and to_date('011713','mmddrr')
GROUP BY a.item, b.salesman, a.manufacturer
ORDER BY a.item
The best and easy solution for solving this issue is pass your data from this function in controller.
$scope.trustSrcurl = function(data)
{
return $sce.trustAsResourceUrl(data);
}
In html page
<iframe class="youtube-player" type="text/html" width="640" height="385" ng-src="{{trustSrcurl(video.src)}}" allowfullscreen frameborder="0"></iframe>
or a single select statement...
DECLARE @results VarChar(1000)
SELECT @results = CASE
WHEN @results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
Not with a regular statement, no.
What you can do is wrap the functionality in a PL/pgsql function (or another language, but PL/pgsql seems to be the most appropriate for this), and then just call that function. That means it'll still be a single statement to your app.
I had to completely refactor my code when I updated my PHP version to 7.2+ because of bad usage of the count($x) function. This is a real pain and its also extremely scary as there are hundreds usages, in different scenarios and there is no one rules fits all..
Rules I followed to refactor everything, examples:
$x = Auth::user()->posts->find(6); (check if user has a post id=6 using ->find())
[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x) { return 'Found'; }
$x = Auth::user()->profile->departments; (check if profile has some departments, there can have many departments)
[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }
$x = Auth::user()->profile->get(); (check if user has a profile after using a ->get())
[FAILS] if(count($x)) { return 'Found'; }
[GOOD] if($x->count()) { return 'Found'; }
Hopes this can help, even 5 years after the question has been asked, this stackoverflow post has helped me a lot!
To compare two objects along with all attributes of it, I followed this code and it didn't require tostring() or json compar
if(user1.equals(user2))
{
console.log("Both are equal");
}
_x000D_
e.
You can do this:
@Override
protected Dialog onCreateDialog(int id) {
String messageDialog;
String valueOK;
String valueCancel;
String titleDialog;
switch (id) {
case id:
titleDialog = itemTitle;
messageDialog = itemDescription
valueOK = "OK";
return new AlertDialog.Builder(HomeView.this).setTitle(titleDialog).setPositiveButton(valueOK, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Log.d(this.getClass().getName(), "AlertItem");
}
}).setMessage(messageDialog).create();
and then call to
showDialog(numbreOfItem);
Here's a little cmd script you can copy-n-paste into a file named something like where.cmd
:
@echo off
rem - search for the given file in the directories specified by the path, and display the first match
rem
rem The main ideas for this script were taken from Raymond Chen's blog:
rem
rem http://blogs.msdn.com/b/oldnewthing/archive/2005/01/20/357225.asp
rem
rem
rem - it'll be nice to at some point extend this so it won't stop on the first match. That'll
rem help diagnose situations with a conflict of some sort.
rem
setlocal
rem - search the current directory as well as those in the path
set PATHLIST=.;%PATH%
set EXTLIST=%PATHEXT%
if not "%EXTLIST%" == "" goto :extlist_ok
set EXTLIST=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
:extlist_ok
rem - first look for the file as given (not adding extensions)
for %%i in (%1) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i
rem - now look for the file adding extensions from the EXTLIST
for %%e in (%EXTLIST%) do @for %%i in (%1%%e) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i
I have created a custom regex to deal with names:
I have tried these types of names and found working perfect
My RegEx looks like this:
^([a-zA-Z]{2,}\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\s?([a-zA-Z]{1,})?)
MVC4 Model:
[RegularExpression("^([a-zA-Z]{2,}\\s[a-zA-Z]{1,}'?-?[a-zA-Z]{2,}\\s?([a-zA-Z]{1,})?)", ErrorMessage = "Valid Charactors include (A-Z) (a-z) (' space -)") ]
Please note the double \\
for escape characters
For those of you that are new to RegEx I thought I'd include a explanation.
^ // start of line
[a-zA-Z]{2,} // will except a name with at least two characters
\s // will look for white space between name and surname
[a-zA-Z]{1,} // needs at least 1 Character
\'?-? // possibility of **'** or **-** for double barreled and hyphenated surnames
[a-zA-Z]{2,} // will except a name with at least two characters
\s? // possibility of another whitespace
([a-zA-Z]{1,})? // possibility of a second surname
ModelState.IsValid
tells you if any model errors have been added to ModelState
.
The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.
The sample DataAnnotations
model binder will fill model state with validation errors taken from the DataAnnotations
attributes on your model.
This is what you are looking for:
^((?!(abc|def)).)*$
the explanation is here: Regular expression to match a line that doesn't contain a word?
This link explains where you're going wrong:
Place the definition of your constructors, destructors methods and whatnot in your header file, and that will correct the problem.
This offers another solution:
How can I avoid linker errors with my template functions?
However this requires you to anticipate how your template will be used and, as a general solution, is counter-intuitive. It does solve the corner case though where you develop a template to be used by some internal mechanism, and you want to police the manner in which it is used.
data = numpy.asarray(im)
Notice:In PIL, img is RGBA. In cv2, img is BGRA.
My robust solution:
def cv_from_pil_img(pil_img):
assert pil_img.mode=="RGBA"
return cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGBA2BGRA)
If you are using Java 9+, you can use ifPresentOrElse()
method:
opt.ifPresentOrElse(
value -> System.out.println("Found: " + value),
() -> System.out.println("Not found")
);
private boolean isPasswordVisible;
private TextInputEditText firstEditText;
...
firstEditText = findViewById(R.id.et_first);
...
private void togglePassVisability() {
if (isPasswordVisible) {
String pass = firstEditText.getText().toString();
firstEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
firstEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
firstEditText.setText(pass);
firstEditText.setSelection(pass.length());
} else {
String pass = firstEditText.getText().toString();
firstEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
firstEditText.setInputType(InputType.TYPE_CLASS_TEXT);
firstEditText.setText(pass);
firstEditText.setSelection(pass.length());
}
isPasswordVisible= !isPasswordVisible;
}
As it was already mentioned here Callable is relatively new interface and it was introduced as a part of concurrency package. Both Callable and Runnable can be used with executors. Class Thread (that implements Runnable itself) supports Runnable only.
You can still use Runnable with executors. The advantage of Callable that you can send it to executor and immediately get back Future result that will be updated when the execution is finished. The same may be implemented with Runnable, but in this case you have to manage the results yourself. For example you can create results queue that will hold all results. Other thread can wait on this queue and deal with results that arrive.
"this" is all about scope. Every function has its own scope, and since everything in JS is an object, even a function can store some values into itself using "this". OOP 101 teaches that "this" is only applicable to instances of an object. Therefore, every-time a function executes, a new "instance" of that function has a new meaning of "this".
Most people get confused when they try to use "this" inside of anonymous closure functions like:
(function(value) { this.value = value; $('.some-elements').each(function(elt){ elt.innerHTML = this.value; // uh oh!! possibly undefined }); })(2);
So here, inside each(), "this" doesn't hold the "value" that you expect it to (from
this.value = value;above it). So, to get over this (no pun intended) problem, a developer could:
(function(value) { var self = this; // small change self.value = value; $('.some-elements').each(function(elt){ elt.innerHTML = self.value; // phew!! == 2 }); })(2);
Try it out; you'll begin to like this pattern of programming
Other way we can create a function to control "using multiple class"
CSS
<style>
.Red {
color: Red;
}
.Yellow {
color: Yellow;
}
.Blue {
color: Blue;
}
.Green {
color: Green;
}
.Gray {
color: Gray;
}
.b {
font-weight: bold;
}
</style>
Script
<script>
angular.module('myapp', [])
.controller('ExampleController', ['$scope', function ($scope) {
$scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
$scope.getClass = function (strValue) {
if (strValue == ("It is Red"))
return "Red";
else if (strValue == ("It is Yellow"))
return "Yellow";
else if (strValue == ("It is Blue"))
return "Blue";
else if (strValue == ("It is Green"))
return "Green";
else if (strValue == ("It is Gray"))
return "Gray";
}
}]);
</script>
Using it
<body ng-app="myapp" ng-controller="ExampleController">
<h2>AngularJS ng-class if example</h2>
<ul >
<li ng-repeat="icolor in MyColors" >
<p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
</li>
</ul>
You can refer to full code page at ng-class if example
It depends on the scope of the project that you're working on. In the context of your question, and I mean just your question, then it doesn't matter.
For a further explanation (optional), some scenarios I have noticed from this whole discussion is as follow:
(1) - If you're working in an embedded environment where you cannot rely on the main OS' to reclaim the memory for you, then you should free them since memory leaks can really crash the program if done unnoticed.
(2) - If you're working on a personal project where you won't disclose it to anyone else, then you can skip it (assuming you're using it on the main OS') or include it for "best practices" sake.
(3) - If you're working on a project and plan to have it open source, then you need to do more research into your audience and figure out if freeing the memory would be the better choice.
(4) - If you have a large library and your audience consisted of only the main OS', then you don't need to free it as their OS' will help them to do so. In the meantime, by not freeing, your libraries/program may help to make the overall performance snappier since the program does not have to close every data structure, prolonging the shutdown time (imagine a very slow excruciating wait to shut down your computer before leaving the house...)
I can go on and on specifying which course to take, but it ultimately depends on what you want to achieve with your program. Freeing memory is considered good practice in some cases and not so much in some so it ultimately depends on the specific situation you're in and asking the right questions at the right time. Good luck!
subprocess.Popen: http://docs.python.org/2/library/subprocess.html#subprocess.Popen
import subprocess
command = "ntpq -p" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None, shell=True)
#Launch the shell command:
output = process.communicate()
print output[0]
In the Popen constructor, if shell is True, you should pass the command as a string rather than as a sequence. Otherwise, just split the command into a list:
command = ["ntpq", "-p"] # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=None)
If you need to read also the standard error, into the Popen initialization, you can set stderr to subprocess.PIPE or to subprocess.STDOUT:
import subprocess
command = "ntpq -p" # the shell command
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
#Launch the shell command:
output, error = process.communicate()
Using query-string module is the recommended one when you need a module to parse your query string in ease.
componentWillMount() {
var query = queryString.parse(this.props.location.search);
if (query.token) {
window.localStorage.setItem("jwt", query.token);
store.dispatch(push("/"));
}
}
Here, I am redirecting back to my client from Node.js server after successful Google-Passport authentication, which is redirecting back with token as query param.
I am parsing it with query-string module, saving it and updating the query params in the url with push from react-router-redux.
What happens here is that the the vendored versions of request/urllib3 clash when imported in two different places (same code, but different names). If you then have a network error, it doesn't retry to get the wheel, but fails with the above error. See here for a deeper dive into this error.
For the solution with system pip, see above.
If you have this problem in a virtualenv built by python -m venv
(which still copies the wheels from /usr/share/python-wheels
, even if you have pip installed separately), the easiest way to "fix" it seems to be:
/usr/bin/python3.6 -m venv ...
requests
into the environment (this might raise the above error): <venv>/bin/pip install requests
requests
which would be used by pip: rm <venv>/share/python-wheels/{requests,chardet,urllib3}-*.whl
Now a <venv>/bin/pip
uses the installed version of requests
which has urllib3 vendored.
Consider using <span>
to isolate small segments of markup to be styled without breaking up layout. This would seem to be more idiomatic than trying to force a <div>
not to display itself--if in fact the checkbox itself cannot be styled in the way you want.
where java
works for me to list all java exe but java -verbose
tells you which rt.jar
is used and thus which jre (full path):
[Opened C:\Program Files\Java\jre6\lib\rt.jar]
...
Edit: win7 and java:
java version "1.6.0_20"
Java(TM) SE Runtime Environment (build 1.6.0_20-b02)
Java HotSpot(TM) 64-Bit Server VM (build 16.3-b01, mixed mode)
You can use auto margins
Prior to alignment via
justify-content
andalign-self
, any positive free space is distributed to auto margins in that dimension.
So you can use one of these (or both):
p { margin-bottom: auto; } /* Push following elements to the bottom */
a { margin-top: auto; } /* Push it and following elements to the bottom */
.content {_x000D_
height: 200px;_x000D_
border: 1px solid;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
h1, h2 {_x000D_
margin: 0;_x000D_
}_x000D_
a {_x000D_
margin-top: auto;_x000D_
}
_x000D_
<div class="content">_x000D_
<h1>heading 1</h1>_x000D_
<h2>heading 2</h2>_x000D_
<p>Some text more or less</p>_x000D_
<a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
Alternatively, you can make the element before the a
grow to fill the available space:
p { flex-grow: 1; } /* Grow to fill available space */
.content {_x000D_
height: 200px;_x000D_
border: 1px solid;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
h1, h2 {_x000D_
margin: 0;_x000D_
}_x000D_
p {_x000D_
flex-grow: 1;_x000D_
}
_x000D_
<div class="content">_x000D_
<h1>heading 1</h1>_x000D_
<h2>heading 2</h2>_x000D_
<p>Some text more or less</p>_x000D_
<a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
I spend days together to figure out this issue. I know its late but this might be helpful:
I resolved this issue by changing the compatible/stable version of:
Spring boot: 2.1.1
Spring Data Elastic: 2.1.4
Elastic: 6.4.0 (default)
Maven:
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
</dependency>
You don't need to mention Elastic version. By default it is 6.4.0. But if you want to add a specific verison. Use below snippet inside properties tag and use the compatible version of Spring Boot and Spring Data(if required)
<properties>
<elasticsearch.version>6.8.0</elasticsearch.version>
</properties>
Also, I used the Rest High Level client in ElasticConfiguration :
@Value("${elasticsearch.host}")
public String host;
@Value("${elasticsearch.port}")
public int port;
@Bean(destroyMethod = "close")
public RestHighLevelClient restClient1() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
Important Note: Elastic use 9300 port to communicate between nodes and 9200 as HTTP client. In application properties:
elasticsearch.host=10.40.43.111
elasticsearch.port=9200
spring.data.elasticsearch.cluster-nodes=10.40.43.111:9300 (customized Elastic server)
spring.data.elasticsearch.cluster-name=any-cluster-name (customized cluster name)
From Postman, you can use: http://10.40.43.111:9200/[indexname]/_search
Happy coding :)
The only reason that the linter complains about using setState({..})
in componentDidMount
and componentDidUpdate
is that when the component render the setState immediately causes the component to re-render.
But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.
Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.
this works too.
df = NULL
for (k in 1:10)
{
x = 1
y = 2
z = 3
df = rbind(df, data.frame(x,y,z))
}
output will look like this
df #enter
x y z #col names
1 2 3
The reason is because a FileStream is returned from your method to create a file. You should return the FileStream into a variable or call the close method directly from it after the File.Create.
It is a best practice to let the using block help you implement the IDispose pattern for a task like this. Perhaps what might work better would be:
if(!File.Exists(myPath)){
using(FileStream fs = File.Create(myPath))
using(StreamWriter writer = new StreamWriter(fs)){
// do your work here
}
}
This is similar to some of the above answers, but with this, you can specify if you want to remove rows with a percentage of missing values greater-than or equal-to a given percent (with the argument pct
)
drop_rows_all_na <- function(x, pct=1) x[!rowSums(is.na(x)) >= ncol(x)*pct,]
Where x
is a dataframe and pct
is the threshold of NA
-filled data you want to get rid of.
pct = 1
means remove rows that have 100% of its values NA
.
pct = .5
means remome rows that have at least half its values NA
Assuming you want to change the url to another within the same domain, you can use this:
history.pushState('data', '', 'http://www.yourcurrentdomain.com/new/path');
There are basically two alternatives, using setLength(0)
to reset the StringBuilder or creating a new one in each iteration. Both can have pros and cons depending on the usage.
If you know the expected capacity of the StringBuilder beforehand, creating a new one each time should be just as fast as setting a new length. It will also help the garbage collector, since each StringBuilder will be relatively short-lived and the gc is optimized for that.
When you don't know the capacity, reusing the same StringBuilder might be faster. Each time you exceed the capacity when appending, a new backing array has to be allocated and the previous content has to be copied. By reusing the same StringBuilder, it will reach the needed capacity after some iterations and there won't be any copying thereafter.
So this is probably waaaaaay late to the party but the actual problem is an error or rather the repetition of the same error in three batch files.
C:\Program Files(x86)\Microsoft Visual Studio 10.0\Common7\Tools\VCVarsQueryRegistry.bat
C:\Program Files(x86)\Microsoft Visual Studio 10.0\Common7\Tools\vsvars32.bat
C:\Program Files(x86)\Microsoft Visual Studio 10.0\VC\bin\vcvars32.bat
The pattern of the error is everywhere a for loop is used to loop through registry values. It looks like this:
@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO (
@if "%%i"=="10.0" (
@SET "VS100COMNTOOLS=%%k"
)
)
The problem is the second occurrence of %%i. The way the loop construct works is the first %% variable is the first token, the next is the second and so on. So the second %%i should be a %%j (or whatever you want) so that it points to the value that would possibly be a "10.0". You can tell the developer wanted to use i,j,k as the values because in the enclosed @SET in the if, they use %%k. Which would be the path.
So, in short, go through all these types of loops in the three files above and change the second occurrence of %%i to %%k and everything will work like it's supposed to. So it should look like this:
@for /F "tokens=1,2*" %%i in ('reg query "%1\SOFTWARE\Microsoft\VisualStudio\SxS\VS7" /v "10.0"') DO (
@if "%%j"=="10.0" (
@SET "VS100COMNTOOLS=%%k"
)
)
Hope this helps. Not sure if this applies to all versions. I only know that it does apply to VS 2010 (SP1).
All these theoretical discussions are great, but in reality, at least if you're using MySQL and really for SQLServer as well, it's best to stick with non-binary data for your booleans for the simple reason that it's easier to work with when you're outputting the data, querying and so on. It is especially important if you're trying to achieve interoperability between MySQL and SQLServer (i.e. you sync data between the two), because the handling of BIT datatype is different in the two of them. SO in practice you will have a lot less hassles if you stick with a numeric datatype. I would recommend for MySQL to stick with BOOL or BOOLEAN which gets stored as TINYINT(1). Even the way MySQL Workbench and MySQL Administrator display the BIT datatype isn't nice (it's a little symbol for binary data). So be practical and save yourself the hassles (and unfortunately I'm speaking from experience).
The '\r' stands for "Carriage Return" - it's a holdover from the days of typewriters and really old printers. The best example is in Windows and other DOSsy OSes, where a newline is given as "\r\n". These are the instructions sent to an old printer to start a new line: first move the print head back to the beginning, then go down one.
Different OSes will use other newline sequences. Linux and OSX just use '\n'. Older Mac OSes just use '\r'. Wikipedia has a more complete list, but those are the important ones.
Hope this helps!
PS: As for why you get that weird output... Perhaps the console is moving the "cursor" back to the beginning of the line, and then overwriting the first bit with spaces or summat.
See https://devcenter.heroku.com/articles/git#deploying-code
$ git push heroku yourbranch:master
I used vw
(viewport width) and vh
(viewport height). viewport is your entire screen. 100vw
is your screens total width and 100vh
is total height.
.class_name{
width: 50vw;
height: 50vh;
border: 1px solid red;
position: fixed;
left: 25vw;top: 25vh;
}
Short answer:
In common use, space " "
, Tab "\t"
and newline "\n"
are the difference:
string.IsNullOrWhiteSpace("\t"); //true
string.IsNullOrEmpty("\t"); //false
string.IsNullOrWhiteSpace(" "); //true
string.IsNullOrEmpty(" "); //false
string.IsNullOrWhiteSpace("\n"); //true
string.IsNullOrEmpty("\n"); //false
https://dotnetfiddle.net/4hkpKM
also see this answer about: whitespace characters
Long answer:
There are also a few other white space characters, you probably never used before
https://docs.microsoft.com/en-us/dotnet/api/system.char.iswhitespace
Node.js
introduced async await
in 7.6
so this makes Javascript
more beautiful.
var results = [];
var config = JSON.parse(queries);
for (var key in config) {
var query = config[key].query;
results.push(await search(query));
}
res.writeHead( ... );
res.end(results);
For this to work search
fucntion has to return a promise
or it has to be async
function
If it is not returning a Promise
you can help it to return a Promise
function asyncSearch(query) {
return new Promise((resolve, reject) => {
search(query,(result)=>{
resolve(result);
})
})
}
Then replace this line await search(query);
by await asyncSearch(query);
Use
label.setOpaque(true);
Otherwise the background is not painted, since the default of opaque
is false
for JLabel
.
From the JavaDocs:
If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.
For more information, read the Java Tutorial How to Use Labels.
This worked for me and includes using OutputStream:
PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
Rectangle size = reader.GetPageSizeWithRotation(1);
using (Stream outStream = Response.OutputStream)
{
Document document = new Document(size);
PdfWriter writer = PdfWriter.GetInstance(document, outStream);
document.Open();
try
{
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
try
{
cb.SetFontAndSize(BaseFont.CreateFont(), 12);
cb.SetTextMatrix(110, 110);
cb.ShowText("aaa");
}
finally
{
cb.EndText();
}
PdfImportedPage page = writer.GetImportedPage(reader, 1);
cb.AddTemplate(page, 0, 0);
}
finally
{
document.Close();
writer.Close();
reader.Close();
}
}
You can use object-fit
css3 property, something like
<!doctype html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<meta charset='utf-8'>_x000D_
<style>_x000D_
.holder {_x000D_
display: inline;_x000D_
}_x000D_
.holder img {_x000D_
max-height: 200px;_x000D_
max-width: 200px;_x000D_
object-fit: cover;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div class='holder'>_x000D_
<img src='meld.png'>_x000D_
</div>_x000D_
<div class='holder'>_x000D_
<img src='twiddla.png'>_x000D_
</div>_x000D_
<div class='holder'>_x000D_
<img src='meld.png'>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
It is not exactly your answer, though, because of it doesn't stretch the container, but it behaves like the gallery and you can keep styling the img
itself.
Another drawback of this solution is still a poor support of the css3 property. More details are available here: http://www.steveworkman.com/html5-2/javascript/2012/css3-object-fit-polyfill/. jQuery solution can be found there as well.
use jquery : $("#id").css("background","red");
setup.py
is a Python file like any other. It can take any name, except by convention it is named setup.py
so that there is not a different procedure with each script.
Most frequently setup.py
is used to install a Python module but server other purposes:
Modules:
Perhaps this is most famous usage of setup.py
is in modules. Although they can be installed using pip
, old Python versions did not include pip
by default and they needed to be installed separately.
If you wanted to install a module but did not want to install pip
, just about the only alternative was to install the module from setup.py
file. This could be achieved via python setup.py install
. This would install the Python module to the root dictionary (without pip
, easy_install
ect).
This method is often used when pip
will fail. For example if the correct Python version of the desired package is not available via pip
perhaps because it is no longer maintained, , downloading the source and running python setup.py install
would perform the same thing, except in the case of compiled binaries are required, (but will disregard the Python version -unless an error is returned).
Another use of setup.py
is to install a package from source. If a module is still under development the wheel files will not be available and the only way to install is to install from the source directly.
Building Python extensions:
When a module has been built it can be converted into module ready for distribution using a distutils setup script. Once built these can be installed using the command above.
A setup script is easy to build and once the file has been properly configured and can be compiled by running python setup.py build
(see link for all commands).
Once again it is named setup.py
for ease of use and by convention, but can take any name.
Cython:
Another famous use of setup.py
files include compiled extensions. These require a setup script with user defined values. They allow fast (but once compiled are platform dependant) execution. Here is a simple example from the documentation:
from distutils.core import setup
from Cython.Build import cythonize
setup(
name = 'Hello world app',
ext_modules = cythonize("hello.pyx"),
)
This can be compiled via python setup.py build
Cx_Freeze:
Another module requiring a setup script is cx_Freeze
. This converts Python script to executables. This allows many commands such as descriptions, names, icons, packages to include, exclude ect and once run will produce a distributable application. An example from the documentation:
import sys
from cx_Freeze import setup, Executable
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}
base = None
if sys.platform == "win32":
base = "Win32GUI"
setup( name = "guifoo",
version = "0.1",
description = "My GUI application!",
options = {"build_exe": build_exe_options},
executables = [Executable("guifoo.py", base=base)])
This can be compiled via python setup.py build
.
So what is a setup.py
file?
Quite simply it is a script that builds or configures something in the Python environment.
A package when distributed should contain only one setup script but it is not uncommon to combine several together into a single setup script. Notice this often involves distutils
but not always (as I showed in my last example). The thing to remember it just configures Python package/script in some way.
It takes the name so the same command can always be used when building or installing.
For reference using the [EnableCors()]
approach will not work if you intercept the Message Pipeline using a DelegatingHandler
. In my case was checking for an Authorization
header in the request and handling it accordingly before the routing was even invoked, which meant my request was getting processed earlier in the pipeline so the [EnableCors()]
had no effect.
In the end found an example CrossDomainHandler
class (credit to shaunxu for the Gist) which handles the CORS for me in the pipeline and to use it is as simple as adding another message handler to the pipeline.
public class CrossDomainHandler : DelegatingHandler
{
const string Origin = "Origin";
const string AccessControlRequestMethod = "Access-Control-Request-Method";
const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
bool isCorsRequest = request.Headers.Contains(Origin);
bool isPreflightRequest = request.Method == HttpMethod.Options;
if (isCorsRequest)
{
if (isPreflightRequest)
{
return Task.Factory.StartNew(() =>
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
if (accessControlRequestMethod != null)
{
response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
}
string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
if (!string.IsNullOrEmpty(requestedHeaders))
{
response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
}
return response;
}, cancellationToken);
}
else
{
return base.SendAsync(request, cancellationToken).ContinueWith(t =>
{
HttpResponseMessage resp = t.Result;
resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
return resp;
});
}
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
To use it add it to the list of registered message handlers
config.MessageHandlers.Add(new CrossDomainHandler());
Any preflight requests by the Browser are handled and passed on, meaning I didn't need to implement an [HttpOptions]
IHttpActionResult
method on the Controller.
I think this is the best way:
this.stops.stream().filter(s -> Objects.equals(s.getStation().getName(), this.name)).findFirst().orElse(null);
Search (Ctrl+F) your harddrive(s) for: SDK Manager.exe or adb.exe
This worked for me in Luna elementary OS
sudo apt-get install libxtst6:i386
In order to maintain for numerical stability, max(x) should be subtracted. The following is the code for softmax function;
def softmax(x):
if len(x.shape) > 1:
tmp = np.max(x, axis = 1)
x -= tmp.reshape((x.shape[0], 1))
x = np.exp(x)
tmp = np.sum(x, axis = 1)
x /= tmp.reshape((x.shape[0], 1))
else:
tmp = np.max(x)
x -= tmp
x = np.exp(x)
tmp = np.sum(x)
x /= tmp
return x
Use LXML. LXML uses the full power of libxml2 and libxslt, but wraps them in more "Pythonic" bindings than the Python bindings that are native to those libraries. As such, it gets the full XPath 1.0 implementation. Native ElemenTree supports a limited subset of XPath, although it may be good enough for your needs.
If you have more numbers or if you intend to add new test numbers for CASE
then you can use a more flexible approach:
DECLARE @Numbers TABLE
(
Number VARCHAR(50) PRIMARY KEY
,Class TINYINT NOT NULL
);
INSERT @Numbers
VALUES ('1121231',1);
INSERT @Numbers
VALUES ('31242323',1);
INSERT @Numbers
VALUES ('234523',2);
INSERT @Numbers
VALUES ('2342423',2);
SELECT c.*, n.Class
FROM tblClient c
LEFT OUTER JOIN @Numbers n ON c.Number = n.Number;
Also, instead of table variable you can use a regular table.
A good idea is to set all of the "" (blank cells) to NA before any further analysis.
If you are reading your input from a file, it is a good choice to cast all "" to NAs:
foo <- read.table(file="Your_file.txt", na.strings=c("", "NA"), sep="\t") # if your file is tab delimited
If you have already your table loaded, you can act as follows:
foo[foo==""] <- NA
Then to keep only rows with no NA you may just use na.omit()
:
foo <- na.omit(foo)
Or to keep columns with no NA:
foo <- foo[, colSums(is.na(foo)) == 0]
On the basic example of Flutter you can set with backgroundColor: Colors.X
of Scaffold
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
backgroundColor: Colors.blue,
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add_circle),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
On strings and memory allocation:
A string in C is just a sequence of char
s, so you can use char *
or a char
array wherever you want to use a string data type:
typedef struct {
int number;
char *name;
char *address;
char *birthdate;
char gender;
} patient;
Then you need to allocate memory for the structure itself, and for each of the strings:
patient *createPatient(int number, char *name,
char *addr, char *bd, char sex) {
// Allocate memory for the pointers themselves and other elements
// in the struct.
patient *p = malloc(sizeof(struct patient));
p->number = number; // Scalars (int, char, etc) can simply be copied
// Must allocate memory for contents of pointers. Here, strdup()
// creates a new copy of name. Another option:
// p->name = malloc(strlen(name)+1);
// strcpy(p->name, name);
p->name = strdup(name);
p->address = strdup(addr);
p->birthdate = strdup(bd);
p->gender = sex;
return p;
}
If you'll only need a few patient
s, you can avoid the memory management at the expense of allocating more memory than you really need:
typedef struct {
int number;
char name[50]; // Declaring an array will allocate the specified
char address[200]; // amount of memory when the struct is created,
char birthdate[50]; // but pre-determines the max length and may
char gender; // allocate more than you need.
} patient;
On linked lists:
In general, the purpose of a linked list is to prove quick access to an ordered collection of elements. If your llist
contains an element called num
(which presumably contains the patient number), you need an additional data structure to hold the actual patient
s themselves, and you'll need to look up the patient number every time.
Instead, if you declare
typedef struct llist
{
patient *p;
struct llist *next;
} list;
then each element contains a direct pointer to a patient
structure, and you can access the data like this:
patient *getPatient(list *patients, int num) {
list *l = patients;
while (l != NULL) {
if (l->p->num == num) {
return l->p;
}
l = l->next;
}
return NULL;
}
From what I tested:
Session.Abandon(); // Does nothing
Session.Clear(); // Removes the data contained in the session
Example:
001: Session["test"] = "test";
002: Session.Abandon();
003: Print(Session["test"]); // Outputs: "test"
Session.Abandon does only set a boolean flag in the session-object to true. The calling web-server may react to that or not, but there is NO immediate action caused by ASP. (I checked that myself with the .net-Reflector)
In fact, you can continue working with the old session, by hitting the browser's back button once, and continue browsing across the website normally.
So, to conclude this: Use Session.Clear() and save frustration.
Remark: I've tested this behaviour on the ASP.net development server. The actual IIS may behave differently.
Here is an example of how you could do this. Note that I was inspired by a comment in the ng-repeat docs: http://jsfiddle.net/digitalzebra/wnWY6/
Note the ng-repeat directive:
<div ng-app>
<div ng-controller="TestCtrl">
<div ng-repeat="a in range(5) track by $index">{{$index + 1}}</div>
</div>
</div>
Here is the controller:
function TestCtrl($scope) {
$scope.range = function(n) {
return new Array(n);
};
};
It may be bacause you do not have jre installed. Thus go to http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html and download it.
integer excract from any string
$in = 'tel.123-12-33';
preg_match_all('!\d+!', $in, $matches);
$out = (int)implode('', $matches[0]);
//$out ='1231233';
There are two ways to delete an application you have uploaded from the Google Play Developer Console based off of the application's status within the Console. An app's status can be viewed from the "All Applications" tab listed in the furthest column. (See below)
Select your app from the list and at the top of the page, underneath your application name, it will say DRAFT in blue with the super low-profile option to delete it just to the right. Observe below:
Click that and you're done! Keep in mind: all of the work you have put into this application so far will be deleted from the Google Play Developer Console.
This method is similar, however it should be noted that it is not possible to permanently delete an app from your Developer Console once it has been published to the Play Store.
1) Select the application you would like to publish from the "All Applications" tab on the right of the screen
2) Below the title of the app, similar to how it was with the DRAFT application, there will be super low-profile text allowing you the option to unpublish your app from the Play Store. This process "may take a few hours to complete" as it is said by the Developer Console.
(Pictures on the way. As you have seen, my example app is still pending publication, lol)
I hope this helps to answer some people's questions.
@John, Earlz and Nathan. The way I learned it at uni is: functions return values, methods don't. In some languages the syntax is/was actually different. Example (no specific language):
Method SetY(int y) ...
Function CalculateY(int x) As Integer ...
Most languages now use the same syntax for both versions, using void as a return type to say there actually isn't a return type. I assume it's because the syntax is more consistent and easier to change from method to function, and vice versa.
Simple! The folder named ..
is the parent folder, so you can make the path to the file you need as such
var foobar = require('../config/dev/foobar.json');
If you needed to go up two levels, you would write ../../
etc
Some more details about this in this SO answer and it's comments
dashed
border style for outline.background-color
with :before
or :after
pseudo element.Note: This method will allow you to have maximum browser support.
Output Image:
* {box-sizing: border-box;}_x000D_
_x000D_
.box {_x000D_
border: 1px dashed #fff;_x000D_
position: relative;_x000D_
height: 160px;_x000D_
width: 350px;_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.box:before {_x000D_
position: absolute;_x000D_
background: black;_x000D_
content: '';_x000D_
bottom: -10px;_x000D_
right: -10px;_x000D_
left: -10px;_x000D_
top: -10px;_x000D_
z-index: -1;_x000D_
}
_x000D_
<div class="box">_x000D_
_x000D_
</div>
_x000D_
Adding the - will order it in descending order. You can also set this by adding a default ordering to the meta of your model. This will mean that when you do a query you just do MyModel.objects.all() and it will come out in the correct order.
class MyModel(models.Model):
check_in = models.DateField()
class Meta:
ordering = ('-check_in',)