.icon {
width: 48px;
height: 48px;
display: inline-block;
background: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/18515/heart.svg) no-repeat 50% 50%;
background-size: cover;
}
.icon-orange {
-webkit-filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4);
filter: hue-rotate(40deg) saturate(0.5) brightness(390%) saturate(4);
}
.icon-yellow {
-webkit-filter: hue-rotate(70deg) saturate(100);
filter: hue-rotate(70deg) saturate(100);
}
For bitbucket repository, generate App Password (Bitbucket settings -> Access Management -> App Password, see the image) with read access to the repo and project.
Then the command that you should use is:
git clone https://username:[email protected]/reponame/projectname.git
// Following is angular 2.0 directive for window re size that adjust scroll bar for give element as per your tag
---- angular 2.0 window resize directive.
import { Directive, ElementRef} from 'angular2/core';
@Directive({
selector: '[resize]',
host: { '(window:resize)': 'onResize()' } // Window resize listener
})
export class AutoResize {
element: ElementRef; // Element that associated to attribute.
$window: any;
constructor(_element: ElementRef) {
this.element = _element;
// Get instance of DOM window.
this.$window = angular.element(window);
this.onResize();
}
// Adjust height of element.
onResize() {
$(this.element.nativeElement).css('height', (this.$window.height() - 163) + 'px');
}
}
Here's a very simple free open-source CsvExport class for C#. There's an ASP.NET MVC example at the bottom.
https://github.com/jitbit/CsvExport
It takes care about line-breaks, commas, escaping quotes, MS Excel compatibilty... Just add one short .cs
file to your project and you're good to go.
(disclaimer: I'm one of the contributors)
Install the wheel
package first:
pip install wheel
The documentation isn't overly clear on this, but "the wheel project provides a bdist_wheel command for setuptools" actually means "the wheel package...".
I'm using this tutorial and it works nicely for my application.
In my activity I put this code:
GPSTracker tracker = new GPSTracker(this);
if (!tracker.canGetLocation()) {
tracker.showSettingsAlert();
} else {
latitude = tracker.getLatitude();
longitude = tracker.getLongitude();
}
also check if your emulator runs with Google API
If possible, you may want to use IPython.
To get a list of all current user-defined variables, IPython provides a magic command named who
(magics must be prefixed with the modulo character unless the automagic
feature is enabled):
In [1]: foo = 'bar'
In [2]: %who
foo
You can use the whos
magic to get more detail:
In [3]: %whos
Variable Type Data/Info
----------------------------
foo str bar
There are a wealth of other magics available. IPython is basically the Python interpreter on steroids. One convenient magic is store
, which lets you save variables between sessions (using pickle
).
Note: I am not associated with IPython Dev - just a satisfied user.
Edit:
You can find all the magic commands in the IPython Documentation.
This article also has a helpful section on the use of magic commands in Jupyter Notebook
Use datetime.datetime.fromtimestamp
:
>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'
%f
directive is only supported by datetime.datetime.strftime
, not by time.strftime
.
UPDATE Alternative using %
, str.format
:
>>> import time
>>> s, ms = divmod(1236472051807, 1000) # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
Is the following acceptable:
$('#myTableRow').remove();
Delete the .xap file if your breakpoint aren't being hit. Inside YourProject.Web/ClientBin Delete YourProject.xap. I've have tried all above and stumble across this fix, works everytime. Wise to clean the project after deleting as well.
On my case, just to be safe regarding scrolling, I added the window.scroll to the equation:
var element = document.getElementById('myElement');
var topPos = element.getBoundingClientRect().top + window.scrollY;
var leftPos = element.getBoundingClientRect().left + window.scrollX;
That allows me to get the real relative position of element on document, even if it has been scrolled.
I'm guessing that you want something like
SELECT tab1.a, tab2.b, tab3.c, tab4.d
FROM table1 tab1
JOIN table2 tab2 ON (tab1.fg = tab2.fg)
LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
tab3.dd = tab5.dd)
The SQLite documentation is a great reference and the DateAndTimeFunctions page is a good one to bookmark.
It's also helpful to remember that it's pretty easy to play with queries with the sqlite command line utility:
sqlite> select julianday(datetime('now'));
2454788.09219907
sqlite> select datetime(julianday(datetime('now')));
2008-11-17 14:13:55
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5
. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash()
of $md5.ComputeHash()
was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.
You can do this :
//Create an Array of type ArrayList
`ArrayList<Integer>[] a = new ArrayList[n];`
//For each element in array make an ArrayList
for(int i=0; i<n; i++){
a[i] = new ArrayList<Integer>();
}
def ipcheck():
# 1.Validate the ip adderess
input_ip = input('Enter the ip:')
flag = 0
pattern = "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}$"
match = re.match(pattern, input_ip)
if (match):
field = input_ip.split(".")
for i in range(0, len(field)):
if (int(field[i]) < 256):
flag += 1
else:
flag = 0
if (flag == 4):
print("valid ip")
else:
print('No match for ip or not a valid ip')
There are two problems on our way to the absolute path:
The following code will give us all useful paths:
URL localPackage = this.getClass().getResource("");
URL urlLoader = YourClassName.class.getProtectionDomain().getCodeSource().getLocation();
String localDir = localPackage.getPath();
String loaderDir = urlLoader.getPath();
System.out.printf("loaderDir = %s\n localDir = %s\n", loaderDir, localDir);
Here both functions that can be used for localization of the resource folder are researched. As for class
, it can be got in either way, statically or dynamically.
If the project is not in the plugin, the code if run in JUnit, will print:
loaderDir = /C:.../ws/source.dir/target/test-classes/
localDir = /C:.../ws/source.dir/target/test-classes/package/
So, to get to src/rest/resources we should go up and down the file tree. Both methods can be used. Notice, we can't use getResource(resourceFolderName)
, for that folder is not in the target folder. Nobody puts resources in the created folders, I hope.
If the class is in the package that is in the plugin, the output of the same test will be:
loaderDir = /C:.../ws/plugin/bin/
localDir = /C:.../ws/plugin/bin/package/
So, again we should go up and down the folder tree.
The most interesting is the case when the package is launched in the plugin. As JUnit plugin test, for our example. The output is:
loaderDir = /C:.../ws/plugin/
localDir = /package/
Here we can get the absolute path only combining the results of both functions. And it is not enough. Between them we should put the local path of the place where the classes packages are, relatively to the plugin folder. Probably, you will have to insert something as src
or src/test/resource
here.
You can insert the code into yours and see the paths that you have.
For Apache HttpClient 4.5 or newer version:
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://targethost/login");
String JSON_STRING="";
HttpEntity stringEntity = new StringEntity(JSON_STRING,ContentType.APPLICATION_JSON);
httpPost.setEntity(stringEntity);
CloseableHttpResponse response2 = httpclient.execute(httpPost);
Note:
1 in order to make the code compile, both httpclient
package and httpcore
package should be imported.
2 try-catch block has been ommitted.
Reference: appache official guide
the Commons HttpClient project is now end of life, and is no longer being developed. It has been replaced by the Apache HttpComponents project in its HttpClient and HttpCore modules
You can edit this in your storyboard (if you are using one). Under the table view there is a checkbox that says "Scrolling Enabled". Uncheck it and you're done.
Linq With Or Condition by using Lambda expression you can do as below
DataTable dtEmp = new DataTable();
dtEmp.Columns.Add("EmpID", typeof(int));
dtEmp.Columns.Add("EmpName", typeof(string));
dtEmp.Columns.Add("Sal", typeof(decimal));
dtEmp.Columns.Add("JoinDate", typeof(DateTime));
dtEmp.Columns.Add("DeptNo", typeof(int));
dtEmp.Rows.Add(1, "Rihan", 10000, new DateTime(2001, 2, 1), 10);
dtEmp.Rows.Add(2, "Shafi", 20000, new DateTime(2000, 3, 1), 10);
dtEmp.Rows.Add(3, "Ajaml", 25000, new DateTime(2010, 6, 1), 10);
dtEmp.Rows.Add(4, "Rasool", 45000, new DateTime(2003, 8, 1), 20);
dtEmp.Rows.Add(5, "Masthan", 22000, new DateTime(2001, 3, 1), 20);
var res2 = dtEmp.AsEnumerable().Where(emp => emp.Field<int>("EmpID")
== 1 || emp.Field<int>("EmpID") == 2);
foreach (DataRow row in res2)
{
Label2.Text += "Emplyee ID: " + row[0] + " & Emplyee Name: " + row[1] + ", ";
}
HTML:
<div class="parent">
<div class="child">
</div>
</div>
CSS:
.parent{
position: relative;
width: 300px;
height: 150px;
border: 1px solid black;
overflow: hidden;
}
.child {
height: 150px;
width: 318px;
overflow-y: scroll;
}
Apply CSS accordingly.
Check it here (tested in Internet Explorer and Firefox).
Using the length of the list would be the fastest solution to check if an index exists:
def index_exists(ls, i):
return (0 <= i < len(ls)) or (-len(ls) <= i < 0)
This also tests for negative indices, and most sequence types (Like ranges
and str
s) that have a length.
If you need to access the item at that index afterwards anyways, it is easier to ask forgiveness than permission, and it is also faster and more Pythonic. Use try: except:
.
try:
item = ls[i]
# Do something with item
except IndexError:
# Do something without the item
This would be as opposed to:
if index_exists(ls, i):
item = ls[i]
# Do something with item
else:
# Do something without the item
If your application only works in portrait orientation, this is enough:
[[[UIApplication sharedApplication] keyWindow] addSubview:yourView]
And your view will not be shown over keyboard and status bar.
If you want to get a topmost view that over keyboard or status bar, or you want the topmost view can rotate correctly with devices, please try this framework:
https://github.com/HarrisonXi/TopmostView
It supports iOS7/8/9.
If you want a shorter version of Jay's you could try
set usr=%userprofile%
cd %usr%
Or you could even use %u% if you wanted to. It saves some keystrokes anyway.
Here is an updated version of Paul Burke's answer. In versions below Android 4.4 (KitKat) we don't have the DocumentsContract class.
In order to work on versions below KitKat create this class:
public class DocumentsContract {
private static final String DOCUMENT_URIS =
"com.android.providers.media.documents " +
"com.android.externalstorage.documents " +
"com.android.providers.downloads.documents " +
"com.android.providers.media.documents";
private static final String PATH_DOCUMENT = "document";
private static final String TAG = DocumentsContract.class.getSimpleName();
public static String getDocumentId(Uri documentUri) {
final List<String> paths = documentUri.getPathSegments();
if (paths.size() < 2) {
throw new IllegalArgumentException("Not a document: " + documentUri);
}
if (!PATH_DOCUMENT.equals(paths.get(0))) {
throw new IllegalArgumentException("Not a document: " + documentUri);
}
return paths.get(1);
}
public static boolean isDocumentUri(Uri uri) {
final List<String> paths = uri.getPathSegments();
Logger.v(TAG, "paths[" + paths + "]");
if (paths.size() < 2) {
return false;
}
if (!PATH_DOCUMENT.equals(paths.get(0))) {
return false;
}
return DOCUMENT_URIS.contains(uri.getAuthority());
}
}
See this implementation from PEP318, implementing the singleton pattern with a decorator:
def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
...
Oracle
stores only the fractions up to second in a DATE
field.
Use TIMESTAMP
instead:
SELECT TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM dual
, possibly casting it to a DATE
then:
SELECT CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM dual
You could try this: df2 = pd.DataFrame.from_dict({'a':a,'b':b}, orient = 'index')
It's often clearer to separate the two actions git pull
does. The first thing it does is update the local tracking branc that corresponds to the remote branch. This can be done with git fetch
. The second is that it then merges in changes, which can of course be done with git merge
, though other options such as git rebase
are occasionally useful.
You can give https://github.com/ersiner/osx-env-sync a try. It handles both command line and GUI apps from a single source and works withe the latest version of OS X (Yosemite).
You can use path substitutions and other shell tricks since what you write is regular bash script to be sourced by bash in the first place. No restrictions.. (Check osx-env-sync documentation and you'll understand how it achieves this.)
I answered a similar question here where you'll find more.
If your JSON is without key you can do it like this:
library[library.length] = {"foregrounds" : foregrounds,"backgrounds" : backgrounds};
So, try this:
var library = {[{
"title" : "Gold Rush",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["1.jpg","","2.jpg"]
}, {
"title" : California",
"foregrounds" : ["Slide 1","Slide 2","Slide 3"],
"backgrounds" : ["3.jpg","4.jpg","5.jpg"]
}]
}
Then:
library[library.length] = {"title" : "Gold Rush", "foregrounds" : ["Howdy","Slide 2"], "backgrounds" : ["1.jpg",""]};
If you are OK with converting the input button to a server side control by specifying runat="server"
, and you are using asp.net
, an option could be using the HtmlButton.OnServerClick property.
<input id="foo "runat="server" type="button" onserverclick="foo_OnClick" />
This should work and call foo_OnClick
in your server side code.
Also notice that based on Microsoft documentation linked above, you should also be able to use the HTML 4.0 tag.
Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.
@Paul Cavacas, I had the same issue and I solved by setting the Input()
decorator above the getter.
@Input('allowDays')
get in(): any {
return this._allowDays;
}
//@Input('allowDays')
// not working
set in(val) {
console.log('allowDays = '+val);
this._allowDays = val;
}
See this plunker: https://plnkr.co/edit/6miSutgTe9sfEMCb8N4p?p=preview
Use this syntax for VB.NET 2005/2008 compatibility:
Dim theVar As New List(Of String)(New String() {"one", "two", "three"})
Although the VB.NET 2010 syntax is prettier.
Try.
<ScrollView onScroll={this.handleScroll} />
And then:
handleScroll: function(event: Object) {
console.log(event.nativeEvent.contentOffset.y);
},
count = 0
s = "azcbobobEgghakl"
s = s.lower()
for i in range(0, len(s)):
if s[i] == 'a'or s[i] == 'e'or s[i] == 'i'or s[i] == 'o'or s[i] == 'u':
count += 1
print("Number of vowels: "+str(count))
I use function for returning index for the matching element (Python 2.6):
def index(l, f):
return next((i for i in xrange(len(l)) if f(l[i])), None)
Then use it via lambda function for retrieving needed element by any required equation e.g. by using element name.
element = mylist[index(mylist, lambda item: item["name"] == "my name")]
If i need to use it in several places in my code i just define specific find function e.g. for finding element by name:
def find_name(l, name):
return l[index(l, lambda item: item["name"] == name)]
And then it is quite easy and readable:
element = find_name(mylist,"my name")
There should be no real world need for such a function anymore. This is mere academic interest.
As purely an exercise, this is a more functional way of doing it. It's an extension of @tfmontague's answer as I'd suggested adding a guard block there. But seeing as I feel compelled to ES6 and functionalise all the things, here's my pimped version. It complicates the logic as you have to map over the array and reduce over the object, but it avoids any mutations.
const cloner = (x) => {
const recurseObj = x => (typeof x === 'object') ? cloner(x) : x
const cloneObj = (y, k) => {
y[k] = recurseObj(x[k])
return y
}
// Guard blocks
// Add extra for Date / RegExp if you want
if (!x) {
return x
}
if (Array.isArray(x)) {
return x.map(recurseObj)
}
return Object.keys(x).reduce(cloneObj, {})
}
const tests = [
null,
[],
{},
[1,2,3],
[1,2,3, null],
[1,2,3, null, {}],
[new Date('2001-01-01')], // FAIL doesn't work with Date
{x:'', y: {yx: 'zz', yy: null}, z: [1,2,3,null]},
{
obj : new function() {
this.name = "Object test";
}
} // FAIL doesn't handle functions
]
tests.map((x,i) => console.log(i, cloner(x)))
_x000D_
If the string is empty, comboBox.getSelectedItem().toString()
will give a NullPointerException
. So better to typecast by (String)
.
There are, as i recall, two distributions of the gnu toolchain for windows: mingw and cygwin.
I'd expect cygwin work - a lot of effort has been made to make that a "stadard" posix environment.
The mingw toolchain uses msvcrt.dll for its runtime and thus will probably expose msvcrt's "thread" api: _beginthread which is defined in <process.h>
I'd go for regexp_replace, although I'm not 100% sure this is usable in PL/SQL
my_value := regexp_replace(my_value, '[[:space:]]*','');
I use kbhit() to see if a char is present and then getchar() to read the data. On windows, you can use "conio.h". On linux, you will have to implement your own kbhit().
See code below:
// kbhit
#include <stdio.h>
#include <sys/ioctl.h> // For FIONREAD
#include <termios.h>
#include <stdbool.h>
int kbhit(void) {
static bool initflag = false;
static const int STDIN = 0;
if (!initflag) {
// Use termios to turn off line buffering
struct termios term;
tcgetattr(STDIN, &term);
term.c_lflag &= ~ICANON;
tcsetattr(STDIN, TCSANOW, &term);
setbuf(stdin, NULL);
initflag = true;
}
int nbbytes;
ioctl(STDIN, FIONREAD, &nbbytes); // 0 is STDIN
return nbbytes;
}
// main
#include <unistd.h>
int main(int argc, char** argv) {
char c;
//setbuf(stdout, NULL); // Optional: No buffering.
//setbuf(stdin, NULL); // Optional: No buffering.
printf("Press key");
while (!kbhit()) {
printf(".");
fflush(stdout);
sleep(1);
}
c = getchar();
printf("\nChar received:%c\n", c);
printf("Done.\n");
return 0;
}
Sys.sleep() will not work if the CPU usage is very high; as in other critical high priority processes are running (in parallel).
This code worked for me. Here I am printing 1 to 1000 at a 2.5 second interval.
for (i in 1:1000)
{
print(i)
date_time<-Sys.time()
while((as.numeric(Sys.time()) - as.numeric(date_time))<2.5){} #dummy while loop
}
Building on @nad2000's answer and @Pavel's answer here, this is where I ended up for my Flyway migration scripts. Handling for scenarios where the database schema was manually modified.
DO $$
BEGIN
IF NOT EXISTS(
SELECT TRUE FROM pg_attribute
WHERE attrelid = (
SELECT c.oid
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE
n.nspname = CURRENT_SCHEMA()
AND c.relname = 'device_ip_lookups'
)
AND attname = 'active_date'
AND NOT attisdropped
AND attnum > 0
)
THEN
RAISE NOTICE 'ADDING COLUMN';
ALTER TABLE device_ip_lookups
ADD COLUMN active_date TIMESTAMP;
ELSE
RAISE NOTICE 'SKIPPING, COLUMN ALREADY EXISTS';
END IF;
END $$;
You had a mistake on the statement below. Use . not ,
echo '<img src="', $dir, '/', $file, '" alt="', $file, $
to
echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $
and
echo 'Directory \'', $dir, '\' not found!';
to
echo 'Directory \''. $dir. '\' not found!';
Yes, it creates a new list. This is by design.
The list will contain the same results as the original enumerable sequence, but materialized into a persistent (in-memory) collection. This allows you to consume the results multiple times without incurring the cost of recomputing the sequence.
The beauty of LINQ sequences is that they are composable. Often, the IEnumerable<T>
you get is the result of combining multiple filtering, ordering, and/or projection operations. Extension methods like ToList()
and ToArray()
allow you to convert the computed sequence into a standard collection.
The issue with reading single Excel Cell in .Net
comes from the fact, that the empty cell is evaluated to a Null
. Thus, one cannot use its .Value
or .Value2
properties, because an error shows up.
To return an empty string, when the cell is Null
the Convert.ToString(Cell)
can be used in the following way:
Excel.Workbook wkb = Open(excel, filePath);
Excel.Worksheet wk = (Excel.Worksheet)excel.Worksheets.get_Item(1);
for (int i = 1; i < 5; i++)
{
string a = Convert.ToString(wk.Cells[i, 1].Value2);
Console.WriteLine(a);
}
if you are using php then....
try{
$con = new PDO ("mysql:host=localhost;dbname=dbasename","root","");
}
catch(PDOException $e){
echo "error".$e-getMessage();
}
$select = $con->prepare("SELECT * FROM table");
$select->setFetchMode(PDO::FETCH_ASSOC);
$select->execute();
while($data=$select->fetch()){
$id = $data['id'];
$column = $data['column'];
$column = preg_replace("/[^a-zA-Z0-9]+/", " ", $column); //remove all special characters
$update = $con->prepare("UPDATE table SET column=:column WHERE id='$id'");
$update->bindParam(':column', $column );
$update->execute();
// echo $column."<br>";
}
hg update [-r REV]
If later you commit, you will effectively create a new branch. Then you might continue working only on this branch or eventually merge the existing one into it.
Following code is doing the job using reflection. It assumes you have getters for the properties you want to serialize
<?php
/**
* Serialize a simple PHP object into json
* Should be used for POPO that has getter methods for the relevant properties to serialize
* A property can be simple or by itself another POPO object
*
* Class CleanJsonSerializer
*/
class CleanJsonSerializer {
/**
* Local cache of a property getters per class - optimize reflection code if the same object appears several times
* @var array
*/
private $classPropertyGetters = array();
/**
* @param mixed $object
* @return string|false
*/
public function serialize($object)
{
return json_encode($this->serializeInternal($object));
}
/**
* @param $object
* @return array
*/
private function serializeInternal($object)
{
if (is_array($object)) {
$result = $this->serializeArray($object);
} elseif (is_object($object)) {
$result = $this->serializeObject($object);
} else {
$result = $object;
}
return $result;
}
/**
* @param $object
* @return \ReflectionClass
*/
private function getClassPropertyGetters($object)
{
$className = get_class($object);
if (!isset($this->classPropertyGetters[$className])) {
$reflector = new \ReflectionClass($className);
$properties = $reflector->getProperties();
$getters = array();
foreach ($properties as $property)
{
$name = $property->getName();
$getter = "get" . ucfirst($name);
try {
$reflector->getMethod($getter);
$getters[$name] = $getter;
} catch (\Exception $e) {
// if no getter for a specific property - ignore it
}
}
$this->classPropertyGetters[$className] = $getters;
}
return $this->classPropertyGetters[$className];
}
/**
* @param $object
* @return array
*/
private function serializeObject($object) {
$properties = $this->getClassPropertyGetters($object);
$data = array();
foreach ($properties as $name => $property)
{
$data[$name] = $this->serializeInternal($object->$property());
}
return $data;
}
/**
* @param $array
* @return array
*/
private function serializeArray($array)
{
$result = array();
foreach ($array as $key => $value) {
$result[$key] = $this->serializeInternal($value);
}
return $result;
}
}
Iterator is super class of ListIterator.
Here are the differences between them:
iterator
you can move only forward, but with ListIterator
you can move backword also while reading the elements.ListIterator
you can obtain the index at any point while traversing, which is not possible with iterator
s.iterator
you can check only for next element available or not, but in listiterator
you can check previous and next elements.listiterator
you can add new element at any point of time, while traversing. Not possible with iterator
.listiterator
you can modify an element while traversing, which is not possible with iterator
.Iterator look and feel:
public interface Iterator<E> {
boolean hasNext();
E next();
void remove(); //optional-->use only once with next(),
dont use it when u use for:each
}
ListIterator look and feel:
public interface ListIterator<E> extends Iterator<E> {
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove(); //optional
void set(E e); //optional
void add(E e); //optional
}
In my case the issue is that on Xcode Beta 11.5 there's a change on the ways to sign the app so just make sure that both for the Debug/Release the provisioning certificate is properly set
If you want to debug why not use console debug
window.console.debug(jsonObject);
You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:
clean:
@if [ "test" = "test" ]; then\
echo "Hello world";\
fi
Note that the closing ";" and "\" are necessary.
for me following worked, just ran these command one by one
git pull -r origin master
git push -f origin your_branch
If you want the word "Hello" to print in a column that's 40 characters wide, with spaces padding the left, use the following.
char *ptr = "Hello";
printf("%40s\n", ptr);
That will give you 35 spaces, then the word "Hello". This is how you format stuff when you know how wide you want the column, but the data changes (well, it's one way you can do it).
If you know you want exactly 40 spaces then some text, just save the 40 spaces in a constant and print them. If you need to print multiple lines, either use multiple printf
statements like the one above, or do it in a loop, changing the value of ptr
each time.
There is no inbuilt solution to this problem, this is a problem with your design and coding pattern.
You can use publisher/subscriber pattern. For this you can use jQuery custom events or your own event mechanism.
First,
function changeHtml(selector, html) {
var elem = $(selector);
jQuery.event.trigger('htmlchanging', { elements: elem, content: { current: elem.html(), pending: html} });
elem.html(html);
jQuery.event.trigger('htmlchanged', { elements: elem, content: html });
}
Now you can subscribe divhtmlchanging/divhtmlchanged events as follow,
$(document).bind('htmlchanging', function (e, data) {
//your before changing html, logic goes here
});
$(document).bind('htmlchanged', function (e, data) {
//your after changed html, logic goes here
});
Now, you have to change your div content changes through this changeHtml()
function. So, you can monitor or can do necessary changes accordingly because bind callback data argument containing the information.
You have to change your div's html like this;
changeHtml('#mydiv', '<p>test content</p>');
And also, you can use this for any html element(s) except input element. Anyway you can modify this to use with any element(s).
The mz
module provides promisified versions of the core node library. Using them is simple. First install the library...
npm install mz
Then...
const fs = require('mz/fs');
fs.readFile('./Index.html').then(contents => console.log(contents))
.catch(err => console.error(err));
Alternatively you can write them in asynchronous functions:
async function myReadfile () {
try {
const file = await fs.readFile('./Index.html');
}
catch (err) { console.error( err ) }
};
I got the same error when issuing a URL without the protocol (like localhost:4200
) instead of a correct one also specifying the protocol (e.g. http://localhost:4200).
Google Chrome works fine without the protocol (it takes http as the default), but Firefox crashes with this error.
tchester said :
(2) Create a login for the non-sysadmin user that has public access to the master database
I went to my user's database list (server/security/connections/my user name/properties/user mapping, and wanted to check the box for master database. I got an error message telling that the user already exists in the master database. Went to master database, dropped the user, went back to "user mapping" and checked the box for master. Check the "public" box below.
After that, you need to re-issue the grant execute on xp_cmdshell to "my user name"
Yves
This TypeScript code
class A {
private a1;
public a2;
}
compiles to this JavaScript code
class A {
}
That's because properties in JavaScript start extisting only after they have some value. You have to assign the properties some value.
class A {
private a1 = "";
public a2 = "";
}
it compiles to
class A {
constructor() {
this.a1 = "";
this.a2 = "";
}
}
Still, you cannot get the properties from mere class (you can get only methods from prototype). You must create an instance. Then you get the properties by calling Object.getOwnPropertyNames()
.
let a = new A();
let array = return Object.getOwnPropertyNames(a);
array[0] === "a1";
array[1] === "a2";
class Describer {
static describe(instance): Array<string> {
return Object.getOwnPropertyNames(instance);
}
}
let a = new A();
let x = Describer.describe(a);
The overriding method CAN throw any unchecked (runtime) exception, regardless of whether the overridden method declares the exception
Example:
class Super {
public void test() {
System.out.println("Super.test()");
}
}
class Sub extends Super {
@Override
public void test() throws IndexOutOfBoundsException {
// Method can throw any Unchecked Exception
System.out.println("Sub.test()");
}
}
class Sub2 extends Sub {
@Override
public void test() throws ArrayIndexOutOfBoundsException {
// Any Unchecked Exception
System.out.println("Sub2.test()");
}
}
class Sub3 extends Sub2 {
@Override
public void test() {
// Any Unchecked Exception or no exception
System.out.println("Sub3.test()");
}
}
class Sub4 extends Sub2 {
@Override
public void test() throws AssertionError {
// Unchecked Exception IS-A RuntimeException or IS-A Error
System.out.println("Sub4.test()");
}
}
It is not the answer you probably want, but why hide what you're trying to make public?
Mark the test with the ExpectedExceptionAttribute (this is the term in NUnit or MSTest; users of other unit testing frameworks may need to translate).
First of all, have only one id="test"
Secondly, try this:
if ($('[name="test"]').is(':checked'))
Simple example: Form with textbox and Search button.
If you write "name" into the textbox
and submit form, it will brings you patients with "name" in table.
View:
@using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
UpdateTargetId = "patientList",
LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading
}))
{
string patient_Name = "";
@Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
<input type="submit" value="Search" />
}
@* ... *@
<div id="loader" class=" aletr" style="display:none">
Loading...<img src="~/Images/ajax-loader.gif" />
</div>
@Html.Partial("_patientList") @* this is view with patient table. Same view you will return from controller *@
_patientList.cshtml:
@model IEnumerable<YourApp.Models.Patient>
<table id="patientList" >
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Number)
</th>
</tr>
@foreach (var patient in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => patient.Name)
</td>
<td>
@Html.DisplayFor(modelItem => patient.Number)
</td>
</tr>
}
</table>
Patient.cs
public class Patient
{
public string Name { get; set; }
public int Number{ get; set; }
}
PatientController.cs
public PartialViewResult GetPatients(string patient_Name="")
{
var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
return PartialView("_patientList", patients);
}
And also as TSmith said in comments, don´t forget to install jQuery Unobtrusive Ajax library through NuGet.
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);
}
The command in wfg5475's answer is working properly, just need to add one thing to show only files in a directory & sub directory:
ls -ltraR |egrep -v '\.$|\.\.|\.:|\.\/|total|^d' |sed '/^$/d'
Added one thing: ^d
to ignore the all directories from the listing outputs
You can do it by using window_handles
and switch_to_window
method.
Before clicking the link first store the window handle as
window_before = driver.window_handles[0]
after clicking the link store the window handle of newly opened window as
window_after = driver.window_handles[1]
then execute the switch to window method to move to newly opened window
driver.switch_to_window(window_after)
and similarly you can switch between old and new window. Following is the code example
import unittest
from selenium import webdriver
class GoogleOrgSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Firefox()
def test_google_search_page(self):
driver = self.driver
driver.get("http://www.cdot.in")
window_before = driver.window_handles[0]
print window_before
driver.find_element_by_xpath("//a[@href='http://www.cdot.in/home.htm']").click()
window_after = driver.window_handles[1]
driver.switch_to_window(window_after)
print window_after
driver.find_element_by_link_text("ATM").click()
driver.switch_to_window(window_before)
def tearDown(self):
self.driver.close()
if __name__ == "__main__":
unittest.main()
The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:
var array = db.CollectionName.find({}).sort({ _id: -1 }).limit(1).toArray(); var max = max.length?max[0]+1:1;
Even if an User ID is deleted, this wont create duplicate
POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like
Here is a good start for this
You can also generate POCOs so easily from your existing Entity framework project using Code generators.
Looking under the hood, the two statements will be transformed into different query representations. Depending on the QueryProvider
of Collection
, this might be optimized away or not.
When this is a linq-to-object call, multiple where clauses will lead to a chain of IEnumerables that read from each other. Using the single-clause form will help performance here.
When the underlying provider translates it into a SQL statement, the chances are good that both variants will create the same statement.
See http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
This explains that Unicode versions of Windows APIs have higher limits, and how to enable that.
I suggest the use of htop, as a better alternative to top.
From what I know
3 one-liners
a = 10 if <condition>
example:
a = 10 if true # a = 10
b = 10 if false # b = nil
a = 10 unless <condition>
example:
a = 10 unless false # a = 10
b = 10 unless true # b = nil
a = <condition> ? <a> : <b>
example:
a = true ? 10 : 100 # a = 10
a = false ? 10 : 100 # a = 100
I hope it helps.
I'd like to add this note I don't very clearly elsewhere; inside a module/package, when loading from files, the module/package name must be prefixed with the mymodule
. Imagine mymodule
being layout like this:
/main.py
/mymodule
/__init__.py
/somefile.py
/otherstuff.py
When loading somefile.py
/otherstuff.py
from __init__.py
the contents should look like:
from mymodule.somefile import somefunc
from mymodule.otherstuff import otherfunc
Scenario:
Windows 10 with Visual Studio 2017 (FRESH installation).
'C' project (ERROR like -> cannot open source file: 'stdio.h', 'windows.h', etc.).
Resolve:
Run 'Visual Studio Installer'.
Click button 'Modify'.
Select 'Desktop development with C++'.
From "Installation details"(usually on the right-sidebar) select:
4.1. Windows 10 SDK(10.0.17134.0).
Click button 'Modify', to apply changes.
I prefer to do it this way
heroku logs --tail | tee -a herokuLogs
You can leave the script running in background and you can simply filter the logs from the text file the way you want anytime.
See gjvdkamp
's answer below; this feature now exists in C#
var @switch = new Dictionary<Type, Action> {
{ typeof(Type1), () => ... },
{ typeof(Type2), () => ... },
{ typeof(Type3), () => ... },
};
@switch[typeof(MyType)]();
It's a little less flexible as you can't fall through cases, continue etc. But I rarely do so anyway.
this is js1568's solution, modified to work on a generic array of objects, like:
var genericObject=[
{genProp:'this is a string',randomInt:10,isBoolean:false},
{genProp:'this is another string',randomInt:20,isBoolean:false},
{genProp:'this is a string',randomInt:10,isBoolean:true},
{genProp:'this is another string',randomInt:30,isBoolean:false},
{genProp:'this is a string',randomInt:40,isBoolean:true},
{genProp:'i like strings',randomInt:60,isBoolean:true},
{genProp:'this is a string',randomInt:70,isBoolean:true},
{genProp:'this string is unique',randomInt:50,isBoolean:true},
{genProp:'this is a string',randomInt:50,isBoolean:false},
{genProp:'i like strings',randomInt:70,isBoolean:false}
]
It accepts one more parameter called propertyName, guess! :)
$.extend({
distinctObj:function(obj,propertyName) {
var result = [];
$.each(obj,function(i,v){
var prop=eval("v."+propertyName);
if ($.inArray(prop, result) == -1) result.push(prop);
});
return result;
}
});
so, if you need to extract a list of unique values for a given property, for example the values used for randomInt property, use this:
$.distinctObj(genericObject,'genProp');
it returns an array like this:
["this is a string", "this is another string", "i like strings", "this string is unique"]
There are many different ways for accomplishing this, but one of the most elegant one is:
kubectl run -i --tty --image ubuntu:latest ubuntu-test --restart=Never --rm /bin/sh
According to the documentation:
Thrown to indicate that the code has attempted to cast an Object
to a subclass
of which it is not an instance. For example, the following code generates a ClassCastException
:
Object x = new Integer(0);
System.out.println((String)x);
Another way (Using Formulas in VBA). I guess this is the shortest VBA code as well?
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("B1:B" & lRow).Formula = "=If(A1<>"""",""My Text"","""")"
.Range("B1:B" & lRow).Value = .Range("B1:B" & lRow).Value
End With
End Sub
Replace (.*")\d+(")
With $1x$2
Where x
is your "value inside scopes".
Here is the simplest way to do it in Android. I know it will not work in Java but It may help Android application developer.
import android.webkit.URLUtil;
public String getFileNameFromURL(String url) {
String fileNameWithExtension = null;
String fileNameWithoutExtension = null;
if (URLUtil.isValidUrl(url)) {
fileNameWithExtension = URLUtil.guessFileName(url, null, null);
if (fileNameWithExtension != null && !fileNameWithExtension.isEmpty()) {
String[] f = fileNameWithExtension.split(".");
if (f != null & f.length > 1) {
fileNameWithoutExtension = f[0];
}
}
}
return fileNameWithoutExtension;
}
Python is copy by value of reference. An object occupies a field in memory, and a reference is associated with that object, but itself occupies a field in memory. And name/value is associated with a reference. In python function, it always copy the value of the reference, so in your code, n is copied to be a new name, when you assign that, it has a new space in caller stack. But for the list, the name also got copied, but it refer to the same memory(since you never assign the list a new value). That is a magic in python!
This will definitely help. Answer by npm itself. https://docs.npmjs.com/getting-started/fixing-npm-permissions
Below is extracted from the URL for your convenience.
Option 1: Change the permission to npm's default directory
Find the path to npm's directory:
npm config get prefix
For many systems, this will be /usr/local.
WARNING: If the displayed path is just /usr, switch to Option 2 or you will mess up your permissions.
Change the owner of npm's directories to the name of the current user (your username!):
sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}
This changes the permissions of the sub-folders used by npm and some other tools (lib/node_modules, bin, and share).
Option 2: Change npm's default directory to another directory
Make a directory for global installations:
mkdir ~/.npm-global
Configure npm to use the new directory path:
npm config set prefix '~/.npm-global'
Open or create a ~/.profile file and add this line:
export PATH=~/.npm-global/bin:$PATH
Back on the command line, update your system variables:
source ~/.profile
Test: Download a package globally without using sudo.
`npm install -g jshint`
Instead of steps 2-4, you can use the corresponding ENV variable (e.g. if you don't want to modify ~/.profile
):
NPM_CONFIG_PREFIX=~/.npm-global
Option 3: Use a package manager that takes care of this for you
If you're doing a fresh install of Node on Mac OS, you can avoid this problem altogether by using the Homebrew package manager. Homebrew sets things up out of the box with the correct permissions.
brew install node
Ctrl+d and Ctrl+Shift+d....
[
{ "keys": ["ctrl+d"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+d"], "command": "toggle_comment", "args": { "block": true } },
]
Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):
string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];
This is very similar to the Substring
method, just by a different means.
I needed something similar for arrays. That helped me
some_array_rounded=np.around(some_array, 5)
You can use dtype=np.int64
instead of dtype=int
Worked out a fiddle. Do check it out
(function() {
var oJson = {
"name": "",
"skills": "",
"jobtitle": "Entwickler",
"res_linkedin": "GwebSearch"
}
alert(oJson.jobtitle);
})();
I thought the regular modulus operator would work for this in java, but it can't be hard to code. Just divide the numerator by the denominator, and take the integer portion of the result. Multiply that by the denominator, and subtract the result from the numerator.
x = n / d
xint = Integer portion of x
result = n - d * xint
Use a binding for the value in your template.
value="{{ option.id }}"
should be
[value]="option.id"
And in your selected value use ngModel
instead of value
.
<mat-select [(value)]="selected2">
should be
<mat-select [(ngModel)]="selected2">
Complete code:
<div>
<mat-select [(ngModel)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
</mat-select>
</div>
On a side note as of version 2.0.0-beta.12 the material select now accepts a mat-form-field
element as the parent element so it is consistent with the other material input controls. Replace the div
element with mat-form-field
element after you upgrade.
<mat-form-field>
<mat-select [(ngModel)]="selected2">
<mat-option *ngFor="let option of options2" [value]="option.id">{{ option.name }}</mat-option>
</mat-select>
</mat-form-field>
If you're targeting iOS 4.0+, you can do the following:
[executing first operation];
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[executing second operation];
});
You can do this simply with SSMS. Just go to your table name and expand the Triggers node to view a list of triggers associated with that table. Right click to modify your trigger.
Your best bet is to have a look at strptime()
Something along the lines of
>>> from datetime import datetime
>>> date_str = 'Tue May 08 15:14:45 +0800 2012'
>>> date = datetime.strptime(date_str, '%a %B %d %H:%M:%S +0800 %Y')
>>> date
datetime.datetime(2012, 5, 8, 15, 14, 45)
Im not sure how to do the +0800 timezone unfortunately, maybe someone else can help out with that.
The formatting strings can be found at http://docs.python.org/library/time.html#time.strftime and are the same for formatting the string for printing.
Hope that helps
Mark
PS, Your best bet for timezones in installing pytz from pypi. ( http://pytz.sourceforge.net/ ) in fact I think pytz has a great datetime parsing method if i remember correctly. The standard lib is a little thin on the ground with timezone functionality.
The parent directory of an included file would be
dirname(getcwd())
e.g. the file is /var/www/html/folder/inc/file.inc.php which is included in /var/www/html/folder/index.php
then by calling /file/index.php
getcwd() is /var/www/html/folder
__DIR__ is /var/www/html/folder/inc
so dirname(__DIR__) is /var/www/html/folder
but what we want is /var/www/html which is dirname(getcwd())
The list comprehensions actually are implemented more efficiently than explicit looping (see the dis
output for example functions) and the map
way has to invoke an ophaque callable object on every iteration, which incurs considerable overhead overhead.
Regardless, [[] for _dummy in xrange(n)]
is the right way to do it and none of the tiny (if existent at all) speed differences between various other ways should matter. Unless of course you spend most of your time doing this - but in that case, you should work on your algorithms instead. How often do you create these lists?
Well you missed quotation mark around your string selectcard
it should be "selectcard"
if (card.value == selectcard)
should be
if (card.value == "selectcard")
Here is complete code for that
function validate()
{
var ddl = document.getElementById("cardtype");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "selectcard")
{
alert("Please select a card type");
}
}
Try:
output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output
Wrapping your command in $( )
tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)
I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.
Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:
jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD
jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD
What you're seeing is integer division. To get floating point division by default,
from __future__ import division
Or, you could convert 1 or 2 of 1/2 into a floating point value.
sqrt = x**(1.0/2)
This error might be caused by the jQuery event-aliases like .load()
, .unload()
or .error()
that all are deprecated since jQuery 1.8. Lookup for these aliases in your code and replace them with the .on()
method instead. For example, replace the following deprecated excerpt:
$(window).load(function(){...});
with the following:
$(window).on('load', function(){ ...});
If you are using lodash or npm
, use lodash's merge function to deep copy all of the object's properties to a new empty object like so:
var objectCopy = lodash.merge({}, originalObject);
I guess an img tag is needed as a child of an a tag, the following way:
<a download="YourFileName.jpeg" href="data:image/jpeg;base64,iVBO...CYII=">
<img src="data:image/jpeg;base64,iVBO...CYII="></img>
</a>
or
<a download="YourFileName.jpeg" href="/path/to/OtherFile.jpg">
<img src="/path/to/OtherFile.jpg"></img>
</a>
Only using the a tag as explained in #15 didn't worked for me with the latest version of Firefox and Chrome, but putting the same image data in both a.href and img.src tags worked for me.
From JavaScript it could be generated like this:
var data = canvas.toDataURL("image/jpeg");
var img = document.createElement('img');
img.src = data;
var a = document.createElement('a');
a.setAttribute("download", "YourFileName.jpeg");
a.setAttribute("href", data);
a.appendChild(img);
var w = open();
w.document.title = 'Export Image';
w.document.body.innerHTML = 'Left-click on the image to save it.';
w.document.body.appendChild(a);
for me I simply had to add configure my git username and email with the following commands:
git config --global user.email "[email protected]"
git config --global user.name "Your Name"
If you're using CentOS 7, and you've installed Docker via yum, don't forget to run:
$ sudo systemctl start docker
$ sudo systemctl enable docker
This will start the server, as well as re-start it automatically on boot.
The message usually comes when you put the wrong image name. Please check your image if it exists on the Docker repository with the correct tag. It helped me.
docker run -d -p 80:80 --name ngnix ngnix:latest
Unable to find image 'ngnix:latest' locally
docker: Error response from daemon: pull access denied for ngnix, repository does not exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
$ docker run -d -p 80:80 --name nginx nginx:latest
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
Set font-size
in viewport-width-related units, e.g.:
table { font-size: 0.9vw; }
This will make font unreadable when page is too narrow, but sometimes this is acceptable.
I give you The Function parse_params
that will parse params from the command line.
--all
equals -all
equals all=all
)The script below is a copy-paste working demonstration. See show_use
function to understand how to use parse_params
.
Limitations:
-d 1
)--any-param
and -anyparam
are equivalenteval $(parse_params "$@")
must be used inside bash function (it will not work in the global scope)#!/bin/bash
# Universal Bash parameter parsing
# Parse equal sign separated params into named local variables
# Standalone named parameter value will equal its param name (--force creates variable $force=="force")
# Parses multi-valued named params into an array (--path=path1 --path=path2 creates ${path[*]} array)
# Puts un-named params as-is into ${ARGV[*]} array
# Additionally puts all named params as-is into ${ARGN[*]} array
# Additionally puts all standalone "option" params as-is into ${ARGO[*]} array
# @author Oleksii Chekulaiev
# @version v1.4.1 (Jul-27-2018)
parse_params ()
{
local existing_named
local ARGV=() # un-named params
local ARGN=() # named params
local ARGO=() # options (--params)
echo "local ARGV=(); local ARGN=(); local ARGO=();"
while [[ "$1" != "" ]]; do
# Escape asterisk to prevent bash asterisk expansion, and quotes to prevent string breakage
_escaped=${1/\*/\'\"*\"\'}
_escaped=${_escaped//\'/\\\'}
_escaped=${_escaped//\"/\\\"}
# If equals delimited named parameter
nonspace="[^[:space:]]"
if [[ "$1" =~ ^${nonspace}${nonspace}*=..* ]]; then
# Add to named parameters array
echo "ARGN+=('$_escaped');"
# key is part before first =
local _key=$(echo "$1" | cut -d = -f 1)
# Just add as non-named when key is empty or contains space
if [[ "$_key" == "" || "$_key" =~ " " ]]; then
echo "ARGV+=('$_escaped');"
shift
continue
fi
# val is everything after key and = (protect from param==value error)
local _val="${1/$_key=}"
# remove dashes from key name
_key=${_key//\-}
# skip when key is empty
# search for existing parameter name
if (echo "$existing_named" | grep "\b$_key\b" >/dev/null); then
# if name already exists then it's a multi-value named parameter
# re-declare it as an array if needed
if ! (declare -p _key 2> /dev/null | grep -q 'declare \-a'); then
echo "$_key=(\"\$$_key\");"
fi
# append new value
echo "$_key+=('$_val');"
else
# single-value named parameter
echo "local $_key='$_val';"
existing_named=" $_key"
fi
# If standalone named parameter
elif [[ "$1" =~ ^\-${nonspace}+ ]]; then
# remove dashes
local _key=${1//\-}
# Just add as non-named when key is empty or contains space
if [[ "$_key" == "" || "$_key" =~ " " ]]; then
echo "ARGV+=('$_escaped');"
shift
continue
fi
# Add to options array
echo "ARGO+=('$_escaped');"
echo "local $_key=\"$_key\";"
# non-named parameter
else
# Escape asterisk to prevent bash asterisk expansion
_escaped=${1/\*/\'\"*\"\'}
echo "ARGV+=('$_escaped');"
fi
shift
done
}
#--------------------------- DEMO OF THE USAGE -------------------------------
show_use ()
{
eval $(parse_params "$@")
# --
echo "${ARGV[0]}" # print first unnamed param
echo "${ARGV[1]}" # print second unnamed param
echo "${ARGN[0]}" # print first named param
echo "${ARG0[0]}" # print first option param (--force)
echo "$anyparam" # print --anyparam value
echo "$k" # print k=5 value
echo "${multivalue[0]}" # print first value of multi-value
echo "${multivalue[1]}" # print second value of multi-value
[[ "$force" == "force" ]] && echo "\$force is set so let the force be with you"
}
show_use "param 1" --anyparam="my value" param2 k=5 --force --multi-value=test1 --multi-value=test2
In C#, they are interchangeable (although method is the proper term) because you cannot write a method without incorporating it into a class. If it were independent of a class, then it would be a function. Methods are functions that operate through a designated class.
What worked for me now is:
CSS:
.right {
text-align: right;
margin-right: 1em;
}
.left {
text-align: left;
margin-left: 1em;
}
HTML:
<table width="100%">
<tbody>
<tr>
<td class="left">
<input id="abort" type="submit" name="abort" value="Back">
<input id="save" type="submit" name="save" value="Save">
</td>
<td class="right">
<input id="delegate" type="submit" name="delegate" value="Delegate">
<input id="unassign" type="submit" name="unassign" value="Unassign">
<input id="complete" type="submit" name="complete" value="Complete">
</td>
</tr>
</tbody>
</table>
See the following fiddle:
I suppose there is no fundamental reason why the compiler couldn't automatically translate your switch statement into:
if (t == typeof(int))
{
...
}
elseif (t == typeof(string))
{
...
}
...
But there isn't much gained by that.
A case statement on integral types allows the compiler to make a number of optimizations:
There is no duplication (unless you duplicate case labels, which the compiler detects). In your example t could match multiple types due to inheritance. Should the first match be executed? All of them?
The compiler can choose to implement a switch statement over an integral type by a jump table to avoid all the comparisons. If you are switching on an enumeration that has integer values 0 to 100 then it creates an array with 100 pointers in it, one for each switch statement. At runtime it simply looks up the address from the array based on the integer value being switched on. This makes for much better runtime performance than performing 100 comparisons.
int
is a primitive type that represent an integer. whereas Integer
is an Object that wraps int
. The Integer
object gives you more functionality, such as converting to hex, string, etc.
You can also use OOP concepts with Integer
. For example, you can use Integer for generics (i.e. Collection
).<Integer>
By default, when you click on a ListView item it doesn't change its state to "selected". So, when the event fires and you do:
myList.getSelectedItem();
The method doesn't have anything to return. What you have to do is to use the position and obtain the underlying object by doing:
myList.getItemAtPosition(position);
Do you mean any specific syntax for wildcards? Usually *
stands for "one or many" characters and ?
stands for one.
The simplest way probably is to translate a wildcard expression into a regular expression, then use that for filtering the results.
outerloop:
$(sentences).each(function()
{
$(words).each(function(i)
{
break; /* breaks inner loop */
}
$(words).each(function(i)
{
break outerloop; /* breaks outer loop */
}
}
Give this a try...
server {
listen 80;
server_name dev.int.com;
access_log off;
location / {
proxy_pass http://IP:8080;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:8080/jira /;
proxy_connect_timeout 300;
}
location ~ ^/stash {
proxy_pass http://IP:7990;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-for $remote_addr;
port_in_redirect off;
proxy_redirect http://IP:7990/ /stash;
proxy_connect_timeout 300;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/local/nginx/html;
}
}
If you convert table field:
Define the field so it contains seconds:
CREATE TABLE IF NOT EXISTS test (
...
field INTERVAL SECOND(0)
);
Extract the value. Remember to cast to int other wise you can get an unpleasant surprise once the intervals are big:
EXTRACT(EPOCH FROM field)::int
Well, I've received this error today on Windows 8 64-bit out of the blue, for the first time, and it turns out my my.ini had been reset, and the bin/mysqld file had been deleted, among other items in the "Program Files/MySQL/MySQL Server 5.6"
folder.
To fix it, I had to run the MySQL installer again, installing only the server, and copy a recent version of the my.ini file from "ProgramData/MySQL/MySQL Server 5.6"
, named my_2014-03-28T15-51-20.ini
in my case (don't know how or why that got copied there so recently) back into "Program Files/MySQL/MySQL Server 5.6"
.
The only change to the system since MySQL worked was the installation of Native Instruments' Traktor 2 and a Traktor Audio 2 sound card, which really shouldn't have caused this problem, and no one else has used the system besides me. If anyone has a clue, it would be kind of you to comment to prevent this for me and anyone else who has encountered this.
It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:
Access-Control-Allow-Origin:*
or
Access-Control-Allow-Origin:your domain
In Apache config files, the code is like this:
Header set Access-Control-Allow-Origin "*"
In nodejs,the code is like this:
res.setHeader('Access-Control-Allow-Origin','*');
Here is a great way to solve this problem:
Create a rectangle drawable with rounded corners like this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<stroke android:width="2dp"
android:color="#888888"/>
<corners android:bottomRightRadius="6dp"
android:bottomLeftRadius="6dp"
android:topLeftRadius="6dp"
android:topRightRadius="6dp"/>
</shape>
save it in the drawable folder with the name rounded_border.xml
Then create a relative layout that uses the rounded_border as a background like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/rounded_border">
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
save that in your layout folder and name it table_with_border.xml
then whenever you need such a table pull it into a view using the include syntax like this:
<include
android:id="@+id/rounded_table"
android:layout_width="match_parent"
android:layout_height="wrap_content"
layout="@layout/table_with_border" />
You will probably want to add some spacing around the edges - so just wrap the include in a LinearLayout and add some padding around the edges.
Simple and easy way to get a pretty border around a table.
After browsing search engines for a few hours I came across a site with a great ERD example here: http://www.exploredatabase.com/2016/07/description-about-weak-entity-sets-in-DBMS.html
I've recreated the ERD. Unfortunately they did not specify the primary key of the weak entity.
If the building could only have one and only one apartment, then it seems the partial discriminator room number would not be created (i.e. discarded).
In here you can save the phone number as international formatted phone number
internationalFormatPhoneNumber = phoneUtil.format(givenPhoneNumber, PhoneNumberFormat.INTERNATIONAL);
it return the phone number as International format +94 71 560 4888
so now I have get country code as this
String countryCode = internationalFormatPhoneNumber.substring(0,internationalFormatPhoneNumber.indexOf('')).replace('+', ' ').trim();
Hope this will help you
You want to use BigInteger.toByteArray()
String msg = "Hello there!";
BigInteger bi = new BigInteger(msg.getBytes());
System.out.println(new String(bi.toByteArray())); // prints "Hello there!"
The way I understand it is that you're doing the following transformations:
String -----------------> byte[] ------------------> BigInteger
String.getBytes() BigInteger(byte[])
And you want the reverse:
BigInteger ------------------------> byte[] ------------------> String
BigInteger.toByteArray() String(byte[])
Note that you probably want to use overloads of String.getBytes()
and String(byte[])
that specifies an explicit encoding, otherwise you may run into encoding issues.
the problem is blade, try this
<i class="fa" v-bind:class="['{{content['cravings']}}' ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']"></i>
are you parsing output of ls -l
?
If you are, and you just want to get the file name
find . -iname "*[0-9]"
If you have no choice because usrLog.txt is created by something/someone else and you absolutely must use this file, other options include
awk '/^[-d].*[0-9]$/' file
Ruby(1.9+)
ruby -ne 'print if /^[-d].*[0-9]$/' file
Bash
while read -r line ; do case $line in [-d]*[0-9] ) echo $line; esac; done < file
They are lists because you type them as lists in the dictionary:
bikes = {
# Bike designed for children"
"Trike": ["Trike", 20, 100],
# Bike designed for everyone"
"Kruzer": ["Kruzer", 50, 165]
}
You should use the bike-class instead:
bikes = {
# Bike designed for children"
"Trike": Bike("Trike", 20, 100),
# Bike designed for everyone"
"Kruzer": Bike("Kruzer", 50, 165)
}
This will allow you to get the cost of the bikes with bike.cost as you were trying to.
for bike in bikes.values():
profit = bike.cost * margin
print(bike.name + " : " + str(profit))
This will now print:
Kruzer : 33.0
Trike : 20.0
file_name=test.log
# set first K lines:
K=1000
# line count (N):
N=$(wc -l < $file_name)
# length of the bottom file:
L=$(( $N - $K ))
# create the top of file:
head -n $K $file_name > top_$file_name
# create bottom of file:
tail -n $L $file_name > bottom_$file_name
Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so
split -l 300000 file_name
will output xaa
with 300k lines and xab
with 100k lines, for an input with 400k lines.
I would do it this way
$("#idElement").val('optionValue').trigger('change');
In Windows 7, 8 or 8.1, in Devices Manager:
When you run the code
listoflists.append((list, list[0]))
You are not (as I think you expect) adding a copy of list
to the end of listoflists
. What you are doing is adding a reference to list
to the end of listoflists
. Thus, every time you update list
, it updates every reference to list
, which in this case, is every item in listoflists
What you could do instead is something like this:
listoflists = []
for i in range(1, 10):
listoflists.append((range(i), 0))
You can get a list of column names by running:
SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name
tbl_name
rootpage
sql
You can check if a certain column exists by running:
SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='sql';
1
Reference:
On the low level, these events can be caught using rtnetlink sockets, without any polling. Side note: if you use rtnetlink, you have to work together with udev, or your program may get confused when udev renames a new network interface.
The problem with doing network configurations with shell scripts is that shell scripts are terrible for event handling (such as a network cable being plugged in and out). If you need something more powerful, take a look at my NCD programming language, a programming language designed for network configurations.
For example, a simple NCD script that will print "cable in" and "cable out" to stdout (assuming the interface is already up):
process foo {
# Wait for device to appear and be configured by udev.
net.backend.waitdevice("eth0");
# Wait for cable to be plugged in.
net.backend.waitlink("eth0");
# Print "cable in" when we reach this point, and "cable out"
# when we regress.
println("cable in"); # or pop_bubble("Network cable in.");
rprintln("cable out"); # or rpop_bubble("Network cable out!");
# just joking, there's no pop_bubble() in NCD yet :)
}
(internally, net.backend.waitlink()
uses rtnetlink, and net.backend.waitdevice()
uses udev)
The idea of NCD is that you use it exclusively to configure the network, so normally, configuration commands would come in between, such as:
process foo {
# Wait for device to appear and be configured by udev.
net.backend.waitdevice("eth0");
# Set device up.
net.up("eth0");
# Wait for cable to be plugged in.
net.backend.waitlink("eth0");
# Add IP address to device.
net.ipv4.addr("eth0", "192.168.1.61", "24");
}
The important part to note is that execution is allowed to regress; in the second example, for instance, if the cable is pulled out, the IP address will automatically be removed.
Citing this Stack Overflow answer.
It is a pretty neat way to get type-of-change (A:Added, M:Modified, D:Deleted) for each file that got changed.
git diff --name-status
var pinIcon = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(12, 18)
);
<html>
<head>
<style>
.rightclick {
/* YOUR CONTEXTMENU'S CSS */
visibility: hidden;
background-color: white;
border: 1px solid grey;
width: 200px;
height: 300px;
}
</style>
</head>
<body>
<div class="rightclick" id="ya">
<p onclick="alert('choc-a-late')">I like chocolate</p><br><p onclick="awe-so-me">I AM AWESOME</p>
</div>
<p>Right click to get sweet results!</p>
</body>
<script>
document.onclick = noClick;
document.oncontextmenu = rightClick;
function rightClick(e) {
e = e || window.event;
e.preventDefault();
document.getElementById("ya").style.visibility = "visible";
console.log("Context Menu v1.3.0 by IamGuest opened.");
}
function noClick() {
document.getElementById("ya").style.visibility = "hidden";
console.log("Context Menu v1.3.0 by IamGuest closed.");
}
</script>
<!-- Coded by IamGuest. Thank you for using this code! -->
</html>
You can tweak and modify this code to make a better looking, more efficient contextmenu. As for modifying an existing contextmenu, I'm not sure how to do that... Check out this fiddle for an organized point of view. Also, try clicking the items in my contextmenu. They should alert you a few awesome messages. If they don't work, try something more... complex.
There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?
Make an images folder inside src(/src/images) And keep your image in it. Then import this image in your component(use your relative path). Like below-
import imageSrc from './images/image-name.jpg';
And then in your component.
<img title="my-img" src={imageSrc} alt="my-img" />
Another way is to keep images in public folder and import them using relative path. For this make an image folder in public folder and keep your image in it. And then in your component use it like below.
<img title="my-img" src='/images/my-image.jpg' alt="my-img" />
Both method work but first one is recommended because its cleaner way and images are handled by webpack during build time.
Here is an alternative way to get an object's property value:
write-host $(get-something).SomeProp
DataFrame.reset_index
is what you're looking for. If you don't want it saved as a column, then do:
df = df.reset_index(drop=True)
If you don't want to reassign:
df.reset_index(drop=True, inplace=True)
I use this.
public static byte[] toByteArray(InputStream is) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
byte[] b = new byte[4096];
int n = 0;
while ((n = is.read(b)) != -1) {
output.write(b, 0, n);
}
return output.toByteArray();
} finally {
output.close();
}
}
Reset the file in a correct state, commit, and push again.
If you're sure nobody else has fetched your changes yet, you can use --amend
when committing, to modify your previous commit (i.e. rewrite history), and then push. I think you'll have to use the -f
option when pushing, to force the push, though.
NULL
isn't a native part of the core C++ language, but it is part of the standard library. You need to include one of the standard header files that include its definition. #include <cstddef>
or #include <stddef.h>
should be sufficient.
The definition of NULL
is guaranteed to be available if you include cstddef
or stddef.h
. It's not guaranteed, but you are very likely to get its definition included if you include many of the other standard headers instead.
If an URL pattern starts with /
, then it's relative to the context root. The /Admin/*
URL pattern would only match pages on http://localhost:8080/EMS2/Admin/*
(assuming that /EMS2
is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*
, so your URL pattern never matches.
You need to prefix your URL patterns with /faces/Html
as well like so:
<url-pattern>/faces/Html/Admin/*</url-pattern>
You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html
path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml
.
Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping>
with multiple <url-pattern>
entries:
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/faces/Html/Employee/*</url-pattern>
<url-pattern>/faces/Html/Admin/*</url-pattern>
<url-pattern>/faces/Html/Supervisor/*</url-pattern>
</filter-mapping>
From CREATE FUNCTION
:
When a parameter of the function has a default value, the keyword
DEFAULT
must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
So you need to do:
SELECT dbo.fCalculateEstimateDate(647,DEFAULT)
Maybe this answer here will help you. Seems that you want to dispose of the context periodically. This is because the context gets bigger and bigger as the attached entities grows.
If you want to return from an outer function with an error without exit
ing you can use this trick:
do-something-complex() {
# Using `return` here would only return from `fail`, not from `do-something-complex`.
# Using `exit` would close the entire shell.
# So we (ab)use a different feature. :)
fail() { : "${__fail_fast:?$1}"; }
nested-func() {
try-this || fail "This didn't work"
try-that || fail "That didn't work"
}
nested-func
}
Trying it out:
$ do-something-complex
try-this: command not found
bash: __fail_fast: This didn't work
This has the added benefit/drawback that you can optionally turn off this feature: __fail_fast=x do-something-complex
.
Note that this causes the outermost function to return 1.
<div id="scroll">
<p>Try to add more text</p>
</div>
here's the css code
#scroll {
overflow-y:auto;
height:auto;
max-height:200px;
border:1px solid black;
width:300px;
}
here's the demo JSFIDDLE
Check if you did compress the driver or folder in where you put the .mdf file.
If so, plesae goto the driver or folder, change the compress option by
Properties -> Advanced and unticked the “Compress contents to save disk space” checkbox.
After above things, you should be able to start the service again.
I think no one actually has answered to the first question:
Why did they create those variables?
Those variables aren't strictly necessary. It's true. You can perfectly do something like this:
MONTH_CHOICES = (
("JANUARY", "January"),
("FEBRUARY", "February"),
("MARCH", "March"),
# ....
("DECEMBER", "December"),
)
month = models.CharField(max_length=9,
choices=MONTH_CHOICES,
default="JANUARY")
Why using variables is better? Error prevention and logic separation.
JAN = "JANUARY"
FEB = "FEBRUARY"
MAR = "MAR"
# (...)
MONTH_CHOICES = (
(JAN, "January"),
(FEB, "February"),
(MAR, "March"),
# ....
(DEC, "December"),
)
Now, imagine you have a view where you create a new Model instance. Instead of doing this:
new_instance = MyModel(month='JANUARY')
You'll do this:
new_instance = MyModel(month=MyModel.JAN)
In the first option you are hardcoding the value. If there is a set of values you can input, you should limit those options when coding. Also, if you eventually need to change the code at the Model layer, now you don't need to make any change in the Views layer.
I tried using this example but it failed miserably. Every time I use to invoke finish()/ finishactivity() inside a handler, I end up with this menacing java.lang.IllegalAccess Exception
. i'm not sure how did it work for the one who posed the question.
Instead the solution I found was that create a method in your activity such as
void kill_activity()
{
finish();
}
Invoke this method from inside the run method of the handler. This worked like a charm for me. Hope this helps anyone struggling with "how to close an activity from a different thread?".
In C# 6 you can use string interpolation:
string name = "John";
string result = $"Hello {name}";
The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
The two int
variables are defined in the header file. This means that every source file which includes the header will contain their definition (header inclusion is purely textual). The of course leads to multiple definition errors.
You have several options to fix this.
Make the variables static
(static int WIDTH = 1024;
). They will still exist in each source file, but their definitions will not be visible outside of the source file.
Turn their definitions into declarations by using extern
(extern int WIDTH;
) and put the definition into one source file: int WIDTH = 1024;
.
Probably the best option: make the variables const
(const int WIDTH = 1024;
). This makes them static
implicitly, and also allows them to be used as compile-time constants, allowing the compiler to use their value directly instead of issuing code to read it from the variable etc.
You could create an animation and apply it to your button view. For example:
// Locate view
ImageView diskView = (ImageView) findViewById(R.id.imageView3);
// Create an animation instance
Animation an = new RotateAnimation(0.0f, 360.0f, pivotX, pivotY);
// Set the animation's parameters
an.setDuration(10000); // duration in ms
an.setRepeatCount(0); // -1 = infinite repeated
an.setRepeatMode(Animation.REVERSE); // reverses each repeat
an.setFillAfter(true); // keep rotation after animation
// Aply animation to image view
diskView.setAnimation(an);
A simple working code to download a file with SSH.NET library is:
using (Stream fileStream = File.Create(@"C:\target\local\path\file.zip"))
{
sftp.DownloadFile("/source/remote/path/file.zip", fileStream);
}
See also Downloading a directory using SSH.NET SFTP in C#.
To explain, why your code does not work:
The second parameter of SftpClient.DownloadFile
is a stream to write a downloaded contents to.
You are passing in a read stream instead of a write stream. And moreover the path you are opening read stream with is a remote path, what cannot work with File
class operating on local files only.
Just discard the File.OpenRead
line and use a result of previous File.OpenWrite
call instead (that you are not using at all now):
Stream file1 = File.OpenWrite(localFileName);
sftp.DownloadFile(file.FullName, file1);
Or even better, use File.Create
to discard any previous contents that the local file may have.
I'm not sure if your localFileName
is supposed to hold full path, or just file name. So you may need to add a path too, if necessary (combine localFileName
with sDir
?)
If you want to be able access the matrix like so matrix[i][j]
I find it the most convinient to init it in a loop.
var matrix = [],
cols = 3;
//init the grid matrix
for ( var i = 0; i < cols; i++ ) {
matrix[i] = [];
}
this will give you [ [], [], [] ]
so matrix[0][0] matrix[1][0] return undefined and not the error "Uncaught TypeError: Cannot set property '0' of undefined"
try this,
$('#id1').html($('#id1').html().replace('dogsss','dollsss'));
"
is the correct way, the third of your tests:
<option value=""asd">test</option>
You can see this working below, or on jsFiddle.
alert($("option")[0].value);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
<option value=""asd">Test</option>_x000D_
</select>
_x000D_
Alternatively, you can delimit the attribute value with single quotes:
<option value='"asd'>test</option>
Just Re install the turbo C++ from your Computer and install again in the Directory C:\TC\ Folder.
Again The Problem exists ,then change the directory from FILE>>CHANGE DIRECTORY to C:\TC\BIN\
In my case I had Identity="ApplicationPoolIdentity"
for my IIS Application Pool.
After I added IIS APPPOOL\ApplicationName
user to SQL Server it works.
If I recall correctly, a div inside a li used to be invalid.
@Flower @Superstringcheese Div should semantically define a section of a document, but it has already practically lost this role. Span should however contain text.
If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do
str = "file_" + i.to_s.rjust(n, "0")
Working version of kgaidis's Objective C answer using Swift 3.0:
let flow = UICollectionViewFlowLayout()
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let numberOfItems = collectionView.numberOfItems(inSection: 0)
let combinedItemWidth:CGFloat = (CGFloat(numberOfItems) * flow.itemSize.width) + ((CGFloat(numberOfItems) - 1) * flow.minimumInteritemSpacing)
let padding = (collectionView.frame.size.width - combinedItemWidth) / 2
return UIEdgeInsetsMake(0, padding, 0, padding)
}
I would use the following function. I don't like sprintf
; it doesn't do what I want!!
#define hexchar(x) ((((x)&0x0F)>9)?((x)+'A'-10):((x)+'0'))
typedef signed long long Int64;
// Special printf for numbers only
// See formatting information below.
//
// Print the number "n" in the given "base"
// using exactly "numDigits".
// Print +/- if signed flag "isSigned" is TRUE.
// Use the character specified in "padchar" to pad extra characters.
//
// Examples:
// sprintfNum(pszBuffer, 6, 10, 6, TRUE, ' ', 1234); --> " +1234"
// sprintfNum(pszBuffer, 6, 10, 6, FALSE, '0', 1234); --> "001234"
// sprintfNum(pszBuffer, 6, 16, 6, FALSE, '.', 0x5AA5); --> "..5AA5"
void sprintfNum(char *pszBuffer, int size, char base, char numDigits, char isSigned, char padchar, Int64 n)
{
char *ptr = pszBuffer;
if (!pszBuffer)
{
return;
}
char *p, buf[32];
unsigned long long x;
unsigned char count;
// Prepare negative number
if (isSigned && (n < 0))
{
x = -n;
}
else
{
x = n;
}
// Set up small string buffer
count = (numDigits-1) - (isSigned?1:0);
p = buf + sizeof (buf);
*--p = '\0';
// Force calculation of first digit
// (to prevent zero from not printing at all!!!)
*--p = (char)hexchar(x%base);
x = x / base;
// Calculate remaining digits
while(count--)
{
if(x != 0)
{
// Calculate next digit
*--p = (char)hexchar(x%base);
x /= base;
}
else
{
// No more digits left, pad out to desired length
*--p = padchar;
}
}
// Apply signed notation if requested
if (isSigned)
{
if (n < 0)
{
*--p = '-';
}
else if (n > 0)
{
*--p = '+';
}
else
{
*--p = ' ';
}
}
// Print the string right-justified
count = numDigits;
while (count--)
{
*ptr++ = *p++;
}
return;
}
ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...
If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...
HTH
I had a similar issue. Killing an existing instance of the ADB process from Task Manager did not work for me.
Just few days back, I had tried to install MIPS SDK and ADT-17 earlier and Eclipse gave me the error, and I did not fix that issue.
So, now, when I got this ADB server didn't ACK, failed to start daemon... issue, I executed 'Check for Updates' in the Eclipse Help menu item. There were no updates available, but at least 'ADB server did not ACK' error disappeared.
I hope this might help in a few cases.
The accept
attribute is incredibly useful. It is a hint to browsers to only show files that are allowed for the current input
. While it can typically be overridden by users, it helps narrow down the results for users by default, so they can get exactly what they're looking for without having to sift through a hundred different file types.
Note: These examples were written based on the current specification and may not actually work in all (or any) browsers. The specification may also change in the future, which could break these examples.
h1 { font-size: 1em; margin:1em 0; }_x000D_
h1 ~ h1 { border-top: 1px solid #ccc; padding-top: 1em; }
_x000D_
<h1>Match all image files (image/*)</h1>_x000D_
<p><label>image/* <input type="file" accept="image/*"></label></p>_x000D_
_x000D_
<h1>Match all video files (video/*)</h1>_x000D_
<p><label>video/* <input type="file" accept="video/*"></label></p>_x000D_
_x000D_
<h1>Match all audio files (audio/*)</h1>_x000D_
<p><label>audio/* <input type="file" accept="audio/*"></label></p>_x000D_
_x000D_
<h1>Match all image files (image/*) and files with the extension ".someext"</h1>_x000D_
<p><label>.someext,image/* <input type="file" accept=".someext,image/*"></label></p>_x000D_
_x000D_
<h1>Match all image files (image/*) and video files (video/*)</h1>_x000D_
<p><label>image/*,video/* <input type="file" accept="image/*,video/*"></label></p>
_x000D_
The
accept
attribute may be specified to provide user agents with a hint of what file types will be accepted.If specified, the attribute must consist of a set of comma-separated tokens, each of which must be an ASCII case-insensitive match for one of the following:
The string
audio/*
- Indicates that sound files are accepted.
The string
video/*
- Indicates that video files are accepted.
The string
image/*
- Indicates that image files are accepted.
A valid MIME type with no parameters
- Indicates that files of the specified type are accepted.
A string whose first character is a U+002E FULL STOP character (.)
- Indicates that files with the specified file extension are accepted.
Please try this:
DELETE FROM `table` WHERE id >=163 and id<= 265
Where the result is negative, C truncates towards 0 rather than flooring - I learnt this reading about why Python integer division always floors here: Why Python's Integer Division Floors
The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource
annotation.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
...
}
See @TestPropertySource in the Spring docs and Javadocs.
If d is a dictionary, then d.get(k, v)
means, give me the value of k in d, unless k isn't there, in which case give me v. It's being used here to get the current count of the character, which should start at 0 if the character hasn't been encountered before.
You need to use ECHO
. Also, put the quotes around the entire file path if it contains spaces.
One other note, use >
to overwrite a file if it exists or create if it does not exist. Use >>
to append to an existing file or create if it does not exist.
Overwrite the file with a blank line:
ECHO.>"C:\My folder\Myfile.log"
Append a blank line to a file:
ECHO.>>"C:\My folder\Myfile.log"
Append text to a file:
ECHO Some text>>"C:\My folder\Myfile.log"
Append a variable to a file:
ECHO %MY_VARIABLE%>>"C:\My folder\Myfile.log"
Lets use the titanic dataset from the seaborn package as an example
# Load dataset (pip install seaborn)
>> import seaborn.apionly as sns
>> titanic = sns.load_dataset('titanic')
using the column names
>> titanic.loc[:,['sex','age','fare']]
using the column indices
>> titanic.iloc[:,[2,3,6]]
using ix (Older than Pandas <.20 version)
>> titanic.ix[:,[‘sex’,’age’,’fare’]]
or
>> titanic.ix[:,[2,3,6]]
using the reindex method
>> titanic.reindex(columns=['sex','age','fare'])
For me the problem turned out to be minHeight and minWidth on some of the Android themes.
On the Button element, add:
<Button android:minHeight="0dp" android:minWidth="0dp" ...
Or in your button's style:
<item name="android:minHeight">0dp</item>
<item name="android:minWidth">0dp</item>
You must check if result returned by mysql_query is false.
$r = mysql_qyery("...");
if ($r) {
mysql_fetch_assoc($r);
}
You can use @mysql_fetch_assoc($r)
to avoid error displaying.
Something I wrote up incase anyone comes across an issue with people hitting backspace while thinking they are in a form field
window.addEventListener("keydown", function(e){
/*
* keyCode: 8
* keyIdentifier: "U+0008"
*/
if(e.keyCode === 8 && document.activeElement !== 'text') {
e.preventDefault();
alert('Prevent page from going back');
}
});
Yo could also set labels = FALSE
inside axis(...)
and print the labels in a separate command with Text. With this option you can rotate the text the text in case you need it
lablist<-as.vector(c(1:10))
axis(1, at=seq(1, 10, by=1), labels = FALSE)
text(seq(1, 10, by=1), par("usr")[3] - 0.2, labels = lablist, srt = 45, pos = 1, xpd = TRUE)
Detailed explanation here
Have you activated your environment? Also you could try this: vscode select venv
The simplest way I've found to do this in Windows is with WinRAR:
They're different characters. \r
is carriage return, and \n
is line feed.
On "old" printers, \r
sent the print head back to the start of the line, and \n
advanced the paper by one line. Both were therefore necessary to start printing on the next line.
Obviously that's somewhat irrelevant now, although depending on the console you may still be able to use \r
to move to the start of the line and overwrite the existing text.
More importantly, Unix tends to use \n
as a line separator; Windows tends to use \r\n
as a line separator and Macs (up to OS 9) used to use \r
as the line separator. (Mac OS X is Unix-y, so uses \n
instead; there may be some compatibility situations where \r
is used instead though.)
For more information, see the Wikipedia newline article.
EDIT: This is language-sensitive. In C# and Java, for example, \n
always means Unicode U+000A, which is defined as line feed. In C and C++ the water is somewhat muddier, as the meaning is platform-specific. See comments for details.
If you're using SQL Management Studio, please goto connection properties and click on "Trust server certificated"
No, you don't have to include all of POI's dependencies. Maven's transitive dependency mechanism will take care of that. As noted you just have to express a dependency on the appropriate POI artifact. For example:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8-beta4</version>
</dependency>
Edit(UPDATE): I don't know about previous versions but to resolve imports to XSSFWorkbook and other classes in org.apache.poi package you need to add dependency for poi-ooxml too. The dependencies will be:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
One more trick, search photos by hashtags:
GET https://www.instagram.com/graphql/query/?query_hash=3e7706b09c6184d5eafd8b032dbcf487&variables={"tag_name":"nature","first":25,"after":""}
Where:
query_hash
- permanent value(i belive its hash of 17888483320059182, can be changed in future)
tag_name
- the title speaks for itself
first
- amount of items to get (I do not know why, but this value does not work as expected. The actual number of returned photos is slightly larger than the value multiplied by 4.5 (about 110 for the value 25, and about 460 for the value 100))
after
- id of the last item if you want to get items from that id. Value of end_cursor
from JSON response can be used here.
You should really use the following instead (works in all newer browsers):
window.addEventListener('DOMContentLoaded', init, false);
Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:
$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);
Output:
Array
(
[0] => 4
)
Now:
$key = 4;
$value = $array[$key];
print $value;
Output:
Hello There
Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.
e.g. if you do this:
SELECT 1 / 2
you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.
e.g.
SELECT CAST(1 AS DECIMAL) / 2
gives 0.500000
Private Sub CommandButton1_Click()
Workbooks("Textfile_Receiving").Sheets("menu").Range("g1").Value = PROV.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g2").Value = MUN.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g3").Value = CAT.Text
Workbooks("Textfile_Receiving").Sheets("menu").Range("g4").Value = Label5.Caption
Me.Hide
Run "filename"
End Sub
Private Sub MUN_Change()
Dim r As Integer
r = 2
While Range("m" & CStr(r)).Value <> ""
If Range("m" & CStr(r)).Value = MUN.Text Then
Label5.Caption = Range("n" & CStr(r)).Value
End If
r = r + 1
Wend
End Sub
Private Sub PROV_Change()
If PROV.Text = "LAGUNA" Then
MUN.Text = ""
MUN.RowSource = "Menu!M26:M56"
ElseIf PROV.Text = "CAVITE" Then
MUN.Text = ""
MUN.RowSource = "Menu!M2:M25"
ElseIf PROV.Text = "QUEZON" Then
MUN.Text = ""
MUN.RowSource = "Menu!M57:M97"
End If
End Sub
In reality memory locality has a huge performance influence in real processing.
The increased use of disk streaming in "big data" processing vs random access shows how structuring your application around this can dramatically improve performance on a larger scale.
If there is any way to access an array sequentially that is by far the best performing. Designing with this as a goal should be at least considered if performance is important.
In addition to
Mac:
~/.vagrant.d/
Windows:
C:\Users\%userprofile%\.vagrant.d\boxes
You have to delete the files in VirtualBox/OtherVMprovider to make a clean start.
I have a helper function like:
public static string GetString(object o)
{
if (o == DBNull.Value)
return "";
return o.ToString();
}
then I use it to extract the string:
tbUserName.Text = GetString(reader["UserName"]);
Check on custom font name whether checkbox on "Target membership" is added. This should help.
Leaving this here for info,
This error can also be caused if PostgreSQL server is on another machine and is not listening on external interfaces.
To debug this specific problem, you can follow theses steps:
sudo vim /etc/postgresql/9.3/main/postgresql.conf
listen_addresses = '*'
sudo /etc/init.d/postgresql restart
(Note, the commands above are for ubuntu. Other linux distro or OS may have different path to theses files)
Note: using '*'
for listening addresses will listen on all interfaces. If you do '0.0.0.0'
then it'll listen for all ipv4 and if you do '::'
then it'll listen for all ipv6.
http://www.postgresql.org/docs/9.3/static/runtime-config-connection.html
There is an operator just for this. For example, if I wanted to change a variable i by 3 then:
var someValue = 9;
var Increment = 3;
for(var i=0;i<someValue;i+=Increment){
//do whatever
}
_x000D_
var someValue = 3;
var Increment = 3;
for(var i=9;i>someValue;i+=Increment){
//do whatever
}
_x000D_
Make sure you are using binding to get component props in REACT
class FileUploader extends Component {
constructor (props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
onChange=(e,props)=>{
const files = e.target.files;
const selectedFile = files[0];
ProcessFileUpload(selectedFile,props.ProgressCallBack,props.ErrorCallBack,props.CompleatedCallBack,props.BaseURL,props.Location,props.FilesAllowed);
}
handleClick = () => {
this.refs.fileUploader.click();
}
render()
{
return(
<div>
<button type="button" onClick={this.handleClick}>Select File</button>
<input type='file' onChange={(e)=>this.onChange(e,this.props)} ref="fileUploader" style={{display:"none"}} />
</div>)
}
}