def my_string = "some string"
println "here: " + my_string
Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.
You are looking for str.rsplit()
, with a limit:
print x.rsplit('-', 1)[0]
.rsplit()
searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.
Another option is to use str.rpartition()
, which will only ever split just once:
print x.rpartition('-')[0]
For splitting just once, str.rpartition()
is the faster method as well; if you need to split more than once you can only use str.rsplit()
.
Demo:
>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'
and the same with str.rpartition()
>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'
If your collections object is a list, I would use the sort method, as proposed in the other answers.
However, if it is not a list, and you don't really care about what type of Collection object is returned, I think it is faster to create a TreeSet instead of a List:
TreeSet sortedSet = new TreeSet(myComparator);
sortedSet.addAll(myCollectionToBeSorted);
jQuery:
$("#tbodyid").empty();
HTML:
<table>
<tbody id="tbodyid">
<tr>
<td>something</td>
</tr>
</tbody>
</table>
Works for me
http://jsfiddle.net/mbsh3/
EDIT: Okay, so you don't want your local time (which isn't Australia) to contribute to the result, but instead the Australian time zone. Your existing code should be absolutely fine then, although Sydney is currently UTC+11, not UTC+10.. Short but complete test app:
import java.util.*;
import java.text.*;
public class Test {
public static void main(String[] args) throws InterruptedException {
Date date = new Date(1318386508000L);
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
String formatted = format.format(date);
System.out.println(formatted);
format.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
formatted = format.format(date);
System.out.println(formatted);
}
}
Output:
12/10/2011 02:28:28
12/10/2011 13:28:28
I would also suggest you start using Joda Time which is simply a much nicer date/time API...
EDIT: Note that if your system doesn't know about the Australia/Sydney
time zone, it would show UTC. For example, if I change the code about to use TimeZone.getTimeZone("blah/blah")
it will show the UTC value twice. I suggest you print TimeZone.getTimeZone("Australia/Sydney").getDisplayName()
and see what it says... and check your code for typos too :)
Visual studio 2015 does not show MVC project template if you select .Net 4.0 or below. Select .Net 4.5 or above, and you will be able to see MVC project.
This is what showed when you select .NET Framework 4:
and this when you select .NET Framework 4.5:
However, make sure you have installed web developers tools. To do so, go to Add / remove programs -> Visual 2015 -> Modify --> Web developer tools : Check and proceed with the installation.
New-style classes (i.e. subclassed from object
, which is the default in Python 3) have a __subclasses__
method which returns the subclasses:
class Foo(object): pass
class Bar(Foo): pass
class Baz(Foo): pass
class Bing(Bar): pass
Here are the names of the subclasses:
print([cls.__name__ for cls in Foo.__subclasses__()])
# ['Bar', 'Baz']
Here are the subclasses themselves:
print(Foo.__subclasses__())
# [<class '__main__.Bar'>, <class '__main__.Baz'>]
Confirmation that the subclasses do indeed list Foo
as their base:
for cls in Foo.__subclasses__():
print(cls.__base__)
# <class '__main__.Foo'>
# <class '__main__.Foo'>
Note if you want subsubclasses, you'll have to recurse:
def all_subclasses(cls):
return set(cls.__subclasses__()).union(
[s for c in cls.__subclasses__() for s in all_subclasses(c)])
print(all_subclasses(Foo))
# {<class '__main__.Bar'>, <class '__main__.Baz'>, <class '__main__.Bing'>}
Note that if the class definition of a subclass hasn't been executed yet - for example, if the subclass's module hasn't been imported yet - then that subclass doesn't exist yet, and __subclasses__
won't find it.
You mentioned "given its name". Since Python classes are first-class objects, you don't need to use a string with the class's name in place of the class or anything like that. You can just use the class directly, and you probably should.
If you do have a string representing the name of a class and you want to find that class's subclasses, then there are two steps: find the class given its name, and then find the subclasses with __subclasses__
as above.
How to find the class from the name depends on where you're expecting to find it. If you're expecting to find it in the same module as the code that's trying to locate the class, then
cls = globals()[name]
would do the job, or in the unlikely case that you're expecting to find it in locals,
cls = locals()[name]
If the class could be in any module, then your name string should contain the fully-qualified name - something like 'pkg.module.Foo'
instead of just 'Foo'
. Use importlib
to load the class's module, then retrieve the corresponding attribute:
import importlib
modname, _, clsname = name.rpartition('.')
mod = importlib.import_module(modname)
cls = getattr(mod, clsname)
However you find the class, cls.__subclasses__()
would then return a list of its subclasses.
Update September 2016
Swift 3.0: Use type(of:)
, e.g. type(of: someThing)
(since the dynamicType
keyword has been removed)
Update October 2015:
I updated the examples below to the new Swift 2.0 syntax (e.g. println
was replaced with print
, toString()
is now String()
).
From the Xcode 6.3 release notes:
@nschum points out in the comments that the Xcode 6.3 release notes show another way:
Type values now print as the full demangled type name when used with println or string interpolation.
import Foundation
class PureSwiftClass { }
var myvar0 = NSString() // Objective-C class
var myvar1 = PureSwiftClass()
var myvar2 = 42
var myvar3 = "Hans"
print( "String(myvar0.dynamicType) -> \(myvar0.dynamicType)")
print( "String(myvar1.dynamicType) -> \(myvar1.dynamicType)")
print( "String(myvar2.dynamicType) -> \(myvar2.dynamicType)")
print( "String(myvar3.dynamicType) -> \(myvar3.dynamicType)")
print( "String(Int.self) -> \(Int.self)")
print( "String((Int?).self -> \((Int?).self)")
print( "String(NSString.self) -> \(NSString.self)")
print( "String(Array<String>.self) -> \(Array<String>.self)")
Which outputs:
String(myvar0.dynamicType) -> __NSCFConstantString
String(myvar1.dynamicType) -> PureSwiftClass
String(myvar2.dynamicType) -> Int
String(myvar3.dynamicType) -> String
String(Int.self) -> Int
String((Int?).self -> Optional<Int>
String(NSString.self) -> NSString
String(Array<String>.self) -> Array<String>
Update for Xcode 6.3:
You can use the _stdlib_getDemangledTypeName()
:
print( "TypeName0 = \(_stdlib_getDemangledTypeName(myvar0))")
print( "TypeName1 = \(_stdlib_getDemangledTypeName(myvar1))")
print( "TypeName2 = \(_stdlib_getDemangledTypeName(myvar2))")
print( "TypeName3 = \(_stdlib_getDemangledTypeName(myvar3))")
and get this as output:
TypeName0 = NSString
TypeName1 = __lldb_expr_26.PureSwiftClass
TypeName2 = Swift.Int
TypeName3 = Swift.String
Original answer:
Prior to Xcode 6.3 _stdlib_getTypeName
got the mangled type name of a variable. Ewan Swick's blog entry helps to decipher these strings:
e.g. _TtSi
stands for Swift's internal Int
type.
Use iloc
:
df = df.iloc[3:]
will give you a new df without the first three rows.
The simple jquery source for the same -
$("input:radio[name='group1']").click(function() {
$('.desc').hide();
$('#' + $("input:radio[name='group1']:checked").val()).show();
});
In order to make it little more appropriate just add checked to first option --
<div><label><input type="radio" name="group1" value="opt1" checked>opt1</label></div>
remove .desc class from styling and modify divs like --
<div id="opt1" class="desc">lorem ipsum dolor</div>
<div id="opt2" class="desc" style="display: none;">consectetur adipisicing</div>
<div id="opt3" class="desc" style="display: none;">sed do eiusmod tempor</div>
it will really look good any-ways.
Anyway, here is how to fix it:
Go to Start->Control Panel->System->Advanced(tab)->Environment Variables->System Variables->New:
Variable name: _JAVA_OPTIONS
Variable value: -Xmx512M
taken from this link
This error occurs when the linker can't find WinMain
function, so it is probably missing. In your case, you are probably missing main
too.
Consider the following Windows API-level program:
#define NOMINMAX
#include <windows.h>
int main()
{
MessageBox( 0, "Blah blah...", "My Windows app!", MB_SETFOREGROUND );
}
Now let's build it using GNU toolchain (i.e. g++), no special options. Here gnuc
is just a batch file that I use for that. It only supplies options to make g++ more standard:
C:\test> gnuc x.cpp C:\test> objdump -x a.exe | findstr /i "^subsystem" Subsystem 00000003 (Windows CUI) C:\test> _
This means that the linker by default produced a console subsystem executable. The subsystem value in the file header tells Windows what services the program requires. In this case, with console system, that the program requires a console window.
This also causes the command interpreter to wait for the program to complete.
Now let's build it with GUI subsystem, which just means that the program does not require a console window:
C:\test> gnuc x.cpp -mwindows C:\test> objdump -x a.exe | findstr /i "^subsystem" Subsystem 00000002 (Windows GUI) C:\test> _
Hopefully that's OK so far, although the -mwindows
flag is just semi-documented.
Building without that semi-documented flag one would have to more specifically tell the linker which subsystem value one desires, and some Windows API import libraries will then in general have to be specified explicitly:
C:\test> gnuc x.cpp -Wl,-subsystem,windows C:\test> objdump -x a.exe | findstr /i "^subsystem" Subsystem 00000002 (Windows GUI) C:\test> _
That worked fine, with the GNU toolchain.
But what about the Microsoft toolchain, i.e. Visual C++?
Well, building as a console subsystem executable works fine:
C:\test> msvc x.cpp user32.lib x.cpp C:\test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows" 3 subsystem (Windows CUI) C:\test> _
However, with Microsoft's toolchain building as GUI subsystem does not work by default:
C:\test> msvc x.cpp user32.lib /link /subsystem:windows x.cpp LIBCMT.lib(wincrt0.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartu p x.exe : fatal error LNK1120: 1 unresolved externals C:\test> _
Technically this is because Microsoft’s linker is non-standard by default for GUI subsystem. By default, when the subsystem is GUI, then Microsoft's linker uses a runtime library entry point, the function where the machine code execution starts, called winMainCRTStartup
, that calls Microsoft's non-standard WinMain
instead of standard main
.
No big deal to fix that, though.
All you have to do is to tell Microsoft's linker which entry point to use, namely mainCRTStartup
, which calls standard main
:
C:\test> msvc x.cpp user32.lib /link /subsystem:windows /entry:mainCRTStartup x.cpp C:\test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows" 2 subsystem (Windows GUI) C:\test> _
No problem, but very tedious. And so arcane and hidden that most Windows programmers, who mostly only use Microsoft’s non-standard-by-default tools, do not even know about it, and mistakenly think that a Windows GUI subsystem program “must” have non-standard WinMain
instead of standard main
. In passing, with C++0x Microsoft will have a problem with this, since the compiler must then advertize whether it's free-standing or hosted (when hosted it must support standard main
).
Anyway, that's the reason why g++ can complain about WinMain
missing: it's a silly non-standard startup function that Microsoft's tools require by default for GUI subsystem programs.
But as you can see above, g++ has no problem with standard main
even for a GUI subsystem program.
So what could be the problem?
Well, you are probably missing a main
. And you probably have no (proper) WinMain
either! And then g++, after having searched for main
(no such), and for Microsoft's non-standard WinMain
(no such), reports that the latter is missing.
Testing with an empty source:
C:\test> type nul >y.cpp C:\test> gnuc y.cpp -mwindows c:/program files/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../libmingw32.a(main.o):main.c:(.text+0xd2): undefined referen ce to `WinMain@16' collect2: ld returned 1 exit status C:\test> _
Consider we have a scale between (OMin, Omax) and we we have a value X in this range
We want to convert it to scale (NMin, NMax)
We know X and we need to find Y, the ratio must be same:
=> (Y-NMin)/(NMax-NMin) = (X-OMin)/(OMax-OMin)
=> (Y-NMin)/NewRange = (X-OMin)/OldRange
=> Y = ((X-OMin)*NewRange)/oldRange)+NMin Answer
Pragmatically we can write this rquation like this:
private fun convertScale(oldValueToConvert:Int): Float {
// Old Scale 50-100
val oldScaleMin = 50
val oldScaleMax = 100
val oldScaleRange= (oldScaleMax - oldScaleMin)
//new Scale 0-1
val newScaleMin = 0.0f
val newScaleMax = 1.0f
val newScaleRange= (newScaleMax - newScaleMin)
return ((oldValueToConvert - oldScaleMin)* newScaleRange/ oldScaleRange) + newScaleMin
}
JAVA
/**
*
* @param x
* @param inMin
* @param inMax
* @param outMin
* @param outMax
* @return
*/
private long normalize(long x, long inMin, long inMax, long outMin, long outMax) {
long outRange = outMax - outMin;
long inRange = inMax - inMin;
return (x - inMin) *outRange / inRange + outMin;
}
Usage:
float brightness = normalize(progress, 0, 10, 0,255);
Lets give an example that would explain the difference between hashtable and dictionary.
Here is a method that implements hashtable
public void MethodHashTable()
{
Hashtable objHashTable = new Hashtable();
objHashTable.Add(1, 100); // int
objHashTable.Add(2.99, 200); // float
objHashTable.Add('A', 300); // char
objHashTable.Add("4", 400); // string
lblDisplay1.Text = objHashTable[1].ToString();
lblDisplay2.Text = objHashTable[2.99].ToString();
lblDisplay3.Text = objHashTable['A'].ToString();
lblDisplay4.Text = objHashTable["4"].ToString();
// ----------- Not Possible for HashTable ----------
//foreach (KeyValuePair<string, int> pair in objHashTable)
//{
// lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
//}
}
The following is for dictionary
public void MethodDictionary()
{
Dictionary<string, int> dictionary = new Dictionary<string, int>();
dictionary.Add("cat", 2);
dictionary.Add("dog", 1);
dictionary.Add("llama", 0);
dictionary.Add("iguana", -1);
//dictionary.Add(1, -2); // Compilation Error
foreach (KeyValuePair<string, int> pair in dictionary)
{
lblDisplay.Text = pair.Value + " " + lblDisplay.Text;
}
}
I was wondering how to do this myself; it seems Gmail has since silently implemented this feature. I created the following filter:
Matches: subject:([test])
Do this: Skip Inbox
And then I sent a message with the subject
[test] foo
And the message was archived! So it seems all that is necessary is to create a filter for the subject prefix you wish to handle.
You could use setInterval
for this.
<script type="text/javascript">
function myFunction () {
console.log('Executed!');
}
var interval = setInterval(function () { myFunction(); }, 60000);
</script>
Disable the timer by setting clearInterval(interval)
.
See this Fiddle: http://jsfiddle.net/p6NJt/2/
Extension to @Stevoisiak's answer and dealing with non-Latin characters. Only one way will display the non-Latin characters to you. The one method is different on both Python 3 and Python 2.
Input
xml = ElementTree.fromstring('<Person Name="???" />')
xml = ElementTree.Element("Person", Name="???") # Read Note about Python 2
NOTE: In Python 2, when calling the
toString(...)
code, assigningxml
withElementTree.Element("Person", Name="???")
will raise an error...
UnicodeDecodeError: 'ascii' codec can't decode byte 0xed in position 0: ordinal not in range(128)
Output
ElementTree.tostring(xml)
# Python 3 (???): b'<Person Name="크리스" />'
# Python 3 (John): b'<Person Name="John" />'
# Python 2 (???): <Person Name="크리스" />
# Python 2 (John): <Person Name="John" />
ElementTree.tostring(xml, encoding='unicode')
# Python 3 (???): <Person Name="???" /> <-------- Python 3
# Python 3 (John): <Person Name="John" />
# Python 2 (???): LookupError: unknown encoding: unicode
# Python 2 (John): LookupError: unknown encoding: unicode
ElementTree.tostring(xml, encoding='utf-8')
# Python 3 (???): b'<Person Name="\xed\x81\xac\xeb\xa6\xac\xec\x8a\xa4" />'
# Python 3 (John): b'<Person Name="John" />'
# Python 2 (???): <Person Name="???" /> <-------- Python 2
# Python 2 (John): <Person Name="John" />
ElementTree.tostring(xml).decode()
# Python 3 (???): <Person Name="크리스" />
# Python 3 (John): <Person Name="John" />
# Python 2 (???): <Person Name="크리스" />
# Python 2 (John): <Person Name="John" />
First install SQLSysClrTypes for Ms SQL 2014 and secondly install ReportViewer for ms sql 2014
Restart your application or project, in my case its resolved.
I recently found out that :active:focus
does the same thing in css as :active:hover
if you need to override a custom css library, they might use both.
I recently came across this requirement myself, and I decided to implement an ActionFilter
to handle this.
public class ArrayInputAttribute : ActionFilterAttribute
{
private readonly string _parameterName;
public ArrayInputAttribute(string parameterName)
{
_parameterName = parameterName;
Separator = ',';
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ActionArguments.ContainsKey(_parameterName))
{
string parameters = string.Empty;
if (actionContext.ControllerContext.RouteData.Values.ContainsKey(_parameterName))
parameters = (string) actionContext.ControllerContext.RouteData.Values[_parameterName];
else if (actionContext.ControllerContext.Request.RequestUri.ParseQueryString()[_parameterName] != null)
parameters = actionContext.ControllerContext.Request.RequestUri.ParseQueryString()[_parameterName];
actionContext.ActionArguments[_parameterName] = parameters.Split(Separator).Select(int.Parse).ToArray();
}
}
public char Separator { get; set; }
}
I am applying it like so (note that I used 'id', not 'ids', as that is how it is specified in my route):
[ArrayInput("id", Separator = ';')]
public IEnumerable<Measure> Get(int[] id)
{
return id.Select(i => GetData(i));
}
And the public url would be:
/api/Data/1;2;3;4
You may have to refactor this to meet your specific needs.
GnuPG can be used as cross-platform password manager, including GIT HTTPS credetials. Just use your GPG key-pair to encrypt/decrypt passwords(tokens...). To encrypt token(password) run:
gpg -e -o [PATH_TO_ENCRYPTED_TOKEN] -r "[GPG_KEY_USER_ID]"
type the token (or copy-paste it) then press Ctrl+D for ending input, or use file name with this token. Then make custom git credential helper: BASH file with name git-credential-[HELPER_LAST_NAME] (without SH extension):
#!/bin/bash
token=`gpg -d -r "[GPG_KEY_USER_ID]" [PATH_TO_ENCRYPTED_TOKEN] 2>/dev/null`
echo protocol=https
echo host=[YOUR_HOST]
echo username=[YOUR_USER_NAME]
echo password=$token
On MS-WINDOWS in GIT-BASH path names must use UNIX file separator - "/", just run in git-bash "echo $PATH"! Then put the helper into place as in $PATH. Then add and check the helper:
git config --global credential.helper [HELPER_LAST_NAME]
#then check it (password will be printed as plain text!!!):
git credential-[HELPER_LAST_NAME]
GnuPG can be used as password manager in Maven projects instead of Maven's password-encryption method. And so on.
Try defaulting the exports in your components:
import React from 'react';
import Navbar from 'react-bootstrap/lib/Navbar';
export default class MyNavbar extends React.Component {
render(){
return (
<Navbar className="navbar-dark" fluid>
...
</Navbar>
);
}
}
by using default you express that's going to be member in that module which would be imported if no specific member name is provided. You could also express you want to import the specific member called MyNavbar by doing so: import {MyNavbar} from './comp/my-navbar.jsx'; in this case, no default is needed
Simple JAVA code to calculate cosine similarity
/**
* Method to calculate cosine similarity of vectors
* 1 - exactly similar (angle between them is 0)
* 0 - orthogonal vectors (angle between them is 90)
* @param vector1 - vector in the form [a1, a2, a3, ..... an]
* @param vector2 - vector in the form [b1, b2, b3, ..... bn]
* @return - the cosine similarity of vectors (ranges from 0 to 1)
*/
private double cosineSimilarity(List<Double> vector1, List<Double> vector2) {
double dotProduct = 0.0;
double normA = 0.0;
double normB = 0.0;
for (int i = 0; i < vector1.size(); i++) {
dotProduct += vector1.get(i) * vector2.get(i);
normA += Math.pow(vector1.get(i), 2);
normB += Math.pow(vector2.get(i), 2);
}
return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
}
Check out this fiddle ... you're doing it correctly. Make sure the id is content and also check to see there are no other elements with the same id. If there are multiple elements with the same id, it will bind to the first one. That might be why you arn't seeing it.
To make background transparent, set shape
as None
.
See the image below:
EDIT:
For Android Studio 3.0,
you can set it from Legacy
Tab
In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with %
which will remove characters from the end of the string or #
which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed. If you double the character, the longest will be removed.
$ a='hello:world'
$ b=${a%:*}
$ echo "$b"
hello
$ a='hello:world:of:tomorrow'
$ echo "${a%:*}"
hello:world:of
$ echo "${a%%:*}"
hello
$ echo "${a#*:}"
world:of:tomorrow
$ echo "${a##*:}"
tomorrow
You can use this way to format your currency needing.
var xx = new Intl.NumberFormat(‘en-US’, {
style: ‘currency’,
currency: ‘USD’,
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
xx.format(123456.789); // ‘$123,456.79’
For more info you can access this link.
https://www.justinmccandless.com/post/formatting-currency-in-javascript/
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
// ...
}
You can use Hash Map as given in the example below:
import java.util.HashMap;
import java.util.Set;
/**
*
* @author Abdul Rab Khan
*
*/
public class CounterExample {
public static void main(String[] args) {
String[] array = { "name1", "name1", "name2", "name2", "name2" };
countStringOccurences(array);
}
/**
* This method process the string array to find the number of occurrences of
* each string element
*
* @param strArray
* array containing string elements
*/
private static void countStringOccurences(String[] strArray) {
HashMap<String, Integer> countMap = new HashMap<String, Integer>();
for (String string : strArray) {
if (!countMap.containsKey(string)) {
countMap.put(string, 1);
} else {
Integer count = countMap.get(string);
count = count + 1;
countMap.put(string, count);
}
}
printCount(countMap);
}
/**
* This method will print the occurrence of each element
*
* @param countMap
* map containg string as a key, and its count as the value
*/
private static void printCount(HashMap<String, Integer> countMap) {
Set<String> keySet = countMap.keySet();
for (String string : keySet) {
System.out.println(string + " : " + countMap.get(string));
}
}
}
ran across this page and several like it all talking about the GIT_DISCOVERY_ACROSS_FILESYSTEM not set message. In my case our sys admin had decided that the apache2 directory needed to be on a mounted filesystem in case the disk for the server stopped working and had to get rebuilt. I found this with a simple df command:
--> UBIk <--:root@ns1:[/etc]
--PRODUCTION--(16:48:43)--> df -h
Filesystem Size Used Avail Use% Mounted on
<snip>
/dev/mapper/vgraid-lvapache 63G 54M 60G 1% /etc/apache2
<snip>
To fix this I just put the following in the root user's shell (as they are the only ones who need to be looking at etckeeper revisions:
export GIT_DISCOVERY_ACROSS_FILESYSTEM=1
and all was well and good...much joy.
More notes:
--> UBIk <--:root@ns1:[/etc]
--PRODUCTION--(16:48:54)--> export GIT_DISCOVERY_ACROSS_FILESYSTEM=0
--> UBIk <--:root@ns1:[/etc]
--PRODUCTION--(16:57:35)--> git status
On branch master
nothing to commit, working tree clean
--> UBIk <--:root@ns1:[/etc]
--PRODUCTION--(16:57:40)--> touch apache2/me
--> UBIk <--:root@ns1:[/etc]
--PRODUCTION--(16:57:45)--> git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
apache2/me
nothing added to commit but untracked files present (use "git add" to track)
--> UBIk <--:root@ns1:[/etc]
--PRODUCTION--(16:57:47)--> cd apache2
--> UBIk <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:57:50)--> git status
fatal: Not a git repository (or any parent up to mount point /etc/apache2)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
--> UBIk <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:57:52)--> export GIT_DISCOVERY_ACROSS_FILESYSTEM=1
--> UBIk <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:58:59)--> git status
On branch master
Untracked files:
(use "git add <file>..." to include in what will be committed)
me
nothing added to commit but untracked files present (use "git add" to track)
Hopefully that will help someone out somewhere... -wc
Here's a one page cart written in Javascript with localStorage. Here's a full working pen. Previously found on Codebox
cart.js
var cart = {
// (A) PROPERTIES
hPdt : null, // HTML products list
hItems : null, // HTML current cart
items : {}, // Current items in cart
// (B) LOCALSTORAGE CART
// (B1) SAVE CURRENT CART INTO LOCALSTORAGE
save : function () {
localStorage.setItem("cart", JSON.stringify(cart.items));
},
// (B2) LOAD CART FROM LOCALSTORAGE
load : function () {
cart.items = localStorage.getItem("cart");
if (cart.items == null) { cart.items = {}; }
else { cart.items = JSON.parse(cart.items); }
},
// (B3) EMPTY ENTIRE CART
nuke : function () {
if (confirm("Empty cart?")) {
cart.items = {};
localStorage.removeItem("cart");
cart.list();
}
},
// (C) INITIALIZE
init : function () {
// (C1) GET HTML ELEMENTS
cart.hPdt = document.getElementById("cart-products");
cart.hItems = document.getElementById("cart-items");
// (C2) DRAW PRODUCTS LIST
cart.hPdt.innerHTML = "";
let p, item, part;
for (let id in products) {
// WRAPPER
p = products[id];
item = document.createElement("div");
item.className = "p-item";
cart.hPdt.appendChild(item);
// PRODUCT IMAGE
part = document.createElement("img");
part.src = "images/" +p.img;
part.className = "p-img";
item.appendChild(part);
// PRODUCT NAME
part = document.createElement("div");
part.innerHTML = p.name;
part.className = "p-name";
item.appendChild(part);
// PRODUCT DESCRIPTION
part = document.createElement("div");
part.innerHTML = p.desc;
part.className = "p-desc";
item.appendChild(part);
// PRODUCT PRICE
part = document.createElement("div");
part.innerHTML = "$" + p.price;
part.className = "p-price";
item.appendChild(part);
// ADD TO CART
part = document.createElement("input");
part.type = "button";
part.value = "Add to Cart";
part.className = "cart p-add";
part.onclick = cart.add;
part.dataset.id = id;
item.appendChild(part);
}
// (C3) LOAD CART FROM PREVIOUS SESSION
cart.load();
// (C4) LIST CURRENT CART ITEMS
cart.list();
},
// (D) LIST CURRENT CART ITEMS (IN HTML)
list : function () {
// (D1) RESET
cart.hItems.innerHTML = "";
let item, part, pdt;
let empty = true;
for (let key in cart.items) {
if(cart.items.hasOwnProperty(key)) { empty = false; break; }
}
// (D2) CART IS EMPTY
if (empty) {
item = document.createElement("div");
item.innerHTML = "Cart is empty";
cart.hItems.appendChild(item);
}
// (D3) CART IS NOT EMPTY - LIST ITEMS
else {
let p, total = 0, subtotal = 0;
for (let id in cart.items) {
// ITEM
p = products[id];
item = document.createElement("div");
item.className = "c-item";
cart.hItems.appendChild(item);
// NAME
part = document.createElement("div");
part.innerHTML = p.name;
part.className = "c-name";
item.appendChild(part);
// REMOVE
part = document.createElement("input");
part.type = "button";
part.value = "X";
part.dataset.id = id;
part.className = "c-del cart";
part.addEventListener("click", cart.remove);
item.appendChild(part);
// QUANTITY
part = document.createElement("input");
part.type = "number";
part.value = cart.items[id];
part.dataset.id = id;
part.className = "c-qty";
part.addEventListener("change", cart.change);
item.appendChild(part);
// SUBTOTAL
subtotal = cart.items[id] * p.price;
total += subtotal;
}
// EMPTY BUTTONS
item = document.createElement("input");
item.type = "button";
item.value = "Empty";
item.addEventListener("click", cart.nuke);
item.className = "c-empty cart";
cart.hItems.appendChild(item);
// CHECKOUT BUTTONS
item = document.createElement("input");
item.type = "button";
item.value = "Checkout - " + "$" + total;
item.addEventListener("click", cart.checkout);
item.className = "c-checkout cart";
cart.hItems.appendChild(item);
}
},
// (E) ADD ITEM INTO CART
add : function () {
if (cart.items[this.dataset.id] == undefined) {
cart.items[this.dataset.id] = 1;
} else {
cart.items[this.dataset.id]++;
}
cart.save();
cart.list();
},
// (F) CHANGE QUANTITY
change : function () {
if (this.value == 0) {
delete cart.items[this.dataset.id];
} else {
cart.items[this.dataset.id] = this.value;
}
cart.save();
cart.list();
},
// (G) REMOVE ITEM FROM CART
remove : function () {
delete cart.items[this.dataset.id];
cart.save();
cart.list();
},
// (H) CHECKOUT
checkout : function () {
// SEND DATA TO SERVER
// CHECKS
// SEND AN EMAIL
// RECORD TO DATABASE
// PAYMENT
// WHATEVER IS REQUIRED
alert("TO DO");
/*
var data = new FormData();
data.append('cart', JSON.stringify(cart.items));
data.append('products', JSON.stringify(products));
var xhr = new XMLHttpRequest();
xhr.open("POST", "SERVER-SCRIPT");
xhr.onload = function(){ ... };
xhr.send(data);
*/
}
};
window.addEventListener("DOMContentLoaded", cart.init);
I have worked with Xamarin. Here are the positives and negatives I have found:
Positives
Negatives
You could do this pretty easily with my date-shortcode package:
const dateShortcode = require('date-shortcode')
var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'
As long as you still have access to the mac which was used to generate the original distribution certificate it's very simple.
Just use that mac's Keychain Access application to export both the certificate and the private key. Select both using shift or command and right click to export to a .p12 file.
Attached a screenshot to make it very clear.
On your mac, import that .p12 file and you are good to go (just make sure you have a valid provisioning profile).
private void datagrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
string test = this.datagrid.Columns[e.ColumnIndex].HeaderText;
}
This code will get the HeaderText
value.
if
and grep -Eq
arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
echo 'second'
fi
where:
-q
prevents grep
from producing output, it just produces the exit status-E
enables extended regular expressionsI like this because:
case
One downside is that this is likely slower than case
since it calls an external grep
program, but I tend to consider performance last when using Bash.
case
is POSIX 7
Bash appears to follow POSIX by default without shopt
as mentioned by https://stackoverflow.com/a/4555979/895245
Here is the quote: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 section "Case Conditional Construct":
The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) [...] Multiple patterns with the same compound-list shall be delimited by the '|' symbol. [...]
The format for the case construct is as follows:
case word in [(] pattern1 ) compound-list ;; [[(] pattern[ | pattern] ... ) compound-list ;;] ... [[(] pattern[ | pattern] ... ) compound-list] esac
and then http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13 section "2.13. Pattern Matching Notation" only mentions ?
, *
and []
.
use the below command to set the port number in node process while running node JS programme:
set PORT =3000 && node file_name.js
The set port can be accessed in the code as
process.env.PORT
Let’s assume, your old app.module.ts may look similar to this :
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Now import FormsModule in your app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
http://jsconfig.com/solution-cant-bind-ngmodel-since-isnt-known-property-input/
Index is actually available like;
_.sortBy([1, 4, 2, 66, 444, 9], function(num, index){ });
Learn to use else
.
Since value
will never be equal to two unequal strings at once, there are only 5 possible outcomes -- one for each value you care about, plus one for "none of the above". But because your code doesn't eliminate the tests that can't pass, it has 16 "possible" paths (2 ^ the number of tests), of which most will never be followed.
With else
, the only paths that exist are the 5 that can actually happen.
String value = some methodx;
if ("apple".equals(value )) {
method1;
}
else if ("carrot".equals(value )) {
method2;
}
else if ("mango".equals(value )) {
method3;
}
else if ("orance".equals(value )) {
method4;
}
Or start using JDK 7, which includes the ability to use strings in a switch
statement. Course, Java will just compile the switch
into an if
/else
like construct anyway...
//use css
.blue {
background-color:blue !important;
}
.blue th {
color:white !important;
}
//html
<table class="table blue">.....</table>
Another way, simpler.
Add your
build.gradle
file to the root of your project. Close the project. Manually remove *.iml file. Then choose "Import Project...", navigate to your project directory, select the build.gradle file and click OK.
If you need a failure function, you can't use the $.get or $.post functions; you will need to call the $.ajax function directly. You pass an options object that can have "success" and "error" callbacks.
Instead of this:
$.post("/post/url.php", parameters, successFunction);
you would use this:
$.ajax({
url: "/post/url.php",
type: "POST",
data: parameters,
success: successFunction,
error: errorFunction
});
There are lots of other options available too. The documentation lists all the options available.
Non-inherited elements must have default styles set.
If parent class set color:white
and font-weight:bold
style then no inherited child must set 'color:black' and font-weight: normal
in their class. If style
is not set, elements get their style from their parents.
null in Java is like/similar to nullptr in C++.
Program in C++:
class Point
{
private:
int x;
int y;
public:
Point(int ix, int iy)
{
x = ix;
y = iy;
}
void print() { std::cout << '(' << x << ',' << y << ')'; }
};
int main()
{
Point* p = new Point(3,5);
if (p != nullptr)
{
p->print();
p = nullptr;
}
else
{
std::cout << "p is null" << std::endl;
}
return 0;
}
Same program in Java:
public class Point {
private int x;
private int y;
public Point(int ix, int iy) {
x = ix;
y = iy;
}
public void print() { System.out.print("(" + x + "," + y + ")"); }
}
class Program
{
public static void main(String[] args) {
Point p = new Point(3,5);
if (p != null)
{
p.print();
p = null;
}
else
{
System.out.println("p is null");
}
}
}
Now do you understand from the codes above what is null in Java? If no then I recommend you to learn pointers in C/C++ and then you will understand.
Note that in C, unlike C++, nullptr is undefined, but NULL is used instead, which can also be used in C++ too, but in C++ nullptr is more preferable than just NULL, because the NULL in C is always related to pointers and that's it, so in C++ the suffix "ptr" was appended to end of the word, and also all letters are now lowercase, but this is less important.
In Java every variable of type class non-primitive is always reference to object of that type or inherited and null is null class object reference, but not null pointer, because in Java there is no such a thing "pointer", but references to class objects are used instead, and null in Java is related to class object references, so you can also called it as "nullref" or "nullrefobj", but this is long, so just call it "null".
In C++ you can use pointers and the nullptr value for optional members/variables, i.e. member/variable that has no value and if it has no value then it equals to nullptr, so how null in Java can be used for example.
Xcode 8.0 / Swift 3
let fullName = "First Last"
var fullNameArr = fullName.components(separatedBy: " ")
var firstname = fullNameArr[0] // First
var lastname = fullNameArr[1] // Last
Long Way:
var fullName: String = "First Last"
fullName += " " // this will help to see the last word
var newElement = "" //Empty String
var fullNameArr = [String]() //Empty Array
for Character in fullName.characters {
if Character == " " {
fullNameArr.append(newElement)
newElement = ""
} else {
newElement += "\(Character)"
}
}
var firsName = fullNameArr[0] // First
var lastName = fullNameArr[1] // Last
Quite a busy one-liner, but here it is:
myarray
, is normalised with the max value at 1.0
.myarray
.0-255
range.np.uint8()
.Image.fromarray()
.And you're done:
from PIL import Image
from matplotlib import cm
im = Image.fromarray(np.uint8(cm.gist_earth(myarray)*255))
with plt.savefig()
:
with im.save()
:
Besides the mentioned fact that JSX tags are not standard javascript, the reason I use .jsx extension is because with it Emmet still works in the editor - you know, that useful plugin that expands html code, for example ul>li into
<ul>
<li></li>
</ul>
The thing you are asking is not popup but lightbox. For this, the trick is to display a semitransparent layer behind (called overlay) and that required div above it.
Hope you are familiar basic javascript. Use the following code. With javascript, change display:block to/from display:none to show/hide popup.
<div style="background-color: rgba(150, 150, 150, 0.5); overflow: hidden; position: fixed; left: 0px; top: 0px; bottom: 0px; right: 0px; z-index: 1000; display:block;">
<div style="background-color: rgb(255, 255, 255); width: 600px; position: static; margin: 20px auto; padding: 20px 30px 0px; top: 110px; overflow: hidden; z-index: 1001; box-shadow: 0px 3px 8px rgba(34, 25, 25, 0.4);">
<iframe src="otherpage.html" width="400px"></iframe>
</div>
</div>
Try using this:-
mkdir -p dir;
NOTE:- This will also create any intermediate directories that don't exist; for instance,
Check out mkdir -p
or try this:-
if [[ ! -e $dir ]]; then
mkdir $dir
elif [[ ! -d $dir ]]; then
echo "$Message" 1>&2
fi
As a beginner who stumbled across this thread, I'd like to add a python-for-dummies adaptation of abevieiramota's very neat answer (because I'm at the level that I had to look up 'ravel' to work out what their code was doing):
import numpy as np
import matplotlib.pyplot as plt
fig, ((ax1,ax2,ax3),(ax4,ax5,ax6)) = plt.subplots(2,3)
axlist = [ax1,ax2,ax3,ax4,ax5,ax6]
first = ax1.imshow(np.random.random((10,10)), vmin=0, vmax=1)
third = ax3.imshow(np.random.random((12,12)), vmin=0, vmax=1)
fig.colorbar(first, ax=axlist)
plt.show()
Much less pythonic, much easier for noobs like me to see what's actually happening here.
how about sysdate?
SELECT field,datetime_field
FROM database
WHERE datetime_field > (sysdate-1)
So you can use the following :
td {
white-space: normal !important; // To consider whitespace.
}
If this doesn't work:
td {
white-space: normal !important;
word-wrap: break-word;
}
table {
table-layout: fixed;
}
Looks like older answers were fine for older Jackson versions, but since objectMapper
has method setTimeZone(tz)
, setting time zone on a dateFormat is totally ignored.
How to properly setup timeZone to the ObjectMapper in Jackson version 2.11.0:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
Full example
@Test
void test() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.findAndRegisterModules();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
JavaTimeModule module = new JavaTimeModule();
objectMapper.registerModule(module);
objectMapper.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));
ZonedDateTime now = ZonedDateTime.now();
String converted = objectMapper.writeValueAsString(now);
ZonedDateTime restored = objectMapper.readValue(converted, ZonedDateTime.class);
System.out.println("serialized: " + now);
System.out.println("converted: " + converted);
System.out.println("restored: " + restored);
Assertions.assertThat(now).isEqualTo(restored);
}
`
This worked for me:
If you wrote your Serialized class object into a file, then made some changes to file and compiled it, and then you try to read an object, then this will happen.
So, write the necessary objects to file again if a class is modified and recompiled.
PS: This is NOT a solution; was meant to be a workaround.
Just add
xAxis: {
...
lineWidth: 0,
minorGridLineWidth: 0,
lineColor: 'transparent',
...
labels: {
enabled: false
},
minorTickLength: 0,
tickLength: 0
}
to the xAxis definition.
Since Version 4.1.9 you can simply use the axis attribute visible
:
xAxis: {
visible: false,
}
FYI (merged version of Tvanfosson)
it will return actual date => date when you are calling function
export const today = {
iso: {
start: () => new Date(new Date().setHours(0, 0, 0, 0)).toISOString(),
now: () => new Date().toISOString(),
end: () => new Date(new Date().setHours(23, 59, 59, 999)).toISOString()
},
local: {
start: () => new Date(new Date(new Date().setHours(0, 0, 0, 0)).toString().split('GMT')[0] + ' UTC').toISOString(),
now: () => new Date(new Date().toString().split('GMT')[0] + ' UTC').toISOString(),
end: () => new Date(new Date(new Date().setHours(23, 59, 59, 999)).toString().split('GMT')[0] + ' UTC').toISOString()
}
}
// how to use
today.local.now(); //"2018-09-07T01:48:48.000Z" BAKU +04:00
today.iso.now(); // "2018-09-06T21:49:00.304Z" *
* it is applicable for Instant time type on Java8 which convert your local time automatically depending on your region.(if you are planning write global app)
Basically, there are three main characters which should be always escaped in your HTML and XML files, so they don't interact with the rest of the markups, so as you probably expect, two of them gonna be the syntax wrappers, which are <>, they are listed as below:
1) < (<)
2) > (>)
3) & (&)
Also we may use double-quote (") as " and the single quote (') as &apos
Avoid putting dynamic content in <script>
and <style>
.These rules are not for applied for them. For example, if you have to include JSON in a , replace < with \x3c, the U+2028 character with \u2028, and U+2029 with \u2029 after JSON serialisation.)
HTML Escape Characters: Complete List: http://www.theukwebdesigncompany.com/articles/entity-escape-characters.php
So you need to escape <, or & when followed by anything that could begin a character reference. Also The rule on ampersands is the only such rule for quoted attributes, as the matching quotation mark is the only thing that will terminate one. But if you don’t want to terminate the attribute value there, escape the quotation mark.
Changing to UTF-8 means re-saving your file:
Using the character encoding UTF-8 for your page means that you can avoid the need for most escapes and just work with characters. Note, however, that to change the encoding of your document, it is not enough to just change the encoding declaration at the top of the page or on the server. You need to re-save your document in that encoding. For help understanding how to do that with your application read Setting encoding in web authoring applications.Invisible or ambiguous characters:
A particularly useful role for escapes is to represent characters that are invisible or ambiguous in presentation.
One example would be Unicode character U+200F RIGHT-TO-LEFT MARK. This character can be used to clarify directionality in bidirectional text (eg. when using the Arabic or Hebrew scripts). It has no graphic form, however, so it is difficult to see where these characters are in the text, and if they are lost or forgotten they could create unexpected results during later editing. Using ? (or its numeric character reference equivalent ?) instead makes it very easy to spot these characters.
An example of an ambiguous character is U+00A0 NO-BREAK SPACE. This type of space prevents line breaking, but it looks just like any other space when used as a character. Using makes it quite clear where such spaces appear in the text.
Use console.dir(object)
and the Firebug plugin
Formatting depends on the server's culture setting. If you use en-US
culture, you can use Short Date Pattern like {0:d}
For example, it formats 6/15/2009 1:45:30
to 6/15/2009
You can check more formats from BoundField.DataFormatString
For setting up virtualenv on a clean Ubuntu installation, I found this zookeeper tutorial to be the best - you can ignore the parts about zookeper itself. The virtualenvwrapper documentation offers similar content, but it's a bit scarce on telling you what exactly to put into your .bashrc
file.
setTimeout
is a kind of Thread, it holds a operation for a given time and execute.
setTimeout(function,time_in_mills);
in here the first argument should be a function type; as an example if you want to print your name after 3 seconds, your code should be something like below.
setTimeout(function(){console.log('your name')},3000);
Key point to remember is, what ever you want to do by using the setTimeout
method, do it inside a function. If you want to call some other method by parsing some parameters, your code should look like below:
setTimeout(function(){yourOtherMethod(parameter);},3000);
None of above worked for me, because tint was cleared after click. I had to use
button.setImageTintColor(Palette.darkGray(), for: UIControlState())
The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true
along with start:start, end:end
in the second createReadStream
arg.
The other part of the solution was to limit the max chunksize
being sent in the response. The other answer set end
like so:
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).
I needed this stream to be closed because I was displaying the <video>
element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.
My solution was just to set a maxChunk
configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.
// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
end = start + maxChunk - 1;
chunksize = (end - start) + 1;
}
This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.
I also wrote a separate StackOverflow question and answer covering this issue.
x <- c(1:10)
# empty data frame with variables ----
df <- data.frame(x1=character(),
y1=character())
for (i in x) {
a1 <- c(x1 == paste0("The number is ",x[i]),y1 == paste0("This is another number ", x[i]))
df <- rbind(df,a1)
}
names(df) <- c("st_column","nd_column")
View(df)
that might be a good way to do so....
You can use this snippet :-D
using System;
using System.Reflection;
public static class EnumUtils
{
public static T GetDefaultValue<T>()
where T : struct, Enum
{
return (T)GetDefaultValue(typeof(T));
}
public static object GetDefaultValue(Type enumType)
{
var attribute = enumType.GetCustomAttribute<DefaultValueAttribute>(inherit: false);
if (attribute != null)
return attribute.Value;
var innerType = enumType.GetEnumUnderlyingType();
var zero = Activator.CreateInstance(innerType);
if (enumType.IsEnumDefined(zero))
return zero;
var values = enumType.GetEnumValues();
return values.GetValue(0);
}
}
Example:
using System;
public enum Enum1
{
Foo,
Bar,
Baz,
Quux
}
public enum Enum2
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 0
}
public enum Enum3
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
[DefaultValue(Enum4.Bar)]
public enum Enum4
{
Foo = 1,
Bar = 2,
Baz = 3,
Quux = 4
}
public static class Program
{
public static void Main()
{
var defaultValue1 = EnumUtils.GetDefaultValue<Enum1>();
Console.WriteLine(defaultValue1); // Foo
var defaultValue2 = EnumUtils.GetDefaultValue<Enum2>();
Console.WriteLine(defaultValue2); // Quux
var defaultValue3 = EnumUtils.GetDefaultValue<Enum3>();
Console.WriteLine(defaultValue3); // Foo
var defaultValue4 = EnumUtils.GetDefaultValue<Enum4>();
Console.WriteLine(defaultValue4); // Bar
}
}
try this code
output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))
ps axo pid,etime,%cpu,%mem,cmd | grep 'processname' | grep -v grep
PID - Process ID
etime - Process Running/Live Duration
%cpu - CPU usage
%mem - Memory usage
cmd - Command
Replace processname with whatever process you want to track, mysql nginx php-fpm etc ...
Because I always want to give the browser something worthwhile to look at I often use this trick:
First, any portion of a page that needs JavaScript to run properly (including passive HTML elements that get modified through getElementById calls etc.) are designed to be usable as-is with the assumption that there ISN'T javaScript available. (designed as if it wasn't there)
Any elements that would require JavaScript, I place inside a tag something like:
<span name="jsOnly" style="display: none;"></span>
Then at the beginning of my document, I use .onload
or document.ready
within a loop of getElementsByName('jsOnly')
to set the .style.display = "";
turning the JS dependent elements back on. That way, non-JS browsers don't ever have to see the JS dependent portions of the site, and if they have it, it appears immediately when it's ready.
Once you are used to this method, it's fairly easy to hybridize your code to handle both situations, although I am only now experimenting with the noscript
tag and expect it will have some additional advantages.
r
opens for reading, whereas r+
opens for reading and writing. The b
is for binary.
This is spelled out in the documentation:
The most commonly-used values of mode are
'r'
for reading,'w'
for writing (truncating the file if it already exists), and'a'
for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position). If mode is omitted, it defaults to'r'
. The default is to use text mode, which may convert'\n'
characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append'b'
to the mode value to open the file in binary mode, which will improve portability. (Appending'b'
is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.) See below for more possible values of mode.Modes
'r+'
,'w+'
and'a+'
open the file for updating (note that'w+'
truncates the file). Append'b'
to the mode to open the file in binary mode, on systems that differentiate between binary and text files; on systems that don’t have this distinction, adding the'b'
has no effect.
According to the W3C, they are the same. In reality, for cross browser safety, you should use window.location
rather than document.location
.
You can simply use this:
'07311954' in df.date.values
which returns True
or False
Here is the further explanation:
In pandas, using in
check directly with DataFrame and Series (e.g. val in df
or val in series
) will check whether the val
is contained in the Index.
BUT you can still use in
check for their values too (instead of Index)! Just using val in df.col_name.values
or val in series.values
. In this way, you are actually checking the val
with a Numpy array.
And .isin(vals)
is the other way around, it checks whether the DataFrame/Series values are in the vals
. Here vals
must be set or list-like. So this is not the natural way to go for the question.
That is because is does not exist, since it is bounded to Windows.
Use the standard functions from <stdio.h>
instead, such as getc
The suggested ncurses library is good if you want to write console-based GUIs, but I don't think it is what you want.
curl is a command in linux (and a library in php). Curl typically makes an HTTP request.
What you really want to do is make an HTTP (or XHR) request from javascript.
Using this vocab you'll find a bunch of examples, for starters: Sending authorization headers with jquery and ajax
Essentially you will want to call $.ajax
with a few options for the header, etc.
$.ajax({
url: 'https://api.wit.ai/message?v=20140826&q=',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer 6QXNMEMFHNY4FJ5ELNFMP5KRW52WFXN5")
}, success: function(data){
alert(data);
//process the JSON data etc
}
})
Note that $(element).offset()
tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed
you can get unexpected results.
If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed
element's offset()
value will be greater than the expected value by the amount you have scrolled.
If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop()
value from the fixed element's offset().top
value. Example: $("#el").offset().top - $(document).scrollTop()
If the position:fixed
element's offset parent is the document, you want to read parseInt($.css('top'))
instead.
open the 'Finder' in Mac and Command+Shift+G and type in the path:/usr/local/zend/apache2/htdocs. path will open then create/paste your web page/application then check it on the browser.
You could insert both the key,value pair and its inverse into your map structure, but would have to convert the Integer to a string:
map.put("theKey", "theValue");
map.put("theValue", "theKey");
Using map.get("theValue") will then return "theKey".
It's a quick and dirty way that I've made constant maps, which will only work for a select few datasets:
If you want to keep <Integer, String>
you could maintain a second <String, Integer>
map to "put" the value -> key pairs.
I tried about three different ways of intercepting the construction of the Ajax object:
xhrFields
, but that only allows for one listener, only attaches to download (not upload) progress, and requires what seems like unnecessary copy-and-paste. progress
function to the returned promise, but I had to maintain my own array of handlers. I could not find a good object to attach the handlers because one place I'd access to the XHR and another I'd have access to the jQuery XHR, but I never had access to the deferred object (only its promise). ajax
with my own. The only potential shortcoming is you can no longer use your own xhr()
setting. You can allow for that by checking to see whether options.xhr
is a function.I actually call my promise.progress
function xhrProgress
so I can easily find it later. You might want to name it something else to separate your upload and download listeners. I hope this helps someone even if the original poster already got what he needed.
(function extend_jQuery_ajax_with_progress( window, jQuery, undefined )
{
var $originalAjax = jQuery.ajax;
jQuery.ajax = function( url, options )
{
if( typeof( url ) === 'object' )
{options = url;url = undefined;}
options = options || {};
// Instantiate our own.
var xmlHttpReq = $.ajaxSettings.xhr();
// Make it use our own.
options.xhr = function()
{return( xmlHttpReq );};
var $newDeferred = $.Deferred();
var $oldPromise = $originalAjax( url, options )
.done( function done_wrapper( response, text_status, jqXHR )
{return( $newDeferred.resolveWith( this, arguments ));})
.fail( function fail_wrapper( jqXHR, text_status, error )
{return( $newDeferred.rejectWith( this, arguments ));})
.progress( function progress_wrapper()
{
window.console.warn( "Whoa, jQuery started actually using deferred progress to report Ajax progress!" );
return( $newDeferred.notifyWith( this, arguments ));
});
var $newPromise = $newDeferred.promise();
// Extend our own.
$newPromise.progress = function( handler )
{
xmlHttpReq.addEventListener( 'progress', function download_progress( evt )
{
//window.console.debug( "download_progress", evt );
handler.apply( this, [evt]);
}, false );
xmlHttpReq.upload.addEventListener( 'progress', function upload_progress( evt )
{
//window.console.debug( "upload_progress", evt );
handler.apply( this, [evt]);
}, false );
return( this );
};
return( $newPromise );
};
})( window, jQuery );
Also, change this:
SelBranchVal = SelBranchVal + "," + InvForm.SelBranch[x].value;
to
SelBranchVal = SelBranchVal + InvForm.SelBranch[x].value+ "," ;
The reason is that for the first time the variable SelBranchVal
will be empty
Latest published version of the Support Library is 24.1.1, So you can use it like this,
compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'
Same as for other support components.
You can see the revisions here,
https://developer.android.com/topic/libraries/support-library/revisions.html
The best threads tutorial I know of is here:
https://computing.llnl.gov/tutorials/pthreads/
I like that it's written about the API, rather than about a particular implementation, and it gives some nice simple examples to help you understand synchronization.
A URL of the form https://github.com/<owner>/<project>/commit/<hash>
will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:
https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685
You can also shorten the hash to any unique prefix, like so:
https://github.com/jerith666/git-graph/commit/35e32b
I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):
git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685
Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.
It is named "destructor", not "deconstructor".
Inside the destructor of each class, you have to delete all other member variables that have been allocated with new.
edit: To clarify:
Say you have
struct A {}
class B {
A *a;
public:
B () : a (new A) {}
~B() { delete a; }
};
class C {
A *a;
public:
C () : a (new A) {}
};
int main () {
delete new B;
delete new C;
}
Allocating an instance of B and then deleting is clean, because what B allocates internally will also be deleted in the destructor.
But instances of class C will leak memory, because it allocates an instance of A which it does not release (in this case C does not even have a destructor).
Put the command
yum install php-gd
and restart the server (httpd, nginx, etc)
service httpd restart
There is now a "native" solution on Windows 10, after enabling Bash on Windows, you can enter Bash shell by typing bash
:
You can run Bash script like bash ./script.sh
, but keep in mind that C drive is located at /mnt/c
, and external hard drives are not mountable. So you might need to change your script a bit so it is compatible to Windows.
Also, even as root
, you can still get permission denied when moving files around in /mnt
, but you have your full root
power in the /
file system.
Also make sure your shell script is formatted with Unix style, or there can be errors.
Try using this code for v3:
gMap = new google.maps.Map(document.getElementById('map'));
gMap.setZoom(13); // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);
You can Enable DBMS_OUTPUT and set the buffer size. The buffer size can be between 1 and 1,000,000.
dbms_output.enable(buffer_size IN INTEGER DEFAULT 20000);
exec dbms_output.enable(1000000);
Check this
EDIT
As per the comment posted by Frank and Mat, you can also enable it with Null
exec dbms_output.enable(NULL);
buffer_size : Upper limit, in bytes, the amount of buffered information. Setting buffer_size to NULL specifies that there should be no limit. The maximum size is 1,000,000, and the minimum is 2,000 when the user specifies buffer_size (NOT NULL).
As I got the 500.19, I gave IIS_IUSRS
full access rights for the mentioned web.config and for the folder of the project. This solved the issue.
You can give permissions by
IIS_IUSRS
- don't forget the i in front of USRS and don't write an "e" as in USERSpublic class Main {
private static LocalDate local=LocalDate.now();
public static void main(String[] args) {
int month=local.lengthOfMonth();
System.out.println(month);
}
}
Got the error (in the function init) with the following code ;
"use strict" ;
var hdr ;
function init(){ // called on load
hdr = document.getElementById("hdr");
}
... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
The fix for this was to change
var hdr ;
to
var hdr = null ;
To change the project name;
2.In the Identity and Type section of the File inspector, enter a new name into the Name field.
3.Press Return.
A dialog is displayed, listing the items in your project that can be renamed. The dialog includes a preview of how the items will appear after the change.
To selectively rename items, disable the checkboxes for any items you don’t want to rename. To rename only your app, leave the app selected and deselect all other items.
Press "Rename"
In Github click the "Clone or download" button of the project you want to import --> download the ZIP file and unzip it. In Android Studio Go to File -> New Project -> Import Project and select the newly unzipped folder -> press OK. It will build the Gradle automatically.
Good Luck with your project
Reading from standard input, write 'code.py' as follows:
import sys
rep = {'zero':'0', 'temp':'bob', 'garbage':'nothing'}
for line in sys.stdin:
for k, v in rep.iteritems():
line = line.replace(k, v)
print line
Then, execute the script with redirection or piping (http://en.wikipedia.org/wiki/Redirection_(computing))
python code.py < infile > outfile
If you're using AngularJS, any <form>
tags inside your ng-app
are replaced at runtime with ngForm
directives that are designed to be nested.
In Angular forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of
<form>
elements, so Angular provides thengForm
directive which behaves identically to<form>
but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using thengRepeat
directive. (source)
Read a file as a string full version (handling exceptions, using UTF-8, handling new line):
// Calling:
/*
Context context = getApplicationContext();
String filename = "log.txt";
String str = read_file(context, filename);
*/
public String read_file(Context context, String filename) {
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
} catch (FileNotFoundException e) {
return "";
} catch (UnsupportedEncodingException e) {
return "";
} catch (IOException e) {
return "";
}
}
Note: you don't need to bother about file path only with file name.
Here is a simple example
from pandas import DataFrame
# Create data set
d = {'Revenue':[100,111,222],
'Cost':[333,444,555]}
df = DataFrame(d)
# mask = Return True when the value in column "Revenue" is equal to 111
mask = df['Revenue'] == 111
print mask
# Result:
# 0 False
# 1 True
# 2 False
# Name: Revenue, dtype: bool
# Select * FROM df WHERE Revenue = 111
df[mask]
# Result:
# Cost Revenue
# 1 444 111
After trying many suggestions from various sites and similar questions, what worked for me was to uninstall all Python stuff and reinstall Anaconda only (see https://stackoverflow.com/a/38330088/1083292)
The previous Python installation I had was not only redundant but only caused me trouble.
The individual alphabets or symbols residing in a single cell can be inserted into different cells in different columns by the following code:
For i = 1 To Len(Cells(1, 1))
Cells(2, i) = Mid(Cells(1, 1), i, 1)
Next
If you do not want the symbols like colon to be inserted put an if condition in the loop.
As Jon Skeet said, the string must be multiple of 4 bytes. But I was still getting the error.
At least it got removed in debug mode. Put a break point on Convert.FromBase64String()
then step through the code. Miraculously, the error disappeared for me :) It is probably related to View states and similar other issues as others have reported.
If the difference between endTime and startTime is greater than or equal to 60 Minutes , the statement:endTime.Subtract(startTime).Minutes;
will always return (minutesDifference % 60)
. Obviously which is not desired when we are only talking about minutes (not hours here).
Here are some of the ways if you want to get total number of minutes
(in different typecasts):
// Default value that is returned is of type *double*
double double_minutes = endTime.Subtract(startTime).TotalMinutes;
int integer_minutes = (int)endTime.Subtract(startTime).TotalMinutes;
long long_minutes = (long)endTime.Subtract(startTime).TotalMinutes;
string string_minutes = (string)endTime.Subtract(startTime).TotalMinutes;
Did you write return true
somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
Unicode escapes only work in unicode strings, so this
a="\u2026"
is actually a string of 6 characters: '\', 'u', '2', '0', '2', '6'.
To make unicode out of this, use decode('unicode-escape')
:
a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))
## '\\u2026'
## u'\u2026'
To add to the other answers, instead of assigning to a differently named variable inside of an if
condition:
var a: Int? = 5
if let b = a {
// do something
}
you can reuse the same variable name like this:
var a: Int? = 5
if let a = a {
// do something
}
This might help you avoid running out of creative variable names...
This takes advantage of variable shadowing that is supported in Swift.
More readable way of achieving this (not a fan of single line ansible tasks)
- local_action:
module: copy
content: "{{ foo_result }}"
dest: /path/to/destination/file
Other answers did not work well for me. My container could not resolve host ip using host.docker.internal. There are two ways
Sharing host network --net=host:
docker run -it --net=host myimage
Using docker's ip address, which is usually 172.17.0.1. You can check it by calling ifconfig command and grabbing inet addr of docker interface
user@ubuntu:~$ ifconfig
docker0 Link encap:Ethernet HWaddr 02:42:a4:a2:b2:f1
inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
inet6 addr: fe80::42:a4ff:fea2:b2f1/64 Scope:Link
Once you have this ip address, you can pass it as an argument to docker run and then to application or as I do it, map the location of jdbc.properties via volume to the directory on host machine, so you can manage the file externally.
docker run -it -v /host_dir/docker_jdbc_config:${jetty_base}/var/config myimage
NOTE: Your database might not allow external connections. In case of postgresql, you need to edit 2 files, as described here and here:
Edit postgresql.conf to listen on all addresses. By default it will point to localhost.
listen_addresses = '*'
Edit pg_hba.conf to allow connections from all addresses. Add on the last line:
host all all 0.0.0.0/0 md5
IMPORTANT: Last step updating database access is not recommended for production use unless you are really sure what you are doing.
Try
SELECT NAME, count(*) as NUM FROM tbl GROUP BY NAME
Here is a simple way to implement ls
command using c
. To run use for example ./xls /tmp
#include<stdio.h>
#include <dirent.h>
void main(int argc,char *argv[])
{
DIR *dir;
struct dirent *dent;
dir = opendir(argv[1]);
if(dir!=NULL)
{
while((dent=readdir(dir))!=NULL)
{
if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
{
}
else
{
printf(dent->d_name);
printf("\n");
}
}
}
close(dir);
}
Graphviz - from the web page:
The Graphviz layout programs take descriptions of graphs in a simple text language, and make diagrams in several useful formats such as images and SVG for web pages, Postscript for inclusion in PDF or other documents; or display in an interactive graph browser. (Graphviz also supports GXL, an XML dialect.)
It's the simplest and most productive tool I've found to create a variety of boxes-and-lines diagrams. I have and use Visio and OmniGraffle, but there's always the temptation to make "just one more adjustment".
It's also quite easy to write code to produce the "dot file" format that Graphiz consumes, so automated diagram production is also nicely within reach.
Here's a similar answer using using a =>
style function:
var data = [1,2,3,4];
data.forEach( (item, i, self) => self[i] = item + 10 );
gives the result:
[11,12,13,14]
The self
parameter isn't strictly necessary with the arrow style function, so
data.forEach( (item,i) => data[i] = item + 10);
also works.
It's a heavy solution for embedding heavy dependencies, but Maven's Assembly Plugin does the trick for me.
@Rich Seller's answer should work, although for simpler cases you should only need this excerpt from the usage guide:
<project>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2.2</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</project>
sys
has some useful stuff:
$ python
Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.executable
'c:\\Python26\\python.exe'
>>> sys.exec_prefix
'c:\\Python26'
>>>
>>> print '\n'.join(sys.path)
c:\Python26\lib\site-packages\setuptools-0.6c11-py2.6.egg
c:\Python26\lib\site-packages\nose-1.0.0-py2.6.egg
C:\Windows\system32\python26.zip
c:\Python26\DLLs
c:\Python26\lib
c:\Python26\lib\plat-win
c:\Python26\lib\lib-tk
c:\Python26
c:\Python26\lib\site-packages
c:\Python26\lib\site-packages\win32
c:\Python26\lib\site-packages\win32\lib
c:\Python26\lib\site-packages\Pythonwin
c:\Python26\lib\site-packages\wx-2.8-msw-unicode
Further to Karl Anderson solution, you could put your parameters into session information and then clear them after response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));
.
See MSDN page HttpSessionState.Add Method (String, Object) for more information on sessions.
Build
->Clean Project
make the run button enable again in my case
Using html5 doctype at the beginning of the page.
<!DOCTYPE html>
Force IE to use the latest render mode
<meta http-equiv="X-UA-Compatible" content="IE=edge">
If your target browser is ie8, then check your compatible settings in IE8
There is another route of failure, besides the version of Java you are running: You could be running out of Heap/RAM
If you had a once working version of SQLDeveloper, and you are starting to see the screenshot referenced in the original post, then you can try to adjust the amount of space SQLDeveloper requests when starting up.
Edit the file:
/ide/bin/ide.conf
Edit the line that specifies the max ram to use: AddVMOption -Xmx, reducing the size. For example I changed my file to have the following lines, which solved the issue.
#AddVMOption -Xmx640M # Original Value
AddVMOption -Xmx256M # New Value
You will need to enable logging of these events. Do so by opening the group policy editor:
run -> gpedit.msc
and configuring the following category:
Computer Configuration ->
Windows Settings ->
Security Settings ->
Advanced Audit Policy Configuration ->
System Audit Policies - Local Group Policy Object ->
Logon/Logoff ->
Audit Other Login/Logoff Events
(In the Explain tab it says "... allows you to audit ... Locking and unlocking a workstation".)
I solve this problem with docker commit after some modifications in the base container, we only need to tag the new image and start that one
docs.docker.com/engine/reference/commandline/commit
docker commit [container-id] [tag]
docker commit b0e71de98cb9 stack-overflow:0.0.1
then you can pass environment vars or file
docker run --env AWS_ACCESS_KEY_ID --env AWS_SECRET_ACCESS_KEY --env AWS_SESSION_TOKEN --env-file env.local -p 8093:8093 stack-overflow:0.0.1
I got this issue while installing transformers
library from HuggingFace. It was due to the fact package enum34
was installed in my environment which was overriding built-in enum in Python. This package was probably installed by something as for forward compatibility which is no longer needed with Python 3.6+. So the solution is simply,
pip uninstall -y enum34
Update (thanks to @chaost for pointing this update out):
Mads Torgersen: "Extension everything didn’t make it into C# 8.0. It got “caught up”, if you will, in a very exciting debate about the further future of the language, and now we want to make sure we don’t add it in a way that inhibits those future possibilities. Sometimes language design is a very long game!"
Source: comments section in https://blogs.msdn.microsoft.com/dotnet/2018/11/12/building-c-8-0/
I stopped counting how many times over the years I opened this question with hopes to have seen this implemented.
Well, finally we can all rejoice! Microsoft is going to introduce this in their upcoming C# 8 release.
So instead of doing this...
public static class IntExtensions
{
public static bool Even(this int value)
{
return value % 2 == 0;
}
}
We'll be finally able to do it like so...
public extension IntExtension extends int
{
public bool Even => this % 2 == 0;
}
Source: https://blog.ndepend.com/c-8-0-features-glimpse-future/
The accepted answers animation does not work on Safari, I've updated it using translate instead of padding-left which makes for a smoother, bulletproof animation.
Also, the accepted answers demo fiddle has a lot of unnecessary styles.
So I created a simple version if you just want to cut and paste the useful code and not spend 5 mins clearing through the demo.
.marquee {_x000D_
margin: 0 auto;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
box-sizing: border-box;_x000D_
padding: 0;_x000D_
height: 16px;_x000D_
display: block;_x000D_
}_x000D_
.marquee span {_x000D_
display: inline-block;_x000D_
text-indent: 0;_x000D_
overflow: hidden;_x000D_
-webkit-transition: 15s;_x000D_
transition: 15s;_x000D_
-webkit-animation: marquee 15s linear infinite;_x000D_
animation: marquee 15s linear infinite;_x000D_
}_x000D_
_x000D_
@keyframes marquee {_x000D_
0% { transform: translate(100%, 0); -webkit-transform: translateX(100%); }_x000D_
100% { transform: translate(-100%, 0); -webkit-transform: translateX(-100%); }_x000D_
}
_x000D_
<p class="marquee"><span>Simple CSS Marquee - Lorem ipsum dolor amet tattooed squid microdosing taiyaki cardigan polaroid single-origin coffee iPhone. Edison bulb blue bottle neutra shabby chic. Kitsch affogato you probably haven't heard of them, keytar forage plaid occupy pitchfork. Enamel pin crucifix tilde fingerstache, lomo unicorn chartreuse plaid XOXO yr VHS shabby chic meggings pinterest kickstarter.</span></p>
_x000D_
Adding this just as an addition to @jimt's excellent answer:
one common way to define it all at initialization time is using an anonymous struct:
var opts = []struct {
shortnm byte
longnm, help string
needArg bool
}{
{'a', "multiple", "Usage for a", false},
{
shortnm: 'b',
longnm: "b-option",
needArg: false,
help: "Usage for b",
},
}
This is commonly used for testing as well to define few test cases and loop through them.
Found this:
The configuration option config.serve_static_assets
has been renamed to config.serve_static_files
to clarify its role.
in config/environments/production.rb
:
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
So set env RAILS_SERVE_STATIC_FILES
or using Nginx
to serving static files.
Add config.serve_static_assets = true
will still work, but removed in future.
try this in java class
yourNavigationView.setItemTextColor(new ColorStateList(
new int [] [] {
new int [] {android.R.attr.state_pressed},
new int [] {android.R.attr.state_focused},
new int [] {}
},
new int [] {
Color.rgb (255, 128, 192),
Color.rgb (100, 200, 192),
Color.WHITE
}
));
Did you mean len(list1)-1
?
If you're searching for other method, you can try list1.index(list1[-1])
, but I don't recommend this one. You will have to be sure, that the list contains NO duplicates.
There's a convenient method for this in MySql called GROUP_CONCAT. An equivalent for SQL Server doesn't exist, but you can write your own using the SQLCLR. Luckily someone already did that for you.
Your query then turns into this (which btw is a much nicer syntax):
SELECT CUSTOMFIELD, ISSUE, dbo.GROUP_CONCAT(STRINGVALUE)
FROM Jira.customfieldvalue
WHERE CUSTOMFIELD = 12534 AND ISSUE = 19602
GROUP BY CUSTOMFIELD, ISSUE
But please note that this method is good for at the most 100 rows within a group. Beyond that, you'll have major performance problems. SQLCLR aggregates have to serialize any intermediate results and that quickly piles up to quite a lot of work. Keep this in mind!
Interestingly the FOR XML
doesn't suffer from the same problem but instead uses that horrendous syntax.
Tested libraries like Imagemagick and GD are available for .NET
You could also read up on things like bicubic interpolation and write your own.
Take a look at http://developer.android.com/reference/org/json/JSONTokener.html
This might fix your issue.
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
Use the ListView.HitTest
method
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
var senderList = (ListView) sender;
var clickedItem = senderList.HitTest(e.Location).Item;
if (clickedItem != null)
{
//do something
}
}
Or the old way
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
var senderList = (ListView) sender;
if (senderList.SelectedItems.Count == 1 && IsInBound(e.Location, senderList.SelectedItems[0].Bounds))
{
//Do something
}
}
public bool IsInBound(Point location, Rectangle bound)
{
return (bound.Y <= location.Y &&
bound.Y + bound.Height >= location.Y &&
bound.X <= location.X &&
bound.X + bound.Width >= location.X);
}
Try putting this in your .htaccess file:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^sub.domain.com
RewriteRule ^(.*)$ /subdomains/sub/$1 [L,NC,QSA]
For a more general rule (that works with any subdomain, not just sub
) replace the last two lines with this:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com
RewriteRule ^(.*)$ subdomains/%1/$1 [L,NC,QSA]
More simpler way would be to do something as given below inside add :
add : function (e,data){
var extension = data.originalFiles[0].name.substr(
(data.originalFiles[0].name.lastIndexOf('.') +1) );
switch(extension){
case 'csv':
case 'xls':
case 'xlsx':
data.url = <Your URL>;
data.submit();
break;
default:
alert("File type not accepted");
break;
}
}
HttpParams httpParameters = new BasicHttpParams();
HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(httpParameters,
HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(httpParameters, true);
// Set the timeout in milliseconds until a connection is
// established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 35 * 1000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30 * 1000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
You can use the following approaches-
var obj = {a:1}
console.log('a' in obj) // 1
console.log(obj.hasOwnProperty('a')) // 2
console.log(Boolean(obj.a)) // 3
The difference between the following approaches are as follows-
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log('b' in obj)
console.log(Boolean(obj.b))
_x000D_
var obj = {
a: 2,
__proto__ : {b: 2}
}
console.log(obj.hasOwnProperty('b'))
_x000D_
var obj = {
b : undefined
}
console.log(Boolean(obj.b))
console.log('b' in obj);
_x000D_
Here is how you can do it with for-in
loop.
var children = element.childNodes;
for(child in children){
console.log(children[child]);
}
content
doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.
Another problem with your code is "
inside a "
block. You should mix '
and "
(class='headingDetail'
).
If content
did support HTML you could end up in an infinite loop where content
is added inside content
.
Ah, since I had no dependencies in my master project, "gradle dependencies" only lists those and not subproject dependencies so the correct command ended up being
gradle :<subproject>:dependencies
so for me this was
gradle :master:dependencies
You could possibly set a cookie at an expiration date of a month or something and then reassign the cookie every time the user visits the website again
When you press ctrl + space, look in the Status bar below.. It will display a message saying IntelliSense is unavailable for C++ / CLI, if it doesn't support it.. The message will look like this -
var space = $(window).height();
var diff = space - HEIGHT;
var margin = (diff > 0) ? (space - HEIGHT)/2 : 0;
$('#container').css({'margin-top': margin});
keyCode and which represent the actual keyboard key pressed in the form of a numeric value. The reason both exist is that keyCode is available within Internet Explorer while which is available in W3C browsers like FireFox.
charCode is similar, but in this case you retrieve the Unicode value of the character pressed. For example, the letter "A."
The JavaScript expression:
var keyCode = e.keyCode ? e.keyCode : e.charCode;
Essentially says the following:
If the e.keyCode property exists, set variable keyCode to its value. Otherwise, set variable keyCode to the value of the e.charCode property.
Note that retrieving the keyCode or charCode properties typically involve figuring out differences between the event models in IE and in W3C. Some entails writing code like the following:
/*
get the event object: either window.event for IE
or the parameter e for other browsers
*/
var evt = window.event ? window.event : e;
/*
get the numeric value of the key pressed: either
event.keyCode for IE for e.which for other browsers
*/
var keyCode = evt.keyCode ? evt.keyCode : e.which;
EDIT: Corrections to my explanation of charCode as per Tor Haugen's comments.
For Git Bash for Windows (in ConEmu), the following works for me (for Docker Windows containers):
docker run --rm -it -v `pwd -W`:c:/api microsoft/dotnet:2-runtime
Note the backticks/backquotes around pwd -W
!
With all other variations of PWD I've tried I've received: "Error response from daemon: invalid volume specification: ..."
Update: The above was for Docker Windows containers, for Linux containers use:
docker run --rm -it -v `pwd -W`:/api -p 8080:80 microsoft/aspnetcore:2
Just invoke ruby XXXXX.rb
in terminal, if the interpreter is in your $PATH variable.
( this can hardly be a rails thing, until you have it running. )
Another mechanism for dynamic styling is to define it in the JSX for your component. For example, the following could be used to selectively style the current step in the React tic-tac-toe tutorial (one of the suggested extra credit enhancements:
return (
<li key={move}>
<button style={{fontWeight:(move === this.state.stepNumber ? 'bold' : '')}} onClick={() => this.jumpTo(move)}>{desc}</button>
</li>
);
Granted, a cleaner approach would be to add/remove a 'selected' CSS class but this direct approach might be helpful in some cases.
Have a better one based on @hypo 's answer
public class GrowLabel : Label {
private bool mGrowing;
public GrowLabel() {
this.AutoSize = false;
}
private void resizeLabel() {
if (mGrowing)
return;
try {
mGrowing = true;
int width = this.Parent == null ? this.Width : this.Parent.Width;
Size sz = new Size(this.Width, Int32.MaxValue);
sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
this.Height = sz.Height + Padding.Bottom + Padding.Top;
} finally {
mGrowing = false;
}
}
protected override void OnTextChanged(EventArgs e) {
base.OnTextChanged(e);
resizeLabel();
}
protected override void OnFontChanged(EventArgs e) {
base.OnFontChanged(e);
resizeLabel();
}
protected override void OnSizeChanged(EventArgs e) {
base.OnSizeChanged(e);
resizeLabel();
}
}
int width = this.Parent == null ? this.Width : this.Parent.Width;
this allows you to use auto-grow label when docked to a parent, e.g. a panel.
this.Height = sz.Height + Padding.Bottom + Padding.Top;
here we take care of padding for top and bottom.
I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound
This means that nothing is bound to the jndi name greetJndi
, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.
Is there any specific directory structure to deploy in JBoss?
The internal structure of the ejb-jar
is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):
. +-- greetBean.java +-- greetHome.java +-- greetRemote.java +-- META-INF +-- ejb-jar.xml +-- jboss.xml
But as already mentioned, this tutorial is full of mistakes:
<enterprise-beans>]
<-- HERE) in the ejb-jar.xml
(!)PUBLIC
in the ejb-jar.xml
and jboss.xml
(!!)jboss.xml
is incorrect, it should contain a session
element instead of entity
(!!!)Here is a "fixed" version of the ejb-jar.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<home>greetHome</home>
<remote>greetRemote</remote>
<ejb-class>greetBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
And of the jboss.xml
:
<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
<enterprise-beans>
<session>
<ejb-name>greetBean</ejb-name>
<jndi-name>greetJndi</jndi-name>
</session>
</enterprise-beans>
</jboss>
After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:
21:48:06,512 INFO [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/} 21:48:06,534 INFO [EjbDeployer] installing bean: ejb/#greetBean,uid19981448 21:48:06,534 INFO [EjbDeployer] with dependencies: 21:48:06,534 INFO [EjbDeployer] and supplies: 21:48:06,534 INFO [EjbDeployer] jndi:greetJndi 21:48:06,624 INFO [EjbModule] Deploying greetBean 21:48:06,661 WARN [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/ 21:48:06,805 INFO [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'
That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.
It is basically a comment. As we know, a number of people working on the same project must have knowledge about the code changes. We are making some notes in the program about the parameters.
Often I use this approach for initializing a 2-dimensional array
n=[[int(x) for x in input().split()] for i in range(int(input())]
This worked for me JsFiddle
Html
..bootstrap
<div class="row">
<div class="col-4 window-full" style="background-color:green">
First Col
</div>
<div class="col-8">
Column-8
</div>
</div>
css
.row {
background: #f8f9fa;
margin-top: 20px;
}
.col {
border: solid 1px #6c757d;
padding: 10px;
}
JavaScript
var elements = document.getElementsByClassName('window-full');
var windowheight = window.innerHeight + "px";
fullheight(elements);
function fullheight(elements) {
for(let el in elements){
if(elements.hasOwnProperty(el)){
elements[el].style.height = windowheight;
}
}
}
window.onresize = function(event){
fullheight(elements);
}
Checkout JsFiddle link JsFiddle
In Python, this:
my_object.method("foo")
...is syntactic sugar, which the interpreter translates behind the scenes into:
MyClass.method(my_object, "foo")
...which, as you can see, does indeed have two arguments - it's just that the first one is implicit, from the point of view of the caller.
This is because most methods do some work with the object they're called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self
inside the method definition:
class MyNewClass:
def method(self, arg):
print(self)
print(arg)
If you call method("foo")
on an instance of MyNewClass
, it works as expected:
>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo
Occasionally (but not often), you really don't care about the object that your method is bound to, and in that circumstance, you can decorate the method with the builtin staticmethod()
function to say so:
class MyOtherClass:
@staticmethod
def method(arg):
print(arg)
...in which case you don't need to add a self
argument to the method definition, and it still works:
>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo
/**
* @param Object
* @returns boolean
*/
function isJSON (something) {
if (typeof something != 'string')
something = JSON.stringify(something);
try {
JSON.parse(something);
return true;
} catch (e) {
return false;
}
}
You can use it:
var myJson = [{"user":"chofoteddy"}, {"user":"bart"}];
isJSON(myJson); // true
The best way to validate that an object is of type JSON or array is as follows:
var a = [],
o = {};
toString.call(o) === '[object Object]'; // true
toString.call(a) === '[object Array]'; // true
a.constructor.name === 'Array'; // true
o.constructor.name === 'Object'; // true
But, strictly speaking, an array is part of a JSON syntax. Therefore, the following two examples are part of a JSON response:
console.log(response); // {"message": "success"}
console.log(response); // {"user": "bart", "id":3}
And:
console.log(response); // [{"user":"chofoteddy"}, {"user":"bart"}]
console.log(response); // ["chofoteddy", "bart"]
If you use JQuery to bring information via AJAX. I recommend you put in the "dataType" attribute the "json" value, that way if you get a JSON or not, JQuery validate it for you and make it known through their functions "success" and "error". Example:
$.ajax({
url: 'http://www.something.com',
data: $('#formId').serialize(),
method: 'POST',
dataType: 'json',
// "sucess" will be executed only if the response status is 200 and get a JSON
success: function (json) {},
// "error" will run but receive state 200, but if you miss the JSON syntax
error: function (xhr) {}
});
The below SQL someone suggested, does NOT work in SQL Server. This syntax reminds me of my old school class:
UPDATE table2
SET table2.col1 = table1.col1,
table2.col2 = table1.col2,
...
FROM table1, table2
WHERE table1.memberid = table2.memberid
All other queries using NOT IN
or NOT EXISTS
are not recommended. NULLs show up because OP compares entire dataset with smaller subset, then of course there will be matching problem. This must be fixed by writing proper SQL with correct JOIN
instead of dodging problem by using NOT IN
. You might run into other problems by using NOT IN
or NOT EXISTS
in this case.
My vote for the top one, which is conventional way of updating a table based on another table by joining in SQL Server. Like I said, you cannot use two tables in same UPDATE
statement in SQL Server unless you join them first.
You can try using https://ip-api.io - geo location api that returns country among other IP information.
For example with Node.js
const request = require('request-promise')
request('http://ip-api.io/api/json/1.2.3.4')
.then(response => console.log(JSON.parse(response)))
.catch(err => console.log(err))
In addition to the plt.axvline
and plt.plot((x1, x2), (y1, y2))
OR plt.plot([x1, x2], [y1, y2])
as provided in the answers above, one can also use
plt.vlines(x_pos, ymin=y1, ymax=y2)
to plot a vertical line at x_pos
spanning from y1
to y2
where the values y1
and y2
are in absolute data coordinates.
One way to approach the problem is to make a tuple of the dictionary's items:
hash(tuple(my_dict.items()))
A short answer is to add the following options when the JVM is started.
JAVA_OPTS=" $JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8080"
Go to run : ctrl + R
Type : %temp%
delete All files & folders
Rebuild Project.
done!
Loading a python3 generated *.pyc
file with python2 also causes this error.
There is another useful method called AutoResizeColumn
which allows you to auto size a specific column with the required parameter.
You can call it like this:
listview1.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.HeaderSize);
listview1.AutoResizeColumn(4, ColumnHeaderAutoResizeStyle.HeaderSize);
If you are insisting to use the window.location.origin
You can put this in top of your code before reading the origin
if (!window.location.origin) {
window.location.origin = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ':' + window.location.port: '');
}
PS: For the record, it was actually the original question. It was already edited :)
width, height = map(int, input().split())
def rectanglePerimeter(width, height):
return ((width + height)*2)
print(rectanglePerimeter(width, height))
Running it like this produces:
% echo "1 2" | test.py
6
I suspect IDLE is simply passing a single string to your script. The first input()
is slurping the entire string. Notice what happens if you put some print statements in after the calls to input()
:
width = input()
print(width)
height = input()
print(height)
Running echo "1 2" | test.py
produces
1 2
Traceback (most recent call last):
File "/home/unutbu/pybin/test.py", line 5, in <module>
height = input()
EOFError: EOF when reading a line
Notice the first print statement prints the entire string '1 2'
. The second call to input()
raises the EOFError
(end-of-file error).
So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input()
once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what
width, height = map(int, input().split())
does.
Note, there are other ways to pass input to your program. If you had run test.py
in a terminal, then you could have typed 1
and 2
separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1
and 2
programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with
test.py 1 2
<script>
$("#editTest23").click(function () {
var test_date = $(this).data('id');
// alert(status_id);
$.ajax({
type: "POST",
url: base_url+"Doctor/getTestData",
data: {
test_data: test_date,
},
dataType: "text",
success: function (data) {
$('#prepend_here_test1').html(data);
}
});
// you have missed this bracket
return false;
});
</script>
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
Tomcat is primarily an application server, which serves requests to custom-built Java servlets or JSP files on your server. It is usually used in conjunction with the Apache HTTP server (at least in my experience). Use it to manually process incoming requests.
The HTTP server, by itself, is best for serving up static content... html files, images, etc.
You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015
> 01/02/2016
because 09
> 01
. You need to either put your date in a comparable string format or compare DateTime
objects which are comparable.
<?php
$date_now = date("Y-m-d"); // this format is string comparable
if ($date_now > '2016-01-02') {
echo 'greater than';
}else{
echo 'Less than';
}
Or
<?php
$date_now = new DateTime();
$date2 = new DateTime("01/02/2016");
if ($date_now > $date2) {
echo 'greater than';
}else{
echo 'Less than';
}
Your class might implement the Comparable interface to achieve the same functionality. Your class should implement the compareTo() method declared in the interface.
public class MyClass implements Comparable<MyClass>{
String a;
public MyClass(String ab){
a = ab;
}
// returns an int not a boolean
public int compareTo(MyClass someMyClass){
/* The String class implements a compareTo method, returning a 0
if the two strings are identical, instead of a boolean.
Since 'a' is a string, it has the compareTo method which we call
in MyClass's compareTo method.
*/
return this.a.compareTo(someMyClass.a);
}
public static void main(String[] args){
MyClass object1 = new MyClass("test");
MyClass object2 = new MyClass("test");
if(object1.compareTo(object2) == 0){
System.out.println("true");
}
else{
System.out.println("false");
}
}
}
message = str(input("Enter you message:"))
shift = int(input("Enter a number:"))
# encode
stringValue = [ord(message) - 96 for message in message]
print(stringValue)
encode_msg_val = []
[encode_msg_val.append(int(stringValue[i])+shift) for i in
range(len(stringValue))]
encode_msg_array = []
for i in range(len(encode_msg_val)):
encode_val = encode_msg_val[i] + 96
encode_msg_array.append(chr(encode_val))
print(encode_msg_array)
encode_msg = ''.join(encode_msg_array)
# dedcode
[deocde_msg_val = [ord(encode_msg) - 96 for encode_msg in encode_msg]
decode_val = []
[decode_val.append(deocde_msg_val[i] - shift) for i in
range(len(deocde_msg_val))]
decode_msg_array = []
[decode_msg_array.append(decode_val[i] + 96) for i in range(len(decode_val))]
decode_msg_list = []
[decode_msg_list.append(chr(decode_msg_array[i])) for i in
range(len(decode_msg_array))]
decode_msg = ''.join(decode_msg_list)
print(decode_msg)
You can use these solutions :
CSS rules applies to all tags that have following two classes :
.left.ui-class-selector {
/*style here*/
}
CSS rules applies to all tags that have <li>
with following two classes :
li.left.ui-class-selector {
/*style here*/
}
jQuery solution :
$("li.left.ui-class-selector").css("color", "red");
Javascript solution :
document.querySelector("li.left.ui-class-selector").style.color = "red";
Sorry to tell you screencap
just a simple command, only accept few arguments, but none of them can save time for you, here is the -h
help output.
$ adb shell screencap -h
usage: screencap [-hp] [-d display-id] [FILENAME]
-h: this message
-p: save the file as a png.
-d: specify the display id to capture, default 0.
If FILENAME ends with .png it will be saved as a png.
If FILENAME is not given, the results will be printed to stdout.
Besides the command screencap
, there is another command screenshot
, I don't know why screenshot
was removed from Android 5.0
, but it's avaiable below Android 4.4
, you can check the source from here. I didn't make my comparison which is faster between these two commands, but you can give your try in your real environment and make the final decision.
Use the EXECUTABLE_OUTPUT_PATH
CMake variable to set the needed path. For details, refer to the online CMake documentation:
In my case, a script was running command while redirecting both stdout and stderr to a file, something like:
cmd > log 2>&1
I needed to update it such that when there is a failure, take some actions based on the error messages. I could of course remove the dup 2>&1
and capture the stderr from the script, but then the error messages won't go into the log file for reference. While the accepted answer from @lhunath is supposed to do the same, it redirects stdout
and stderr
to different files, which is not what I want, but it helped me to come up with the exact solution that I need:
(cmd 2> >(tee /dev/stderr)) > log
With the above, log will have a copy of both stdout
and stderr
and I can capture stderr
from my script without having to worry about stdout
.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
Maybe you can integrate MuPdf in your application. Here is I've described how to do this: Integrate MuPDF Reader in an app
If you're curious which protocols .NET supports, you can try HttpClient out on https://www.howsmyssl.com/
// set proxy if you need to
// WebRequest.DefaultWebProxy = new WebProxy("http://localhost:3128");
File.WriteAllText("howsmyssl-httpclient.html", new HttpClient().GetStringAsync("https://www.howsmyssl.com").Result);
// alternative using WebClient for older framework versions
// new WebClient().DownloadFile("https://www.howsmyssl.com/", "howsmyssl-webclient.html");
The result is damning:
Your client is using TLS 1.0, which is very old, possibly susceptible to the BEAST attack, and doesn't have the best cipher suites available on it. Additions like AES-GCM, and SHA256 to replace MD5-SHA-1 are unavailable to a TLS 1.0 client as well as many more modern cipher suites.
As Eddie explains above, you can enable better protocols manually:
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11;
I don't know why it uses bad protocols out-the-box. That seems a poor setup choice, tantamount to a major security bug (I bet plenty of applications don't change the default). How can we report it?
You can use Thread.getCurrentThread.getId(), but why would you want to do that when LogRecord objects managed by the logger already have the thread Id. I think you are missing a configuration somewhere that logs the thread Ids for your log messages.
Understand that every 'freezing' application for Python will not really secure your code in any way. Every packaging system for a stand-alone executable Python 'program' will include a lot of the Python libraries and interpreter, which will make your program pretty large.
That said, PyInstaller has done a nearly flawless job with everything I've thrown at it. Currently it only supports up to Python 2.7 but Pyinstaller's support for a varied set of libraries large and small is unmatched in other 'freeze' type programs for Python.
Hope this useful for you.
$(document).click(function(e){
if ($('#news_gallery').on('clicked')) {
var article = $('#news-article .news-article');
}
});
import java.util.Scanner;
class CalculateGCD
{
public static int calGCD(int a, int b)
{
int c=0,d=0;
if(a>b){c=b;}
else{c=a;}
for(int i=c; i>0; i--)
{
if(((a%i)+(b%i))==0)
{
d=i;
break;
}
}
return d;
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the nos whose GCD is to be calculated:");
int a=sc.nextInt();
int b=sc.nextInt();
System.out.println(calGCD(a,b));
}
}
You can use the following:
<style type="text/css">
table { page-break-inside:auto }
tr { page-break-inside:avoid; page-break-after:auto }
</style>
Refer the W3C's CSS Print Profile specification for details.
And also refer the Salesforce developer forums.
If anyone's still looking - Quercus has a war that allows to run PHP scripts in apache tomcat or glassfish. For a step by step guide look at this article
The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min
Therefore there is no difference between default(DateTime)
and new DateTime()
and DateTime.Min
Here's the way to do this via storyboard in XCode 10.2.1. Separator defaults to default
which is the line. Set it to none
to remove the line.
Use master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0)
instead of master.dbo.fn_varbintohexstr
and then substringing
the result.
In fact fn_varbintohexstr
calls fn_varbintohexsubstring
internally. The first argument of fn_varbintohexsubstring
tells it to add 0xF
as the prefix or not. fn_varbintohexstr
calls fn_varbintohexsubstring
with 1
as the first argument internaly.
Because you don't need 0xF
, call fn_varbintohexsubstring
directly.
There are two ways,
android:screenOrientation="portrait"
for each Activity in Manifest Filethis.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
in each java file.Try to load the target URL in browser and view the site's certificate (usually it's accessible by the icon with the lock sign. It's on the left or right side of the browser's address bar) whether it's expired or untrusted by other reason.
New versions usually come with the updated set of the trusted certificates.
Also if it's possible, uninstall old versions. This will make misconfiguration errors explicit.
If you develop under the JDK other than the latest available - try to replace the %JAVA_HOME%/jre/lib/security/cacerts
file with the new one from the latest installed JRE (make a backup copy first) as @jeremy-goodell suggests in his answer
If nothing above solves your problem use keytool
to save certificate(s) to the Java's keystore:
keytool -trustcacerts -keystore "%JAVA_HOME%jre\lib\security\cacerts" -storepass changeit -importcert -alias <alias_name> -file <path_to_crt_file>
File with the certificate can be obtained from the browser as @MagGGG suggests in his answer.
Note 1: you may need to repeat this for every certificate in the chain to you site's certificate. Start from the root one.
Note 2: <alias_name>
should be unique among the keys in the store or keytool
will show an error.
To get list of all the certificates in the store you may run:
keytool -list -trustcacerts -keystore "%JAVA_HOME%jre\lib\security\cacerts" -storepass changeit
In case something goes wrong this will help you to remove certificate from the store:
keytool -delete -alias <alias_name> -keystore "%JAVA_HOME%jre\lib\security\cacerts" -storepass changeit
If you're ok with using Python, Pandas worked great for me (csvsql hanged forever for my case). Something like:
from sqlalchemy import create_engine
import pandas as pd
df = pd.read_csv('/PATH/TO/FILE.csv')
# Optional, set your indexes to get Primary Keys
df = df.set_index(['COL A', 'COL B'])
engine = create_engine('mysql://user:pass@host/db', echo=False)
df.to_sql(table_name, dwh_engine, index=False)
Also this doesn't solve the "using CSV engine" part which was part of the question but might me useful as well.
Confirmed.
The part that drops down is set to either:
x
entries (with scrollbars to see remaining), where x
is
For (3) above you can see the results in this JSFiddle
A modern way, ES5+:
if (Array.isArray(array) && array.length) {
// array exists and is not empty
}
An old-school way:
typeof array != "undefined"
&& array != null
&& array.length != null
&& array.length > 0
A compact way:
if (typeof array != "undefined" && array != null && array.length != null && array.length > 0) {
// array exists and is not empty
}
A CoffeeScript way:
if array?.length > 0
Case Undefined
Undefined variable is a variable that you haven't assigned anything to it yet.
let array = new Array(); // "array" !== "array"
typeof array == "undefined"; // => true
Case Null
Generally speaking, null is state of lacking a value. For example a variable is null when you missed or failed to retrieve some data.
array = searchData(); // can't find anything
array == null; // => true
Case Not an Array
Javascript has a dynamic type system. This means we can't guarantee what type of object a variable holds. There is a chance that we're not talking to an instance of Array
.
supposedToBeArray = new SomeObject();
typeof supposedToBeArray.length; // => "undefined"
array = new Array();
typeof array.length; // => "number"
Case Empty Array
Now since we tested all other possibilities, we're talking to an instance of Array
. In order to make sure it's not empty, we ask about number of elements it's holding, and making sure it has more than zero elements.
firstArray = [];
firstArray.length > 0; // => false
secondArray = [1,2,3];
secondArray.length > 0; // => true
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
Use:
document.getElementById("resultFrame").contentWindow.Reset();
to access the Reset function in the iframe
document.getElementById("resultFrame")
will get the iframe in your code, and contentWindow
will get the window object in the iframe. Once you have the child window, you can refer to javascript in that context.
Also see HERE in particular the answer from bobince.
You can use a dictionary too.
def install():
print "In install"
methods = {'install': install}
method_name = 'install' # set by the command line options
if method_name in methods:
methods[method_name]() # + argument list of course
else:
raise Exception("Method %s not implemented" % method_name)
If you type
input("")
It will wait for them to press any button then it will continue. Also you can put text between the quotes.
I have managed to achieve this using this XML code only. It might be the case that eclipse does not render the height to show it expanding to fit; however, when you actually run this on a device, it properly renders and provides the desired result. (well at least for me)
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:src="@drawable/whatever" />
</FrameLayout>
dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))
na.omit(dat)
x1 x2
1 1 100
3 3 300
5 5 500
I've coded up a helper class for doing this. You can see the code at github: https://github.com/quiqueqs/Toast-Expander/blob/master/src/com/thirtymatches/toasted/ToastedActivity.java
This is how you'd display a toast for 5 seconds (or 5000 milliseconds):
Toast aToast = Toast.makeText(this, "Hello World", Toast.LENGTH_SHORT);
ToastExpander.showFor(aToast, 5000);
This answer is just useful to understand how you can make delay using JQuery delay
function.
Imagine you have an alert and you want to set the alert text then show the alert and after a few seconds hide it.
Here is the simple solution:
$(".alert-element").html("I'm the alert text").fadeIn(500).delay(5000).fadeOut(1000);
It is completely simple:
.html()
will change the text of .alert-element
.fadeIn(500)
will fade in after 500 millisecondsdelay(5000)
function will make 5000 milliseconds of delay before calling next function.fadeOut(1000)
at the end of the statement will fade out the .alert-element
So you need a natural sort ?
If so, than maybe this script by Brian Huisman based on David koelle's work would be what you need.
It seems like Brian Huisman's solution is now directly hosted on David Koelle's blog:
I try to create a table with a field as 200 characters and I've added two rows with early 160 characters and it's OK. Are you sure your rows are less than 200 characters?
Show SqlFiddle
At our company, instead of asking a lot of SQL questions that anyone with a good memory can answer, we created a SQL Developers test. The test is designed to have the candidate put together a solid schema with normalization and RI considerations, check constraints etc. And then be able to create some queries to produce results sets we're looking for. They create all this against a brief design specification we give them. They are allowed to do this at home, and take as much time as they need (within reason).