Maven dependency
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
<version>1.6.19</version>
</dependency>
Configuration class
import org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor;
@Configuration
public class ConfigurationClass{
@Bean
public Wss4jSecurityInterceptor securityInterceptor() {
Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
wss4jSecurityInterceptor.setSecurementActions("UsernameToken");
wss4jSecurityInterceptor.setSecurementMustUnderstand(true);
wss4jSecurityInterceptor.setSecurementPasswordType("PasswordText");
wss4jSecurityInterceptor.setSecurementUsername("123456789011");
wss4jSecurityInterceptor.setSecurementPassword("TestPass123");
return wss4jSecurityInterceptor;
}
Result xml
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header>
<wsse:Security
xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
SOAP-ENV:mustUnderstand="1">
<wsse:UsernameToken wsu:Id="UsernameToken-F57F40DC89CD6998E214700450735811">
<wsse:Username>123456789011</wsse:Username>
<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">TestPass123</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
...
something
...
</SOAP-ENV:Body>
You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.
Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).
EDIT:
Here is some code:
For the UDF:
Public Function UDF_Date(ByVal data) As Date
UDF_Date = Now()
End Function
As Formula in D2:
=UDF_Date(C2)
You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.
And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.
Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.
Addendum:
Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:
The usage of the UDF is the same as described above.
The UDF works only for single cell input ranges.
The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.
If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.
The code might brake for cell-values for which conversion to string is non-deterministic.
The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.
Public Function UDF_Date(ByVal inData As Range) As Date
Dim wb As Workbook
Dim dProps As DocumentProperties
Dim pValue As DocumentProperty
Dim pDate As DocumentProperty
Dim sName As String
Dim sNameDate As String
Dim bDate As Boolean
Dim bValue As Boolean
Dim bChanged As Boolean
bDate = True
bValue = True
bChanged = False
Dim sVal As String
Dim dDate As Date
sName = inData.Address & "_" & inData.Worksheet.Name
sNameDate = sName & "_dat"
sVal = CStr(inData.Value)
dDate = Now()
Set wb = inData.Worksheet.Parent
Set dProps = wb.CustomDocumentProperties
On Error Resume Next
Set pValue = dProps.Item(sName)
If Err.Number <> 0 Then
bValue = False
Err.Clear
End If
On Error GoTo 0
If Not bValue Then
bChanged = True
Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
Else
bChanged = pValue.Value <> sVal
If bChanged Then
pValue.Value = sVal
End If
End If
On Error Resume Next
Set pDate = dProps.Item(sNameDate)
If Err.Number <> 0 Then
bDate = False
Err.Clear
End If
On Error GoTo 0
If Not bDate Then
Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
End If
If bChanged Then
pDate.Value = dDate
Else
dDate = pDate.Value
End If
UDF_Date = dDate
End Function
Make the insertion of the date conditional upon the range.
This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.
Adapted from this tip and @Paul S answer
Private Sub Worksheet_Change(ByVal Target As Range)
Dim R1 As Range
Dim R2 As Range
Dim InRange As Boolean
Set R1 = Range(Target.Address)
Set R2 = Range("C2:C20")
Set InterSectRange = Application.Intersect(R1, R2)
InRange = Not InterSectRange Is Nothing
Set InterSectRange = Nothing
If InRange = True Then
R1.Offset(0, 1).Value = Now()
End If
Set R1 = Nothing
Set R2 = Nothing
End Sub
This sounds very odd, but yes, a system reboot or killall node
solves the problem for me.
Here we go:
DateTime time = DateTime.Now;
Console.WriteLine(time.Day + "-" + time.Month + "-" + time.Year);
WORKS! :)
You can also use an object-oriented path with pathlib
(available as a standard library as of Python 3.4):
from pathlib import Path
start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'
I would suggest you to either use <table>
or CSS.
CSS is preferred for being more flexible. An example would be:
<!-- of course, you should move the inline CSS style to your stylesheet -->
<!-- main container, width = 70% of page, centered -->
<div id="contentBox" style="margin:0px auto; width:70%">
<!-- columns divs, float left, no margin so there is no space between column, width=1/3 -->
<div id="column1" style="float:left; margin:0; width:33%;">
CONTENT
</div>
<div id="column2" style="float:left; margin:0;width:33%;">
CONTENT
</div>
<div id="column3" style="float:left; margin:0;width:33%">
CONTENT
</div>
</div>
jsFiddle: http://jsfiddle.net/ndhqM/
Using float:left would make 3 columns stick to each other, coming in from left inside the centered div "content box".
from win32com.client import Dispatch
wmp = Dispatch('WMPlayer.OCX')
liste = [r"F:\Mp3\rep\6.Evinden Uzakta.mp3",
r"F:\Mp3\rep\07___SAGOPA_KAJMER___BIR__I.MP3",
r"F:\Mp3\rep\7.Terzi.mp3",
r"F:\Mp3\rep\08. Rüya.mp3",
r"F:\Mp3\rep\8.Battle Edebiyati.mp3",
r"F:\Mp3\rep\09_AUDIOTRACK_09.MP3",
r"F:\Mp3\rep\02. Sagopa Kajmer - Uzun Yollara Devam.mp3",
r"F:\Mp3\rep\2Pac_-_CHANGE.mp3",
r"F:\Mp3\rep\03. Herkes.mp3",
r"F:\Mp3\rep\06. Sagopa Kajmer - Istakoz.mp3"]
for x in liste:
mp3 = wmp.newMedia(x)
wmp.currentPlaylist.appendItem(mp3)
wmp.controls.play()
You also should have Tools->Android->Enable ADB Integration active.
"What does if __name__==“__main__”:
do?" has already been answered.
Having a main()
function allows you to call its functionality if you import
the module. The main (no pun intended) benefit of this (IMHO) is that you can unit test it.
In Linux, run file on the Eclipse executable, like this:
$ file /usr/bin/eclipse
eclipse: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped
Yes, it's probably dependent on various things - but I doubt it will make very much difference. I tend to opt for 16K or 32K as a good balance between memory usage and performance.
Note that you should have a try/finally block in the code to make sure the stream is closed even if an exception is thrown.
The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.
function start(){
document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
}
function addActivityItem(){
//option is selected
alert("yeah");
}
window.addEventListener("load", start, false);
You can use "group by" + "orderby". See LINQ 101 for details
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
group x by x into g
let count = g.Count()
orderby count descending
select new {Value = g.Key, Count = count};
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
In response to this post (now deleted):
If you have a list of some custom objects then you need to use custom comparer or group by specific property.
Also query can't display result. Show us complete code to get a better help.
Based on your latest update:
You have this line of code:
group xx by xx into g
Since xx is a custom object system doesn't know how to compare one item against another. As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:
Note that I use Foo.Name as a key - i.e. objects will be grouped based on value of Name property.
There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.
//Using extension methods
var q = list.GroupBy(x => x.Name)
.Select(x => new {Count = x.Count(),
Name = x.Key,
ID = x.First().ID})
.OrderByDescending(x => x.Count);
//Using LINQ
var q = from x in list
group x by x.Name into g
let count = g.Count()
orderby count descending
select new {Name = g.Key, Count = count, ID = g.First().ID};
foreach (var x in q)
{
Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}
This would be in addition to previous, if someone meets a problem with scandic letters that isn't solved with the solution above.
If the java source files contain scandic letters they need to be interpreted correctly by the Java used for compiling. (e.g. scandic letters used in constants)
Even that the files are stored in UTF-8 and the Maven is configured to use UTF-8, the System Java used by the Maven will still use the system default (eg. in Windows: cp1252).
This will be visible only running the tests via maven (possibly printing the values of these constants in tests. The printed scandic letters would show as '< ?>') If not tested properly, this would corrupt the class files as compile result and be left unnoticed.
To prevent this, you have to set the Java used for compiling to use UTF-8 encoding. It is not enough to have the encoding settings in the maven pom.xml, you need to set the environment variable: JAVA_TOOL_OPTIONS = -Dfile.encoding=UTF8
Also, if using Eclipse in Windows, you may need to set the encoding used in addition to this (if you run individual test via eclipse).
If you are using Python2.6 or newer, it's convenient to use socket.create_connection
sock = socket.create_connection(address, timeout=10)
sock.settimeout(None)
fileobj = sock.makefile('rb', 0)
$('.line').click(function() {_x000D_
$(this).toggleClass('red');_x000D_
});
_x000D_
.line {_x000D_
border: 0;_x000D_
background-color: #000;_x000D_
height: 3px;_x000D_
cursor: pointer;_x000D_
}_x000D_
.red {_x000D_
background-color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<hr class="line"></hr>_x000D_
<p>click the line</p>
_x000D_
You can pass lists just like other types:
l = [1,2,3]
def stuff(a):
for x in a:
print a
stuff(l)
This prints the list l. Keep in mind lists are passed as references not as a deep copy.
Another thing you might want to enforce is making sure your abstract class is not instantiated. You can do that by defining a function that acts as FLAG ones set as the Abstract class constructor. This will then try to construct the FLAG which will call its constructor containing exception to be thrown. Example below:
(function(){
var FLAG_ABSTRACT = function(__class){
throw "Error: Trying to instantiate an abstract class:"+__class
}
var Class = function (){
Class.prototype.constructor = new FLAG_ABSTRACT("Class");
}
//will throw exception
var foo = new Class();
})()
.net core
using System.Text.Json;
var jsonStr = JsonSerializer.Serialize(MyObject)
var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);
For more information about excluding properties and nulls check out This Microsoft side
simplest thing to do; just add:
app:navigationIcon="@drawable/ic_action_navigation_menu">
to the <android.support.v7.widget.Toolbar
tag
where @drawable/ic_action_navigation_menu
is the name of icon
Use this way so that result will not be displayed while running stored procedure.
The query:
SELECT a.strUserID FROM tblUsers a WHERE a.lngUserID = lngUserID LIMIT 1 INTO @strUserID;
If you are trying to check the type of an object
after you parse a JSON
string, I suggest checking the constructor attribute:
obj.constructor == Array || obj.constructor == String || obj.constructor == Object
This will be a much faster check than typeof or instanceof.
If a JSON library does not return objects constructed with these functions, I would be very suspiciouse of it.
its working for me
<select name="" id="select">
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
<script>
$("#select > option").on("click", function () {
alert(1)
})
</script>
I was looking for the same and this may also work
p.Wages.all.A_MEAN <- Wages.all %>%
group_by(`Career Cluster`, Year)%>%
summarize(ANNUAL.MEAN.WAGE = mean(A_MEAN))
names(p.Wages.all.A_MEAN) [1] "Career Cluster" "Year" "ANNUAL.MEAN.WAGE"
p.Wages.all.a.mean <- ggplot(p.Wages.all.A_MEAN, aes(Year, ANNUAL.MEAN.WAGE , color= `Career Cluster`))+
geom_point(aes(col=`Career Cluster` ), pch=15, size=2.75, alpha=1.5/4)+
theme(axis.text.x = element_text(color="#993333", size=10, angle=0)) #face="italic",
p.Wages.all.a.mean
From a pipe
# This Is a cat
'This', 'Is', 'a', 'cat' | & {"$input"}
# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}
Write-Host
# This Is a cat
Write-Host 'This', 'Is', 'a', 'cat'
# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'
if you have an object you can define it as @property
so you can get results without a call, e.g.
class Item:
@property
def results(self):
return something
then in the template:
<% for result in item.results %>
...
<% endfor %>
You can try this:
For Date:
$date = new DateTime($from_date);
$date = $date->format('d-m-Y');
For Time:
$time = new DateTime($from_date);
$time = $time->format('H:i:s');
Use navigator.clipboard.writeText
to copy the content to clipboard
navigator.clipboard.writeText(content).then().catch(e => console.error(e));
Your code works as is for me. I'm verifying this by using netcat on Linux.
Using netcat, I can do nc -ul 127.0.0.1 5005
which will listen for packets at:
That being said, here's the output that I see when I run your script, while having netcat running.
[9:34am][wlynch@watermelon ~] nc -ul 127.0.0.1 5005
Hello, World!
Provided that you can use .NET 3.5 (or newer) and LINQ, try
int sum = arr.Sum();
In PHP5, you should use the Document Object Model class instead. Example:
$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);
$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);
$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);
echo htmlentities($domDoc->saveXML());
@media (min-width: @screen-sm-min) {
div.equal-height-sm {
display: table;
> div[class^='col-'] {
display: table-cell;
float: none;
vertical-align: top;
}
}
}
<div class="equal-height-sm">
<div class="col-xs-12 col-sm-7">Test<br/>Test<br/>Test</div>
<div class="col-xs-12 col-sm-5">Test</div>
</div>
Example:
https://jsfiddle.net/b9chris/njcnex83/embedded/result/
Adapted from several answers here. The flexbox-based answers are the right way once IE8 and 9 are dead, and once Android 2.x is dead, but that is not true in 2015, and likely won't be in 2016. IE8 and 9 still make up 4-6% of usage depending on how you measure, and for many corporate users it's much worse. http://caniuse.com/#feat=flexbox
The display: table
, display: table-cell
trick is more backwards-compatible - and one great thing is the only serious compatibility issue is a Safari issue where it forces box-sizing: border-box
, something already applied to your Bootstrap tags. http://caniuse.com/#feat=css-table
You can obviously add more classes that do similar things, like .equal-height-md
. I tied these to divs for the small performance benefit in my constrained usage, but you could remove the tag to make it more generalized like the rest of Bootstrap.
Note that the jsfiddle here uses CSS, and so, things Less would otherwise provide are hard-coded in the linked example. For example @screen-sm-min has been replaced with what Less would insert - 768px.
Even though there is a bool (short for boolean) data type in C++. But in C++, any nonzero value is a true value including negative numbers. A 0 (zero) is treated as false. Where as in JAVA there is a separate data type boolean for true and false.
I resolved this issue after deleting folder where I was trying to add the file in Visual Studio. Deleted folder from window explorer also. After doing all this, successfully able to add folder and file.
I had a the same error and solved it after moving initialization of formBuilder
from ngOnInit
to constructor.
Strings are immutable in Python, which means once a string is created, you cannot alter the contents of the strings. If at all, you need to change it, a new instance of the string will be created with the alterations.
Having that in mind, we have so many ways to solve this
Using str.replace
,
>>> "it is icy".replace("i", "")
't s cy'
Using str.translate
,
>>> "it is icy".translate(None, "i")
't s cy'
Using Regular Expression,
>>> import re
>>> re.sub(r'i', "", "it is icy")
't s cy'
Using comprehension as a filter,
>>> "".join([char for char in "it is icy" if char != "i"])
't s cy'
Using filter
function
>>> "".join(filter(lambda char: char != "i", "it is icy"))
't s cy'
Timing comparison
def findreplace(m_string, char):
m_string = list(m_string)
for k in m_string:
if k == char:
del(m_string[m_string.index(k)])
return "".join(m_string)
def replace(m_string, char):
return m_string.replace("i", "")
def translate(m_string, char):
return m_string.translate(None, "i")
from timeit import timeit
print timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
print timeit("replace('it is icy','i')", "from __main__ import replace")
print timeit("translate('it is icy','i')", "from __main__ import translate")
Result
1.64474582672
0.29278588295
0.311302900314
str.replace
and str.translate
methods are 8 and 5 times faster than the accepted answer.
Note: Comprehension method and filter methods are expected to be slower, for this case, since they have to create list and then they have to be traversed again to construct a string. And re
is a bit overkill for a single character replacement. So, they all are excluded from the timing comparison.
It means
myclass *p = NULL;
*p = ...; // illegal: dereferencing NULL pointer
... = *p; // illegal: dereferencing NULL pointer
p->meth(); // illegal: equivalent to (*p).meth(), which is dereferencing NULL pointer
myclass *p = /* some legal, non-NULL pointer */;
*p = ...; // Ok
... = *p; // Ok
p->meth(); // Ok, if myclass::meth() exists
basically, almost anything involving (*p)
or implicitly involving (*p)
, e.g. p->...
which is a shorthand for (*p). ...
; except for pointer declaration.
file.lines
with JFile package
var JFile=require('jfile');
var myF=new JFile("./data.txt");
myF.lines // ["first line","second line"] ....
Don't forget before :
npm install jfile --save
Set the SelectedPath property before you call ShowDialog ...
folderBrowserDialog1.SelectedPath = @"c:\temp\";
folderBrowserDialog1.ShowDialog();
Will start them at C:\Temp
put the folder which has the properties file for log in java build path source. You can add it by right clicking the project ----> build path -----> configure build path ------> add t
I have modified @rahul kumars answer, so that it uses Observables instead:
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Observable";
import { Observer } from "rxjs/Observer";
@Injectable()
export class ScriptLoaderService {
private scripts: ScriptModel[] = [];
public load(script: ScriptModel): Observable<ScriptModel> {
return new Observable<ScriptModel>((observer: Observer<ScriptModel>) => {
var existingScript = this.scripts.find(s => s.name == script.name);
// Complete if already loaded
if (existingScript && existingScript.loaded) {
observer.next(existingScript);
observer.complete();
}
else {
// Add the script
this.scripts = [...this.scripts, script];
// Load the script
let scriptElement = document.createElement("script");
scriptElement.type = "text/javascript";
scriptElement.src = script.src;
scriptElement.onload = () => {
script.loaded = true;
observer.next(script);
observer.complete();
};
scriptElement.onerror = (error: any) => {
observer.error("Couldn't load script " + script.src);
};
document.getElementsByTagName('body')[0].appendChild(scriptElement);
}
});
}
}
export interface ScriptModel {
name: string,
src: string,
loaded: boolean
}
Some examples of formatted output to stdout and stderr:
printf("%s", "Hello world\n"); // "Hello world" on stdout (using printf)
fprintf(stdout, "%s", "Hello world\n"); // "Hello world" on stdout (using fprintf)
fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)
The other answers didn't work for me, but this did:
del /s /q *.svn
rmdir /s /q *.svn
/q disables Yes/No prompting
/s means delete the file(s) from all subdirectories.
If you have two or more field to order try this:
var soterdList = initialList.OrderBy(x => x.Priority).
ThenBy(x => x.ArrivalDate).
ThenBy(x => x.ShipDate);
You can add other fields with clasole "ThenBy"
jQuery UI Touch Punch just solves it all.
It's a Touch Event Support for jQuery UI. Basically, it just wires touch event back to jQuery UI. Tested on iPad, iPhone, Android and other touch-enabled mobile devices. I used jQuery UI sortable and it works like a charm.
Solution posted by Denys S. in the question post:
I quite messed it up with c to c++ conversion (basically env
variable stuff), but I got it working with the following code for C++:
#include <string.h>
#include <stdio.h>
#include <jni.h>
jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){
jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);
const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
printf("%s\n", str);
return (*env)->NewStringUTF(env, str);
}
And next code for java methods:
public class MainActivity extends Activity {
private static String LIB_NAME = "thelib";
static {
System.loadLibrary(LIB_NAME);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textview);
tv.setText(this.getJniString());
}
// please, let me live even though I used this dark programming technique
public String messageMe(String text) {
System.out.println(text);
return text;
}
public native String getJniString();
}
In some cases when you need to convert enum -> NSString and NSString -> enum it might be simpler to use a typedef and #define (or const NSStrings) instead of enum:
typedef NSString * ImageType;
#define ImageTypeJpg @"JPG"
#define ImageTypePng @"PNG"
#define ImageTypeGif @"GIF"
and then just operate with "named" strings as with any other NSString:
@interface MyData : NSObject
@property (copy, nonatomic) ImageType imageType;
@end
@implementation MyData
- (void)doSomething {
//...
self.imageType = ImageTypePng;
//...
if ([self.imageType isEqualToString:ImageTypeJpg]) {
//...
}
}
@end
For me, the try_files
directive in the (currently most voted) answer https://stackoverflow.com/a/11957896/608359 led to rewrite cycles,
*173 rewrite or internal redirection cycle while internally redirecting
I had better luck with the index directive. Note that I used a forward slash before the name, which might or might not be what you want.
server {
listen 443 ssl;
server_name example.com;
root /home/dclo/example;
index /index.html;
error_page 404 /index.html;
# ... ssl configuration
}
In this case, I wanted all paths to lead to /index.html, including when returning a 404.
$python 2.7.8
from timeit import timeit
import numpy
timeit("list(0 for i in xrange(0, 100000))", number=1000)
> 8.173301935195923
timeit("[0 for i in xrange(0, 100000)]", number=1000)
> 4.881675958633423
timeit("[0] * 100000", number=1000)
> 0.6624710559844971
timeit('list(itertools.repeat(0, 100000))', 'import itertools', number=1000)
> 1.0820629596710205
You should use [0] * n
to generate a list with n
zeros.
See why [] is faster than list()
There is a gotcha though, both itertools.repeat
and [0] * n
will create lists whose elements refer to same id
. This is not a problem with immutable objects like integers or strings but if you try to create list of mutable objects like a list of lists ([[]] * n
) then all the elements will refer to the same object.
a = [[]] * 10
a[0].append(1)
a
> [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
[0] * n
will create the list immediately while repeat
can be used to create the list lazily when it is first accessed.
If you're dealing with really large amount of data and your problem doesn't need variable length of list or multiple data types within the list it is better to use numpy
arrays.
timeit('numpy.zeros(100000, numpy.int)', 'import numpy', number=1000)
> 0.057849884033203125
numpy
arrays will also consume less memory.
There's a little bit more information about the semantics of these errors in RFC 2616, which documents HTTP 1.1.
Personally, I would probably use 400 Bad Request
, but this is just my personal opinion without any factual support.
more generally, this could also look like this:
import multiprocessing
def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n]
numberOfThreads = 4
if __name__ == '__main__':
jobs = []
for i, param in enumerate(params):
p = multiprocessing.Process(target=f, args=(i,param))
jobs.append(p)
for i in chunks(jobs,numberOfThreads):
for j in i:
j.start()
for j in i:
j.join()
Of course, that way is quite cruel (since it waits for every process in a junk until it continues with the next chunk). Still it works well for approx equal run times of the function calls.
To handle HTTP POST
request in Express.js version 4 and above, you need to install middleware module called body-parser
.
body-parser
extract the entire body portion of an incoming request stream and exposes it on req.body
.
The middleware was a part of Express.js earlier but now you have to install it separately.
This body-parser
module parses the JSON, buffer, string and URL encoded data submitted using HTTP POST
request. Install body-parser
using NPM as shown below.
npm install body-parser --save
edit in 2019-april-2: in [email protected] the body-parser middleware bundled with express. for more details see this
You can use a sprite which has both version—the colored and the monochrome—stored into it.
Is it possible that this is an error avoidance technique (advisable or not..)? Since "" is still a string, you would be able to call string functions on it that would result in an exception if it was NULL?
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
Here is a pure-java implementation of background image repeating:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.bg_image);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
LinearLayout layout = new LinearLayout(this);
layout.setBackgroundDrawable(bitmapDrawable);
}
In this case, our background image would have to be stored in res/drawable/bg_image.png.
Assuming you have:
HashMap<Key, Value> map; // Assigned or populated somehow.
For a list of values:
List<Value> values = new ArrayList<Value>(map.values());
For a list of keys:
List<Key> keys = new ArrayList<Key>(map.keySet());
Note that the order of the keys and values will be unreliable with a HashMap; use a LinkedHashMap if you need to preserve one-to-one correspondence of key and value positions in their respective lists.
Use StringBuilder's append line built-in functions:
StringBuilder sb = new StringBuilder();
sb.AppendLine("First line");
sb.AppendLine("Second line");
sb.AppendLine("Third line");
First line
Second line
Third line
I use one of the following two ways for this check:
In case you are logged in to "private.registry.com" you will see an entry for the same as following in ~/.docker/config.json
:
"auths": {
"private.registry.com": {
"auth": "gibberishgibberishgibberishgibberishgibberishgibberish"
}
}
If you are trying to see if you already have an active session with private.registry.com, try to login again:
bash$ docker login private.registry.com
Username (logged-in-user):
If you get an output like the above, it means logged-in-user
already had an active session with private.registry.com
. If you are just prompted for username instead, that would indicate that there's no active session.
FSPL depends on two parameters: First is the frequency of radio signals;Second is the wireless transmission distance. The following formula can reflect the relationship between them.
FSPL (dB) = 20log10(d) + 20log10(f) + K
d = distance
f = frequency
K= constant that depends on the units used for d and f
If d is measured in kilometers, f in MHz, the formula is:
FSPL (dB) = 20log10(d)+ 20log10(f) + 32.44
From the Fade Margin equation, Free Space Path Loss can be computed with the following equation.
Free Space Path Loss=Tx Power-Tx Cable Loss+Tx Antenna Gain+Rx Antenna Gain - Rx Cable Loss - Rx Sensitivity - Fade Margin
With the above two Free Space Path Loss equations, we can find out the Distance in km.
Distance (km) = 10(Free Space Path Loss – 32.44 – 20log10(f))/20
The Fresnel Zone is the area around the visual line-of-sight that radio waves spread out into after they leave the antenna. You want a clear line of sight to maintain strength, especially for 2.4GHz wireless systems. This is because 2.4GHz waves are absorbed by water, like the water found in trees. The rule of thumb is that 60% of Fresnel Zone must be clear of obstacles. Typically, 20% Fresnel Zone blockage introduces little signal loss to the link. Beyond 40% blockage the signal loss will become significant.
FSPLr=17.32*v(d/4f)
d = distance [km]
f = frequency [GHz]
r = radius [m]
the parent element has not to be empty at least put
before the child element.
I used JMock early. I've tried Mockito at my last project and liked it. More concise, more cleaner. PowerMock covers all needs which are absent in Mockito, such as mocking a static code, mocking an instance creation, mocking final classes and methods. So I have all I need to perform my work.
INSERT
INTO Employee
(emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT '001', 'John Doe', '1 River Walk, Green Street', state_id, position_id, manager_id
FROM dual
JOIN state s
ON s.state_name = 'New York'
JOIN positions p
ON p.position_name = 'Sales Executive'
JOIN manager m
ON m.manager_name = 'Barry Green'
Note that but a single spelling mistake (or an extra space) will result in a non-match and nothing will be inserted.
You might be better asking this on the WiX-users mailing list.
WiX is best used with a firm understanding of what Windows Installer is doing. You might consider getting "The Definitive Guide to Windows Installer".
The action that removes an existing product is the RemoveExistingProducts action. Because the consequences of what it does depends on where it's scheduled - namely, whether a failure causes the old product to be reinstalled, and whether unchanged files are copied again - you have to schedule it yourself.
RemoveExistingProducts
processes <Upgrade>
elements in the current installation, matching the @Id
attribute to the UpgradeCode
(specified in the <Product>
element) of all the installed products on the system. The UpgradeCode
defines a family of related products. Any products which have this UpgradeCode, whose versions fall into the range specified, and where the UpgradeVersion/@OnlyDetect
attribute is no
(or is omitted), will be removed.
The documentation for RemoveExistingProducts
mentions setting the UPGRADINGPRODUCTCODE
property. It means that the uninstall process for the product being removed receives that property, whose value is the Product/@Id
for the product being installed.
If your original installation did not include an UpgradeCode
, you will not be able to use this feature.
I had a similar situation and solved by using a temp table inside the procedure, with the same fields being returned by the original Stored Procedure:
CREATE PROCEDURE mynewstoredprocedure
AS
BEGIN
INSERT INTO temptable (field1, field2)
EXEC mystoredprocedure @param1, @param2
select field1, field2 from temptable
-- (mystoredprocedure returns field1, field2)
END
I found a project called Fizzler that takes a jQuery/Sizzler approach to selecting HTML elements. It's based on HTML Agility Pack. It's currently in beta and only supports a subset of CSS selectors, but it's pretty damn cool and refreshing to use CSS selectors over nasty XPath.
Okay, so this question is old... but I wanted to do something similar and I found a solution that works for me. Maybe it might help someone else.
I have a List<QuestionType>
that I fill a drop down with. I want to put that selection into the QuestionType
property on the Question
object that I'm creating in the form. I'm using Knockout.js
for the select binding. This sets the self.QuestionType
knockout observable property to a QuestionType
object when the user selects one.
<select class="form-control form-control-sm"
data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">
</select>
I have a hidden field that will hold this object:
@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)
In the subscription for the observable, I set the hidden field to a JSON.stringify
-ed version of the object.
self.QuestionType.subscribe(function(newValue) {
if (newValue !== null && newValue !== undefined) {
document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);
}
});
In the Question
object, I have a field called QuestionTypeJson
that is filled when the user selects a question type. I use this field to get the QuestionType
in the Question
object like this:
public string QuestionTypeJson { get; set; }
private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
{
get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
set => _questionType = value;
}
So if the QuestionTypeJson
field contains something, it will deserialize that and use it for QuestionType
, otherwise it'll just use what is in the backing field.
I have essentially 'passed' a JavaScript object to my model without using Razor
or an Ajax
call. You can probably do something similar to this without using Knockout.js
, but that's what I'm using so...
The simplest Answer:
#include <stdio.h>
int main(void) {
int a[] = {2,3,4,5,4,5,6,78,9,91,435,4,5,76,7,34};//for Example only
int size;
size = sizeof(a)/sizeof(a[0]);//Method
printf ("size = %d",size);
return 0;
}
In case people are still having trouble with this. I wrote a quick blog post about using Autolayout with UITableViews Leveraging Autolayout For Dynamic Cell Heights as well as an open source component to help make this more abstract and easier to implement. https://github.com/Raizlabs/RZCellSizeManager
It's hard to tell what you're going for in that example. exports =
is about exporting from external modules, but the code sample you linked is an internal module.
Rule of thumb: If you write module foo { ... }
, you're writing an internal module; if you write export something something
at top-level in a file, you're writing an external module. It's somewhat rare that you'd actually write export module foo
at top-level (since then you'd be double-nesting the name), and it's even rarer that you'd write module foo
in a file that had a top-level export (since foo
would not be externally visible).
The following things make sense (each scenario delineated by a horizontal rule):
// An internal module named SayHi with an exported function 'foo'
module SayHi {
export function foo() {
console.log("Hi");
}
export class bar { }
}
// N.B. this line could be in another file that has a
// <reference> tag to the file that has 'module SayHi' in it
SayHi.foo();
var b = new SayHi.bar();
file1.ts
// This *file* is an external module because it has a top-level 'export'
export function foo() {
console.log('hi');
}
export class bar { }
file2.ts
// This file is also an external module because it has an 'import' declaration
import f1 = module('file1');
f1.foo();
var b = new f1.bar();
file1.ts
// This will only work in 0.9.0+. This file is an external
// module because it has a top-level 'export'
function f() { }
function g() { }
export = { alpha: f, beta: g };
file2.ts
// This file is also an external module because it has an 'import' declaration
import f1 = require('file1');
f1.alpha(); // invokes f
f1.beta(); // invokes g
You could to this trick: create a file 1 hour ago, and use the -newer file
argument.
(Or use touch -t
to create such a file).
$ g=3
$ c=133
$ ([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
efg
$ g=1
$ c=123
$ ([ "$g$c" = "1123" ] || [ "$g$c" = "2456" ]) && echo "abc" || echo "efg"
abc
UPDATE table_name
SET column_name=CASE
WHEN column_name in ('value1', 'value2',.....)
THEN 'update_value'
WHEN column_name in ('value1', 'value2',.....)
THEN 'update_value'
END
table_name
= The name of table on which you want to perform operation.
column_name
= The name of Column/Field of which value you want to set.
update_value
= The value you want to set of column_name
mkdir -p ~/.ssh/
cat your_key > ~/.ssh/authorized_keys
cat your_key >> ~/.ssh/authorized_keys
$.ajax({
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
alert(location.ip);
}
});
This code will work https sites too
In my case, I already was signed in. So I had to sign out
and sign in
again.
In spanish Cerrar Sesion
is sign out
.
You can use several methods to remove item(s) from an Array:
//1
someArray.shift(); // first element removed
//2
someArray = someArray.slice(1); // first element removed
//3
someArray.splice(0, 1); // first element removed
//4
someArray.pop(); // last element removed
//5
someArray = someArray.slice(0, a.length - 1); // last element removed
//6
someArray.length = someArray.length - 1; // last element removed
If you want to remove element at position x
, use:
someArray.splice(x, 1);
Or
someArray = someArray.slice(0, x).concat(someArray.slice(-x));
Reply to the comment of @chill182: you can remove one or more elements from an array using Array.filter
, or Array.splice
combined with Array.findIndex
(see MDN), e.g.
// non destructive filter > noJohn = John removed, but someArray will not change_x000D_
let someArray = getArray();_x000D_
let noJohn = someArray.filter( el => el.name !== "John" ); _x000D_
log("non destructive filter > noJohn = ", format(noJohn));_x000D_
log(`**someArray.length ${someArray.length}`);_x000D_
_x000D_
// destructive filter/reassign John removed > someArray2 =_x000D_
let someArray2 = getArray();_x000D_
someArray2 = someArray2.filter( el => el.name !== "John" );_x000D_
log("", "destructive filter/reassign John removed > someArray2 =", _x000D_
format(someArray2));_x000D_
log(`**someArray2.length ${someArray2.length}`);_x000D_
_x000D_
// destructive splice /w findIndex Brian remains > someArray3 =_x000D_
let someArray3 = getArray();_x000D_
someArray3.splice(someArray3.findIndex(v => v.name === "Kristian"), 1);_x000D_
someArray3.splice(someArray3.findIndex(v => v.name === "John"), 1);_x000D_
log("", "destructive splice /w findIndex Brian remains > someArray3 =", _x000D_
format(someArray3));_x000D_
log(`**someArray3.length ${someArray3.length}`);_x000D_
_x000D_
// Note: if you're not sure about the contents of your array, _x000D_
// you should check the results of findIndex first_x000D_
let someArray4 = getArray();_x000D_
const indx = someArray4.findIndex(v => v.name === "Michael");_x000D_
someArray4.splice(indx, indx >= 0 ? 1 : 0);_x000D_
log("", "check findIndex result first > someArray4 (nothing is removed) > ",_x000D_
format(someArray4));_x000D_
log(`**someArray4.length (should still be 3) ${someArray4.length}`);_x000D_
_x000D_
function format(obj) {_x000D_
return JSON.stringify(obj, null, " ");_x000D_
}_x000D_
_x000D_
function log(...txt) {_x000D_
document.querySelector("pre").textContent += `${txt.join("\n")}\n`_x000D_
}_x000D_
_x000D_
function getArray() {_x000D_
return [ {name: "Kristian", lines: "2,5,10"},_x000D_
{name: "John", lines: "1,19,26,96"},_x000D_
{name: "Brian", lines: "3,9,62,36"} ];_x000D_
}
_x000D_
<pre>_x000D_
**Results**_x000D_
_x000D_
</pre>
_x000D_
You've already got it: A if test else B
is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:
{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
The final if
clause acts as a filter, which is different from having the conditional expression.
You should be using where
, select
is a projection that returns the output of the statement, thus why you get boolean values. where
is a filter that keeps the structure of the dataframe, but only keeps data where the filter works.
Along the same line though, per the documentation, you can write this in 3 different ways
// The following are equivalent:
peopleDf.filter($"age" > 15)
peopleDf.where($"age" > 15)
peopleDf($"age" > 15)
Using Java 8 lambda expression:
editText.setOnFocusChangeListener((v, hasFocus) -> {
if(!hasFocus) {
String value = String.valueOf( editText.getText() );
}
});
You would just do the same thing, looping through the array to search for the term you want. Of course if it's a sorted array this would be much faster, so something similar to prehaps:
for(int i = 0; i < arraySize; i++){
if(array[i] == itemToFind){
break;
}
}
This thread is a little old but this worked for me:
numberString = "onetwothreefourfivesixseveneightninefiveten"
testString = "five"
marker = 0
while marker < len(numberString):
try:
print(numberString.index("five",marker))
marker = numberString.index("five", marker) + 1
except ValueError:
print("String not found")
marker = len(numberString)
To dump large tables, you should combine the --single-transaction option with --quick.
http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction
Quite a few good answers, but I just wanted to share my personal favourite Swift random number generation function for positive integers:
func randomNumber(range: Range<Int> = 1...6) -> Int {
let min = range.startIndex
let max = range.endIndex
return Int(arc4random_uniform(UInt32(max - min))) + min
}
Here's a quick update for Swift 3 and, as a bonus, it now works for any value type that conforms to the SignedInteger protocol - much more convenient for core data applications that need to specify Int16, Int32 etc. As a quick note, if you really need it to work on unsigned integers as well, just copy the entire function then replace SignedInteger
with UnsignedInteger
and toIntMax()
with toUIntMax()
.
func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
let length = (range.upperBound - range.lowerBound + 1).toIntMax()
let value = arc4random().toIntMax() % length + range.lowerBound.toIntMax()
return T(value)
}
Thanks to the removal of toIntMax() in Swift 4, we now have to use a different means of converting to a common integer type. In this example I'm using Int64 which is large enough for my purposes, but if you're using unsigned integers or have an Int128 or Int256 custom type you should use those.
public func randomNumber<T : SignedInteger>(inRange range: ClosedRange<T> = 1...6) -> T {
let length = Int64(range.upperBound - range.lowerBound + 1)
let value = Int64(arc4random()) % length + Int64(range.lowerBound)
return T(value)
}
One more, for the total random-phile, here's an extension that returns a random element from any Collection
type object. Note this uses the above function to generate its index so you will need both.
extension Collection {
func randomItem() -> Self.Iterator.Element {
let count = distance(from: startIndex, to: endIndex)
let roll = randomNumber(inRange: 0...count-1)
return self[index(startIndex, offsetBy: roll)]
}
}
randomNumber()
returns a random number between 1 and 6.
randomNumber(50...100)
returns a number between 50 and 100 inclusive. Naturally you can replace the values of 50 and 100 with whatever you like.
Alas, my best StackOverflow answer has been rendered obsolete at last. You can now use simply Int.random(in: 1 ... 6)
to generate a random number in a given range. Also works for other forms of integer and floating point number. Collection types also now provide shuffle()
and randomElement()
functions. There is therefore no longer any need for fancy randomisation functions unless you want to use a specific randomiser type.
Kinda late to the party, but in case anyone else is struggling. None of the Google searches I've found for the past two days have come up with anything that works, but I came up with a concise and elegant solution that will always work no matter how many nested tags you have:
function cursor_position() {_x000D_
var sel = document.getSelection();_x000D_
sel.modify("extend", "backward", "paragraphboundary");_x000D_
var pos = sel.toString().length;_x000D_
if(sel.anchorNode != undefined) sel.collapseToEnd();_x000D_
_x000D_
return pos;_x000D_
}_x000D_
_x000D_
// Demo:_x000D_
var elm = document.querySelector('[contenteditable]');_x000D_
elm.addEventListener('click', printCaretPosition)_x000D_
elm.addEventListener('keydown', printCaretPosition)_x000D_
_x000D_
function printCaretPosition(){_x000D_
console.log( cursor_position(), 'length:', this.textContent.trim().length )_x000D_
}
_x000D_
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
_x000D_
It selects all the way back to the beginning of the paragraph and then counts the length of the string to get the current position and then undoes the selection to return the cursor to the current position. If you want to do this for an entire document (more than one paragraph), then change paragraphboundary
to documentboundary
or whatever granularity for your case. Check out the API for more details. Cheers! :)
CTRL + SHIFT + F will auto format your code(whether it is highlighted or non highlighted).
Option using dplyr
require(dplyr)
dt<-as.data.frame(matrix(runif(10*10),10,10))
dt <- select(dt, -V1, -V2, -V3, -V4)
cor(dt)
Have a look at <openssl/pem.h>
. It gives possible BEGIN markers.
Copying the content from the above link for quick reference:
#define PEM_STRING_X509_OLD "X509 CERTIFICATE"
#define PEM_STRING_X509 "CERTIFICATE"
#define PEM_STRING_X509_PAIR "CERTIFICATE PAIR"
#define PEM_STRING_X509_TRUSTED "TRUSTED CERTIFICATE"
#define PEM_STRING_X509_REQ_OLD "NEW CERTIFICATE REQUEST"
#define PEM_STRING_X509_REQ "CERTIFICATE REQUEST"
#define PEM_STRING_X509_CRL "X509 CRL"
#define PEM_STRING_EVP_PKEY "ANY PRIVATE KEY"
#define PEM_STRING_PUBLIC "PUBLIC KEY"
#define PEM_STRING_RSA "RSA PRIVATE KEY"
#define PEM_STRING_RSA_PUBLIC "RSA PUBLIC KEY"
#define PEM_STRING_DSA "DSA PRIVATE KEY"
#define PEM_STRING_DSA_PUBLIC "DSA PUBLIC KEY"
#define PEM_STRING_PKCS7 "PKCS7"
#define PEM_STRING_PKCS7_SIGNED "PKCS #7 SIGNED DATA"
#define PEM_STRING_PKCS8 "ENCRYPTED PRIVATE KEY"
#define PEM_STRING_PKCS8INF "PRIVATE KEY"
#define PEM_STRING_DHPARAMS "DH PARAMETERS"
#define PEM_STRING_DHXPARAMS "X9.42 DH PARAMETERS"
#define PEM_STRING_SSL_SESSION "SSL SESSION PARAMETERS"
#define PEM_STRING_DSAPARAMS "DSA PARAMETERS"
#define PEM_STRING_ECDSA_PUBLIC "ECDSA PUBLIC KEY"
#define PEM_STRING_ECPARAMETERS "EC PARAMETERS"
#define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY"
#define PEM_STRING_PARAMETERS "PARAMETERS"
#define PEM_STRING_CMS "CMS"
I got similar error. This is because JDK is not properly set in eclipse. Cucumber needs JDK along with JRE, so add below dependency in your pom.xml
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.6</version>
<scope>system</scope>
<systemPath>C:\Program Files\Java\jdk1.8.0_101\lib\tools.jar</systemPath>
</dependency>
try this:
extMobileNo.addTextChangedListener(new MyTextWatcher(extMobileNo));
private boolean validateMobile() {
String mobile =extMobileNo.getText().toString().trim();
if(mobile.isEmpty()||!isValidMobile(mobile)||extMobileNo.getText().toString().toString().length()<10 || mobile.length()>13 )
{
inputLayoutMobile.setError(getString(R.string.err_msg_mobile));
requestFocus(extMobileNo);
return false;
}
else {
inputLayoutMobile.setErrorEnabled(false);
}
return true;
}
private static boolean isValidMobile(String mobile)
{
return !TextUtils.isEmpty(mobile)&& Patterns.PHONE.matcher(mobile).matches();
}
In my case the form (which I cannot modify) was always sending POST.
While in my Web Service I tried to implement GET method (due to lack of documentation I expected that both are allowed).
Thus, it was failing as "Not allowed", since there was no method with POST type on my end.
Changing @GET
to @POST
above my WS method fixed the issue.
There are a few things interacting here:
docker run your_image arg1 arg2
will replace the value of CMD
with arg1 arg2
. That's a full replacement of the CMD, not appending more values to it. This is why you often see docker run some_image /bin/bash
to run a bash shell in the container.
When you have both an ENTRYPOINT and a CMD value defined, docker starts the container by concatenating the two and running that concatenated command. So if you define your entrypoint to be file.sh
, you can now run the container with additional args that will be passed as args to file.sh
.
Entrypoints and Commands in docker have two syntaxes, a string syntax that will launch a shell, and a json syntax that will perform an exec. The shell is useful to handle things like IO redirection, chaining multiple commands together (with things like &&
), variable substitution, etc. However, that shell gets in the way with signal handling (if you've ever seen a 10 second delay to stop a container, this is often the cause) and with concatenating an entrypoint and command together. If you define your entrypoint as a string, it would run /bin/sh -c "file.sh"
, which alone is fine. But if you have a command defined as a string too, you'll see something like /bin/sh -c "file.sh" /bin/sh -c "arg1 arg2"
as the command being launched inside your container, not so good. See the table here for more on how these two options interact
The shell -c
option only takes a single argument. Everything after that would get passed as $1
, $2
, etc, to that single argument, but not into an embedded shell script unless you explicitly passed the args. I.e. /bin/sh -c "file.sh $1 $2" "arg1" "arg2"
would work, but /bin/sh -c "file.sh" "arg1" "arg2"
would not since file.sh
would be called with no args.
Putting that all together, the common design is:
FROM ubuntu:14.04
COPY ./file.sh /
RUN chmod 755 /file.sh
# Note the json syntax on this next line is strict, double quotes, and any syntax
# error will result in a shell being used to run the line.
ENTRYPOINT ["file.sh"]
And you then run that with:
docker run your_image arg1 arg2
There's a fair bit more detail on this at:
You might try searching the internet for ".htaccess Options not allowed here".
A suggestion I found (using google) is:
Check to make sure that your httpd.conf file has AllowOverride All.
A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):
# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html
# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On
</IfModule>
# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>
Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.
sudo nginx -t
should test all files and return errors and warnings locations
Use PHP DOM to parse and add <br/>
in it. Like this:
$html = '<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>';
//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('textarea');
//get text and add <br/> then remove last <br/>
$lines = $nodes->item(0)->nodeValue;
//split it by newlines
$lines = explode("\n", $lines);
//add <br/> at end of each line
foreach($lines as $line)
$output .= $line . "<br/>";
//remove last <br/>
$output = rtrim($output, "<br/>");
//display it
var_dump($output);
This outputs:
string ' put returns between paragraphs
<br/>for linebreak add 2 spaces at end
<br/>indent code by 4 spaces
<br/>quote by placing > at start of line
' (length=141)
You should add reference to "Microsoft.AspNet.WebApi.Client" package (read this article for samples).
Without any additional extension, you may use standard PostAsync
method:
client.PostAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json"));
where jsonInString
value you can get by calling JsonConvert.SerializeObject(<your object>);
No there is no difference at all in functionality.
(The same is true for all other DBMS - most of them support both styles):
Here is the current SQL reference: https://docs.oracle.com/database/121/SQLRF/conditions002.htm#CJAGAABC
The SQL standard only defines a single operator for "not equals" and that is <>
I think MAVEN_OPTS
would be most appropriate for you. See here: http://maven.apache.org/configure.html
In Unix:
Add the
MAVEN_OPTS
environment variable to specify JVM properties, e.g.export MAVEN_OPTS="-Xms256m -Xmx512m"
. This environment variable can be used to supply extra options to Maven.
In Win, you need to set environment variable via the dialogue box
Add ... environment variable by opening up the system properties (
WinKey + Pause
),... In the same dialog, add theMAVEN_OPTS
environment variable in the user variables to specify JVM properties, e.g. the value-Xms256m -Xmx512m
. This environment variable can be used to supply extra options to Maven.
Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.
VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"
With the following appended to android kernel cmd:
UVESA_MODE=440x680 DPI=120
You could set up a cron job to run on every day of the month, and have it run a shell script like the following. This script works out whether tomorrow's day number is less than today's (i.e. if tomorrow is a new month), and then does whatever you want.
TODAY=`date +%d`
TOMORROW=`date +%d -d "1 day"`
# See if tomorrow's day is less than today's
if [ $TOMORROW -lt $TODAY ]; then
echo "This is the last day of the month"
# Do stuff...
fi
Here is a method that does not require editing the code and works regardless of the number of characters.
String text =
java.text.MessageFormat.format(
"You're about to delete {0} rows.".replaceAll("'", "''"), 5);
While sizeof
works for this specific type of string:
char str[] = "content";
int charcount = sizeof str - 1; // -1 to exclude terminating '\0'
It does not work if str
is pointer (sizeof
returns size of pointer, usually 4 or 8) or array with specified length (sizeof
will return the byte count matching specified length, which for char type are same).
Just use strlen()
.
Please use json.Decoder
instead of json.Unmarshal
.
func test(rw http.ResponseWriter, req *http.Request) {
decoder := json.NewDecoder(req.Body)
var t test_struct
err := decoder.Decode(&t)
if err != nil {
panic(err)
}
log.Println(t.Test)
}
This should work:
int hh, mm, ss;
struct tm when = {0};
sscanf_s(date, "%d:%d:%d", &hh, &mm, &ss);
when.tm_hour = hh;
when.tm_min = mm;
when.tm_sec = ss;
time_t converted;
converted = mktime(&when);
Modify as needed.
You have two ways to enable it.
First, you can set the absolute path of the php module file in your httpd.conf file like this:
LoadModule php5_module /path/to/mods-available/libphp5.so
Second, you can link the module file to the mods-enabled directory:
ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so
Using the bitstring module:
>>> bitstring.BitArray(uint=1245427, length=24).bytes
'\x13\x00\xf3'
Note though that for this method you need to specify the length in bits of the bitstring you are creating.
Internally this is pretty much the same as Alex's answer, but the module has a lot of extra functionality available if you want to do more with your data.
You need a main()
function so the program knows where to start.
Like this:
String[][] arrays = { array1, array2, array3, array4, array5 };
or
String[][] arrays = new String[][] { array1, array2, array3, array4, array5 };
(The latter syntax can be used in assignments other than at the point of the variable declaration, whereas the shorter syntax only works with declarations.)
Use the Value
property.
MyDateTimePicker.Value = DateTime.Today.AddDays(-1);
DateTime.Today
holds today's date, from which you can subtract 1 day (add -1 days) to become yesterday.
DateTime.Now
, on the other hand, contains time information as well. DateTime.Now.AddDays(-1)
will return this time one day ago.
You are using Lists, concrete ArrayList. ArrayList also implements Collection interface. Collection interface has sort method which is used to sort the elements present in the specified list of Collection in ascending order. This will be the quickest and possibly the best way for your case.
Sorting a list in ascending order can be performed as default operation on this way:
Collections.sort(list);
Sorting a list in descending order can be performed on this way:
Collections.reverse(list);
According to these facts, your solution has to be written like this:
public class tes
{
public static void main(String args[])
{
List<Integer> lList = new ArrayList<Integer>();
lList.add(4);
lList.add(1);
lList.add(7);
lList.add(2);
lList.add(9);
lList.add(1);
lList.add(5);
Collections.sort(lList);
for(int i=0; i<lList.size();i++ )
{
System.out.println(lList.get(i));
}
}
}
More about Collections you can read here.
This is my implementation:
public class CardsDeck {
private ArrayList<Card> mCards;
private ArrayList<Card> mPulledCards;
private Random mRandom;
public enum Suit {
SPADES,
HEARTS,
DIAMONDS,
CLUBS;
}
public enum Rank {
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING,
ACE;
}
public CardsDeck() {
mRandom = new Random();
mPulledCards = new ArrayList<Card>();
mCards = new ArrayList<Card>(Suit.values().length * Rank.values().length);
reset();
}
public void reset() {
mPulledCards.clear();
mCards.clear();
/* Creating all possible cards... */
for (Suit s : Suit.values()) {
for (Rank r : Rank.values()) {
Card c = new Card(s, r);
mCards.add(c);
}
}
}
public static class Card {
private Suit mSuit;
private Rank mRank;
public Card(Suit suit, Rank rank) {
this.mSuit = suit;
this.mRank = rank;
}
public Suit getSuit() {
return mSuit;
}
public Rank getRank() {
return mRank;
}
public int getValue() {
return mRank.ordinal() + 2;
}
@Override
public boolean equals(Object o) {
return (o != null && o instanceof Card && ((Card) o).mRank == mRank && ((Card) o).mSuit == mSuit);
}
}
/**
* get a random card, removing it from the pack
* @return
*/
public Card pullRandom() {
if (mCards.isEmpty())
return null;
Card res = mCards.remove(randInt(0, mCards.size() - 1));
if (res != null)
mPulledCards.add(res);
return res;
}
/**
* Get a random cards, leaves it inside the pack
* @return
*/
public Card getRandom() {
if (mCards.isEmpty())
return null;
Card res = mCards.get(randInt(0, mCards.size() - 1));
return res;
}
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* @param min Minimum value
* @param max Maximum value. Must be greater than min.
* @return Integer between min and max, inclusive.
* @see java.util.Random#nextInt(int)
*/
public int randInt(int min, int max) {
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = mRandom.nextInt((max - min) + 1) + min;
return randomNum;
}
public boolean isEmpty(){
return mCards.isEmpty();
}
}
Here is how I do it:
(function ( $ ) {
$.fn.gridview = function( options ) {
..........
..........
var factory = new htmlFactory();
factory.header(...);
........
};
}( jQuery ));
var htmlFactory = function(){
//header
this.header = function(object){
console.log(object);
}
}
The servlet container's implementation of HttpServlet.service()
method will automatically forward to doGet()
or doPost()
as necessary, so you shouldn't need to override the service method.
In PHP 5.5+, you can do
function limit($iterable, $limit) {
foreach ($iterable as $key => $value) {
if (!$limit--) break;
yield $key => $value;
}
}
foreach (limit($arr, 10) as $key => $value) {
// do stuff
}
Generators rock.
You could match the port numbers from wireshark up to port numbers from, say, netstat which will tell you the PID of a process listening on that port.
This issue can also occur when upgrade from XCODE 11.x to 12.0. After installation of new version of XCODE, restart system to overcome this issue.
SELECT
hat,
shoe,
boat,
0 as placeholder
FROM
objects
And '' as placeholder
for strings.
With python 3 you can use the pathlib
module (pathlib.PurePath
for example):
>>> import pathlib
>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/')
>>> path.name
'folderD'
If you want the last folder name where a file is located:
>>> path = pathlib.PurePath('/folderA/folderB/folderC/folderD/file.py')
>>> path.parent.name
'folderD'
I know this is an old question, but Bill seems to be the only one that has actually "Explained" the issue. Everyone else seems to be coming up with complex solutions to a misuse of a declaration.
"The two values in your type declaration are precision and scale."
...
"If you specify (10, 4), that means you can only store 6 digits to the left of the decimal, or a max number of 999999.9999. Anything bigger than that will cause an overflow."
So if you declare DECIMAL(10,4)
you can have a total of 10 numbers, with 4 of them coming AFTER the decimal point.
so 123456.1234 has 10 digits, 4 after the decimal point. That will fit into the parameters of DECIMAL(10,4)
.
1234567.1234 will throw an error. there are 11 digits to fit into a 10 digit space, and 4 digits MUST be used AFTER the decimal point. Trimming a digit off the left side of the decimal is not an option.
If your 11 characters were 123456.12345, this would not throw an error as trimming(Rounding) from the end of a decimal value is acceptable.
When declaring decimals, always try to declare the maximum that your column will realistically use and the maximum number of decimal places you want to see.
So if your column would only ever show values with a maximum of 1 million and you only care about the first two decimal places, declare as DECIMAL(9,2)
.
This will give you a maximum number of 9,999,999.99 before an error is thrown.
Understanding the issue before you try to fix it, will ensure you choose the right fix for your situation, and help you to understand the reason why the fix is needed / works.
Again, i know i'm five years late to the party.
However, my two cents on a solution for this, (judging by your comments that the column is already set as DECIMAL(10,4)
and cant be changed)
Easiest way to do it would be two steps.
Check that your decimal is not further than 10 points away, then trim to 10 digits.
CASE WHEN CHARINDEX('.',CONVERT(VARCHAR(50),[columnName]))>10 THEN 'DealWithIt'
ELSE LEFT(CONVERT(VARCHAR(50),[columnName]),10)
END AS [10PointDecimalString]
The reason i left this as a string is so you can deal with the values that are over 10 digits long on the left of the decimal.
But its a start.
I was having the same problem and could not figure out what I was doing wrong. Turns out, the auto-complete for Android Studio was changing the text to either all caps or all lower case (depending on whether I typed in upper case or lower cast words before the auto-complete). The OS was not registering the name due to this issue and I would get the error regarding a missing permission. As stated above, ensure your permissions are labeled correctly:
Correct:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="ANDROID.PERMISSION.ACCESS_FINE_LOCATION" />
Incorrect:
<uses-permission android:name="android.permission.access_fine_location" />
Though this may seem trivial, its easy to overlook.
If there is some setting to make permissions non-case-sensitive, please add a comment with the instructions. Thank you!
It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:
insert into errortable (dateupdated, table1id)
values (sysdate, 1083);
It seems silly to convert the system date to a string just to convert it back to a date.
If you want to see the full date, then you can do:
select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;
@magi182's solution is solid, but it lacks the ability to set a maximum width. I think a maximum width of 640px is necessary because otherwhise the youtube thumbnail looks pixelated.
My solution with two wrappers works like a charm for me:
.videoWrapperOuter {
max-width:640px;
margin-left:auto;
margin-right:auto;
}
.videoWrapperInner {
float: none;
clear: both;
width: 100%;
position: relative;
padding-bottom: 50%;
padding-top: 25px;
height: 0;
}
.videoWrapperInner iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<div class="videoWrapperOuter">
<div class="videoWrapperInner">
<iframe src="//www.youtube.com/embed/C6-TWRn0k4I"
frameborder="0" allowfullscreen></iframe>
</div>
</div>
I also set the padding-bottom in the inner wrapper to 50 %, because with @magi182's 56 %, a black bar on top and bottom appeared.
You could also just change the @RequestParam default required status to false so that HTTP response status code 400 is not generated. This will allow you to place the Annotations in any order you feel like.
@RequestParam(required = false)String name
Here is what you are looking for. But this also changes the color of radioButton etc. So you might want to use a theme for it.
<item name="colorControlNormal">@color/colorControlNormal</item>
<v-container>
has to be right after <template>
, if there is a <div>
in between, the vertical align will just not work.
<template>
<v-container fill-height>
<v-row class="justify-center align-center">
<v-col cols="12" sm="4">
Centered both vertically and horizontally
</v-col>
</v-row>
</v-container>
</template>
Pure JS with cross-browser and debouncing (Pretty good performance)
var CheckIfScrollBottom = debouncer(function() {
if(getDocHeight() == getScrollXY()[1] + window.innerHeight) {
console.log('Bottom!');
}
},500);
document.addEventListener('scroll',CheckIfScrollBottom);
function debouncer(a,b,c){var d;return function(){var e=this,f=arguments,g=function(){d=null,c||a.apply(e,f)},h=c&&!d;clearTimeout(d),d=setTimeout(g,b),h&&a.apply(e,f)}}
function getScrollXY(){var a=0,b=0;return"number"==typeof window.pageYOffset?(b=window.pageYOffset,a=window.pageXOffset):document.body&&(document.body.scrollLeft||document.body.scrollTop)?(b=document.body.scrollTop,a=document.body.scrollLeft):document.documentElement&&(document.documentElement.scrollLeft||document.documentElement.scrollTop)&&(b=document.documentElement.scrollTop,a=document.documentElement.scrollLeft),[a,b]}
function getDocHeight(){var a=document;return Math.max(a.body.scrollHeight,a.documentElement.scrollHeight,a.body.offsetHeight,a.documentElement.offsetHeight,a.body.clientHeight,a.documentElement.clientHeight)}
Demo : http://jsbin.com/geherovena/edit?js,output
PS: Debouncer
, getScrollXY
, getDocHeight
not written by me
I just show how its work, And how I will do
Although the question is: How do I get control early enough to issue an error message and exit?
The question that I answer is: How do I get control early enough to issue an error message before starting the app?
I can answer it a lot differently then the other posts. Seems answers so far are trying to solve your question from within Python.
I say, do version checking before launching Python. I see your path is Linux or unix. However I can only offer you a Windows script. I image adapting it to linux scripting syntax wouldn't be too hard.
Here is the DOS script with version 2.7:
@ECHO OFF
REM see http://ss64.com/nt/for_f.html
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
IF NOT ErrorLevel 1 GOTO Python27
ECHO must use python2.7 or greater
GOTO EOF
:Python27
python.exe tern.py
GOTO EOF
:EOF
This does not run any part of your application and therefore will not raise a Python Exception. It does not create any temp file or add any OS environment variables. And it doesn't end your app to an exception due to different version syntax rules. That's three less possible security points of access.
The FOR /F
line is the key.
FOR /F "tokens=1,2" %%G IN ('"python.exe -V 2>&1"') DO ECHO %%H | find "2.7" > Nul
For multiple python version check check out url: http://www.fpschultze.de/modules/smartfaq/faq.php?faqid=17
And my hack version:
[MS script; Python version check prelaunch of Python module] http://pastebin.com/aAuJ91FQ
Take note of "MAIN" class the element is placed, for example,
<div class="container">
<ul class="select">
<li> First</li>
<li>Second</li>
</ul>
</div>
In the above scenario, the MAIN object the jQuery will watch is "container".
Then you will basically have elements names under container such as ul
, li
, and select
:
$(document).ready(function(e) {
$('.container').on( 'click',".select", function(e) {
alert("CLICKED");
});
});
If your Blog
class has an appropriate equals()
method defined on it, the simplest way is just to create a Set
out of your list, which will automatically remove duplicates:
List<Blog> blogList = ...; // your initial list
Set<Blog> noDups = new HashSet<Blog>(blogList)
The chances are this will work transparently with the rest of your code - if you're just iterating over the contents, for example, then any instance of Collection
is as good as another. (If iteration order matters, then you may prefer a LinkedHashSet
instead, which will preserve the original ordering of the list).
If you really need the result to be a List
then keeping with the straightforward approach, you can just convert it straight back again by wrapping in an ArrayList
(or similar). If your collections are relatively small (less than a thousand elements, say) then the apparent inefficiencies of this approach are likely to be immaterial.
Follow steps given in https://michlstechblog.info/blog/python-install-python-with-pip-on-windows-by-the-embeddable-zip-file/. Replace x
with version number of Python.
pythonxx.__pth
file, located in your python folder.D:\Pythonx.x.x
to the following): D:\Pythonx.x.x
D:\Pythonx.x.x\DLLs
D:\Pythonx.x.x\lib
D:\Pythonx.x.x\lib\plat-win
D:\Pythonx.x.x\lib\site-packages
I made a small library that lets you easily use a throbber without images.
It uses CSS3 but falls back onto JavaScript if the browser doesn't support it.
// First argument is a reference to a container element in which you
// wish to add a throbber to.
// Second argument is the duration in which you want the throbber to
// complete one full circle.
var throbber = throbbage(document.getElementById("container"), 1000);
// Start the throbber.
throbber.play();
// Pause the throbber.
throbber.pause();
There is a bit of ambiguity in your question. There are at least three two interpretations:
di
refer to index valuesdi
refer to df['col1']
valuesdi
refer to index locations (not the OP's question, but thrown in for fun.)Below is a solution for each case.
Case 1:
If the keys of di
are meant to refer to index values, then you could use the update
method:
df['col1'].update(pd.Series(di))
For example,
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':['w', 10, 20],
'col2': ['a', 30, np.nan]},
index=[1,2,0])
# col1 col2
# 1 w a
# 2 10 30
# 0 20 NaN
di = {0: "A", 2: "B"}
# The value at the 0-index is mapped to 'A', the value at the 2-index is mapped to 'B'
df['col1'].update(pd.Series(di))
print(df)
yields
col1 col2
1 w a
2 B 30
0 A NaN
I've modified the values from your original post so it is clearer what update
is doing.
Note how the keys in di
are associated with index values. The order of the index values -- that is, the index locations -- does not matter.
Case 2:
If the keys in di
refer to df['col1']
values, then @DanAllan and @DSM show how to achieve this with replace
:
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':['w', 10, 20],
'col2': ['a', 30, np.nan]},
index=[1,2,0])
print(df)
# col1 col2
# 1 w a
# 2 10 30
# 0 20 NaN
di = {10: "A", 20: "B"}
# The values 10 and 20 are replaced by 'A' and 'B'
df['col1'].replace(di, inplace=True)
print(df)
yields
col1 col2
1 w a
2 A 30
0 B NaN
Note how in this case the keys in di
were changed to match values in df['col1']
.
Case 3:
If the keys in di
refer to index locations, then you could use
df['col1'].put(di.keys(), di.values())
since
df = pd.DataFrame({'col1':['w', 10, 20],
'col2': ['a', 30, np.nan]},
index=[1,2,0])
di = {0: "A", 2: "B"}
# The values at the 0 and 2 index locations are replaced by 'A' and 'B'
df['col1'].put(di.keys(), di.values())
print(df)
yields
col1 col2
1 A a
2 10 30
0 B NaN
Here, the first and third rows were altered, because the keys in di
are 0
and 2
, which with Python's 0-based indexing refer to the first and third locations.
We can also do the same using java 8.
public static<T> List<T> reverseList(List<T> list) {
List<T> reverse = new ArrayList<>(list.size());
list.stream()
.collect(Collectors.toCollection(LinkedList::new))
.descendingIterator()
.forEachRemaining(reverse::add);
return reverse;
}
jQuery.offset
needs to be combined with scrollTop
and scrollLeft
as shown in this diagram:
Demo:
function getViewportOffset($e) {_x000D_
var $window = $(window),_x000D_
scrollLeft = $window.scrollLeft(),_x000D_
scrollTop = $window.scrollTop(),_x000D_
offset = $e.offset(),_x000D_
rect1 = { x1: scrollLeft, y1: scrollTop, x2: scrollLeft + $window.width(), y2: scrollTop + $window.height() },_x000D_
rect2 = { x1: offset.left, y1: offset.top, x2: offset.left + $e.width(), y2: offset.top + $e.height() };_x000D_
return {_x000D_
left: offset.left - scrollLeft,_x000D_
top: offset.top - scrollTop,_x000D_
insideViewport: rect1.x1 < rect2.x2 && rect1.x2 > rect2.x1 && rect1.y1 < rect2.y2 && rect1.y2 > rect2.y1_x000D_
};_x000D_
}_x000D_
$(window).on("load scroll resize", function() {_x000D_
var viewportOffset = getViewportOffset($("#element"));_x000D_
$("#log").text("left: " + viewportOffset.left + ", top: " + viewportOffset.top + ", insideViewport: " + viewportOffset.insideViewport);_x000D_
});
_x000D_
body { margin: 0; padding: 0; width: 1600px; height: 2048px; background-color: #CCCCCC; }_x000D_
#element { width: 384px; height: 384px; margin-top: 1088px; margin-left: 768px; background-color: #99CCFF; }_x000D_
#log { position: fixed; left: 0; top: 0; font: medium monospace; background-color: #EEE8AA; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
_x000D_
<!-- scroll right and bottom to locate the blue square -->_x000D_
<div id="element"></div>_x000D_
<div id="log"></div>
_x000D_
Try to change type of ScoreIfNoMatch, like this:
public class MatrixModel
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
// the type should be string
public string ScoreIfNoMatch { get; set; }
}
Issue: When I was checking out some modified files in git, got this error. I was having two users ABC and XYZ. files are having uid:gid of ABC but it doesn't have git access and trying to checkout the files with same.
The solution I have tried: XYZ is having git access, tried checking out files with sudo and it worked..!!
As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).
On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.
You can check awesome material design components for AngularJS:
https://material.angularjs.org
One of the answers above mentions handling different pixel density but suggests computing the swipe parameters by hand. It is worth noting that you can actually obtain scaled, reasonable values from the system using ViewConfiguration
class:
final ViewConfiguration vc = ViewConfiguration.get(getContext());
final int swipeMinDistance = vc.getScaledPagingTouchSlop();
final int swipeThresholdVelocity = vc.getScaledMinimumFlingVelocity();
final int swipeMaxOffPath = vc.getScaledTouchSlop();
// (there is also vc.getScaledMaximumFlingVelocity() one could check against)
I noticed that using these values causes the "feel" of fling to be more consistent between the application and rest of system.
For angular 4+ versions you can try
<input [readonly]="true" type="date" name="date" />
Replace:
$authorization = "Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274"
with:
$authorization = "Authorization: Bearer 080042cad6356ad5dc0a720c18b53b8e53d4c274";
to make it a valid and working Authorization header.
Just add \
at the end of line. For example
one\
two
Will become
one
two
It's also better than two spaces because it's visible.
From gamedev
string.erase(std::remove_if(string.begin(), string.end(), std::isspace), string.end());
This a solution that uses the IDE to fix:
Data Conversion
item to your dataflow as shown below; Data Conversion
item, and set it as shown: DB Destination
item, Click on Mapping
, and ensure that your input Column is actually the same as coming from the Copy of [your column name], which is in fact the Data Conversion
output NOT the DB Source
Output (be careful here). Here is a screenshot:And thats it .. save and run ..
There is also a less "hacky" method which works for all popular browsers.
Google has included a browser-check in their Closure Library. In particular, have a look at goog.userAgent
and goog.userAgent.product
. In this way, you are also up to date if something changes in the way the browsers present themselves (given that you always run the latest version of the closure compiler.)
Don't fuss around with .htaccess files when you can use Apache mass virtual hosting.
From the documentation:
#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs
In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.
The only drawback is that the environment variable DOCUMENT_ROOT
is not correctly set to the used subdirectory, but the default document_root in de htconfig.
Adding reference to:
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>${jersey1.version}</version>
</dependency>
As long as adding clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true); on client creation solved the issue for me:
ClientConfig clientConfig = new DefaultClientConfig();
clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, true);
Client client = Client.create(clientConfig);
Here's what I use at the top of all my batch files. I just copy/paste from my template folder.
@echo off
:: --HAS ENDING BACKSLASH
set batdir=%~dp0
:: --MISSING ENDING BACKSLASH
:: set batdir=%CD%
pushd "%batdir%"
Setting current batch file's path to %batdir% allows you to call it in subsequent stmts in current batch file, regardless of where this batch file changes to. Using PUSHD allows you to use POPD to quickly set this batch file's path to original %batdir%. Remember, if using %batdir%ExtraDir or %batdir%\ExtraDir (depending on which version used above, ending backslash or not) you will need to enclose the entire string in double quotes if path has spaces (i.e. "%batdir%ExtraDir"). You can always use PUSHD %~dp0. [https: // ss64.com/ nt/ syntax-args .html] has more on (%~) parameters.
Note that using (::) at beginning of a line makes it a comment line. More importantly, using :: allows you to include redirectors, pipes, special chars (i.e. < > | etc) in that comment.
:: ORIG STMT WAS: dir *.* | find /v "1917" > outfile.txt
Of course, Powershell does this and lots more.
List<string> myList Str = myList.Select(x=>x.Value).OfType<string>().ToList();
Use "Select" to select a particular column
I have seen a lot of people over complicating this using the didSelectRowAtPath
method. I am using Core Data in my example.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
// This solution is for using Core Data
YourCDEntityName * value = (YourCDEntityName *)[[self fetchedResultsController] objectAtIndexPath: indexPath];
YourSecondViewController * details = [self.storyboard instantiateViewControllerWithIdentifier:@"nameOfYourSecondVC"]; // Make sure in storyboards you give your second VC an identifier
// Make sure you declare your value in the second view controller
details.selectedValue = value;
// Now that you have said to pass value all you need to do is change views
[self.navigationController pushViewController: details animated:YES];
}
Four lines of code inside the method and you are done.
struct.pack('B' * len(integers), *integers)
*sequence
means "unpack sequence" - or rather, "when calling f(..., *args ,...)
, let args = sequence
".
I have used bootstrap. My html code looks like ..
<div class="container mt-3" style="width: 100%;">
<div class="row">
<div class="col-sm-12 wrap-text">
<h6>
text content
</h6>
</div>
</div>
</div>
CSS
.wrap-text {
text-align:justify;
}
The shortest way is by adding the ObsoleteAttribute
as an attribute to the method. Make sure to include an appropriate explanation:
[Obsolete("Method1 is deprecated, please use Method2 instead.")]
public void Method1()
{ … }
You can also cause the compilation to fail, treating the usage of the method as an error instead of warning, if the method is called from somewhere in code like this:
[Obsolete("Method1 is deprecated, please use Method2 instead.", true)]
We can achieve multiple view on single RecyclerView from below way :-
Dependencies on Gradle so add below code:-
compile 'com.android.support:cardview-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'
RecyclerView in XML
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Activity Code
private RecyclerView mRecyclerView;
private CustomAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private String[] mDataset = {“Data - one ”, “Data - two”,
“Showing data three”, “Showing data four”};
private int mDatasetTypes[] = {DataOne, DataTwo, DataThree}; //view types
...
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRecyclerView.setLayoutManager(mLayoutManager);
//Adapter is created in the last step
mAdapter = new CustomAdapter(mDataset, mDataSetTypes);
mRecyclerView.setAdapter(mAdapter);
First XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:elevation="@dimen/hundered”
card_view:cardBackgroundColor=“@color/black“>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding=“@dimen/ten">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=“Fisrt”
android:textColor=“@color/white“ />
<TextView
android:id="@+id/temp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:textColor="@color/white"
android:textSize="30sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
Second XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:elevation="100dp"
card_view:cardBackgroundColor="#00bcd4">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/ten">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=“DataTwo”
android:textColor="@color/white" />
<TextView
android:id="@+id/score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:textColor="#ffffff"
android:textSize="30sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
Third XML
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:elevation="100dp"
card_view:cardBackgroundColor="@color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/ten">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=“DataThree” />
<TextView
android:id="@+id/headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:textSize="25sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/ten"
android:id="@+id/read_more"
android:background="@color/white"
android:text=“Show More” />
</LinearLayout>
</android.support.v7.widget.CardView>
Now time to make adapter and this is main for showing different -2 view on same recycler view so please check this code focus fully :-
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private static final String TAG = "CustomAdapter";
private String[] mDataSet;
private int[] mDataSetTypes;
public static final int dataOne = 0;
public static final int dataTwo = 1;
public static final int dataThree = 2;
public static class ViewHolder extends RecyclerView.ViewHolder {
public ViewHolder(View v) {
super(v);
}
}
public class DataOne extends ViewHolder {
TextView temp;
public DataOne(View v) {
super(v);
this.temp = (TextView) v.findViewById(R.id.temp);
}
}
public class DataTwo extends ViewHolder {
TextView score;
public DataTwo(View v) {
super(v);
this.score = (TextView) v.findViewById(R.id.score);
}
}
public class DataThree extends ViewHolder {
TextView headline;
Button read_more;
public DataThree(View v) {
super(v);
this.headline = (TextView) v.findViewById(R.id.headline);
this.read_more = (Button) v.findViewById(R.id.read_more);
}
}
public CustomAdapter(String[] dataSet, int[] dataSetTypes) {
mDataSet = dataSet;
mDataSetTypes = dataSetTypes;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v;
if (viewType == dataOne) {
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.weather_card, viewGroup, false);
return new DataOne(v);
} else if (viewType == dataTwo) {
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.news_card, viewGroup, false);
return new DataThree(v);
} else {
v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.score_card, viewGroup, false);
return new DataTwo(v);
}
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
if (viewHolder.getItemViewType() == dataOne) {
DataOne holder = (DataOne) viewHolder;
holder.temp.setText(mDataSet[position]);
}
else if (viewHolder.getItemViewType() == dataTwo) {
DataThree holder = (DataTwo) viewHolder;
holder.headline.setText(mDataSet[position]);
}
else {
DataTwo holder = (DataTwo) viewHolder;
holder.score.setText(mDataSet[position]);
}
}
@Override
public int getItemCount() {
return mDataSet.length;
}
@Override
public int getItemViewType(int position) {
return mDataSetTypes[position];
}
}
You can check also this link for more information.
You cannot use Set Transaction Isolation Level Read Uncommitted in a View (you can only have one script in there in fact), so you would have to use (nolock) if dirty rows should be included.
I am trying to set a JPanel's background using an image, however, every example I find seems to suggest extending the panel with its own class
yes you will have to extend JPanel
and override the paintcomponent(Graphics g)
function to do so.
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bgImage, 0, 0, null);
}
I have been looking for a way to simply add the image without creating a whole new class and within the same method (trying to keep things organized and simple).
You can use other component which allows to add image as icon directly e.g. JLabel
if you want.
ImageIcon icon = new ImageIcon(imgURL);
JLabel thumb = new JLabel();
thumb.setIcon(icon);
But again in the bracket trying to keep things organized and simple !! what makes you to think that just creating a new class will lead you to a messy world ?
I use this command:
netstat -tulpn | grep LISTEN
You can have a clean output that shows process id and ports that's listening on
For future searchers, if none of the above worked, for me, python was trying to open a folder as a file.
Here's a lazy one-liner, also using itertools:
from itertools import compress, product
def combinations(items):
return ( set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)) )
# alternative: ...in product([0,1], repeat=len(items)) )
Main idea behind this answer: there are 2^N combinations -- same as the number of binary strings of length N. For each binary string, you pick all elements corresponding to a "1".
items=abc * mask=###
|
V
000 ->
001 -> c
010 -> b
011 -> bc
100 -> a
101 -> a c
110 -> ab
111 -> abc
Things to consider:
len(...)
on items
(workaround: if items
is something like an iterable like a generator, turn it into a list first with items=list(_itemsArg)
)items
is not random (workaround: don't be insane){2,2,1}
and {2,1,1}
will both collapse to {2,1}
(workaround: use collections.Counter
as a drop-in replacement for set
; it's basically a multiset... though you may need to later use tuple(sorted(Counter(...).elements()))
if you need it to be hashable)Demo
>>> list(combinations(range(4)))
[set(), {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}, {0}, {0, 3}, {0, 2}, {0, 2, 3}, {0, 1}, {0, 1, 3}, {0, 1, 2}, {0, 1, 2, 3}]
>>> list(combinations('abcd'))
[set(), {'d'}, {'c'}, {'c', 'd'}, {'b'}, {'b', 'd'}, {'c', 'b'}, {'c', 'b', 'd'}, {'a'}, {'a', 'd'}, {'a', 'c'}, {'a', 'c', 'd'}, {'a', 'b'}, {'a', 'b', 'd'}, {'a', 'c', 'b'}, {'a', 'c', 'b', 'd'}]
You may also check in /opt
mount in following path /opt/PostgresPlus/9.5AS/bin/
I tried in online compiler https://www.onlinegdb.com/online_c++_compiler
int main()
{
cout<<"Hello World";
int x = 10;
int *p = &x;
printf("\nAddress of x is %p\n", &x); // 0x7ffc7df0ea54
printf("Address of p is %p\n", p); // 0x7ffc7df0ea54
return 0;
}
If you have to change an old commit message over multiple branches (i.e., the commit with the erroneous message is present in multiple branches) you might want to use:
git filter-branch -f --msg-filter \
'sed "s/<old message>/<new message>/g"' -- --all
Git will create a temporary directory for rewriting and additionally backup old references in refs/original/
.
-f
will enforce the execution of the operation. This is necessary if the temporary directory is already present or if there are already references stored under refs/original
. If that is not the case, you can drop this flag.
--
separates filter-branch options from revision options.
--all
will make sure that all branches and tags are rewritten.
Due to the backup of your old references, you can easily go back to the state before executing the command.
Say, you want to recover your master and access it in branch old_master
:
git checkout -b old_master refs/original/refs/heads/master
The Java way to do what you want is to use the ServiceLoader mechanism.
Also many people roll their own by having a file in a well known classpath location (i.e. /META-INF/services/myplugin.properties) and then using ClassLoader.getResources() to enumerate all files with this name from all jars. This allows each jar to export its own providers and you can instantiate them by reflection using Class.forName()
These are the options currently documented in the tests: ctrl, shift, enter and escape. These are some valid examples of key bindings:
keydown.control.shift.enter
keydown.control.esc
You can track this here while no official docs exist, but they should be out soon.
var obj = [
{"name": "Afghanistan", "code": "AF"},
{"name": "Åland Islands", "code": "AX"},
{"name": "Albania", "code": "AL"},
{"name": "Algeria", "code": "DZ"}
];
// the code you're looking for
var needle = 'AL';
// iterate over each element in the array
for (var i = 0; i < obj.length; i++){
// look for the entry with a matching `code` value
if (obj[i].code == needle){
// we found it
// obj[i].name is the matched result
}
}
Both if (one.length() > 0) {}
and if (!"".equals(one)) {}
will check against an empty foo parameter, and an empty parameter is what you'd get if the the form is submitted with no value in the foo
text field.
If there's any chance you can use the Expression Language to handle the parameter, you could
access it with empty param.foo
in an expression.
<c:if test='${not empty param.foo}'>
This page code gets rendered.
</c:if>
I believe that your problem is due to the fact that you are defining the variable v inside the test. As explained by @rmalchow, it will work you change it into
int v;
if((v = someMethod()) != 0) return true;
There is also another issue of variable scope. Even if what you tried were to work, what would be the point? Assuming you could define the variable scope inside the test, your variable v would not exist outside that scope. Hence, creating the variable and assigning the value would be pointless, for you would not be able to use it.
Variables exist only in the scope they were created. Since you are assigning the value to use it afterwards, consider the scope where you are creating the varible so that it may be used where needed.
import datetime
now = datetime.datetime.now()
print(now.year)
The above code works perfectly fine for me.
we can use data.table library
library(data.table)
expr <- data.table(expr)
expr[cell_type == "hesc"]
expr[cell_type %in% c("hesc","fibroblast")]
or filter using %like%
operator for pattern matching
expr[cell_type %like% "hesc"|cell_type %like% "fibroblast"]
I have used this in SQL to set IDENTITY to a particular value:-
DECLARE @ID int = 42;
DECLARE @TABLENAME varchar(50) = 'tablename'
DECLARE @SQL nvarchar(1000) = 'IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = '''+@TABLENAME+''' AND last_value IS NOT NULL)
BEGIN
DBCC CHECKIDENT('+@TABLENAME+', RESEED,' + CONVERT(VARCHAR(10),@ID-1)+');
END
ELSE
BEGIN
DBCC CHECKIDENT('+@TABLENAME+', RESEED,' + CONVERT(VARCHAR(10),@ID)+');
END';
EXEC (@SQL);
And this in C# to set a particular value:-
SetIdentity(context, "tablename", 42);
.
.
private static void SetIdentity(DbContext context, string table,int id)
{
string str = "IF EXISTS (SELECT * FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = '" + table
+ "' AND last_value IS NOT NULL)\nBEGIN\n";
str += "DBCC CHECKIDENT('" + table + "', RESEED," + (id - 1).ToString() + ");\n";
str += "END\nELSE\nBEGIN\n";
str += "DBCC CHECKIDENT('" + table + "', RESEED," + (id).ToString() + ");\n";
str += "END\n";
context.Database.ExecuteSqlCommand(str);
}
This builds on the above answers and always makes sure the next value is 42 (in this case).
There is also the DateTime
object if you want to go that way: http://www.php.net/manual/en/datetime.construct.php
I'm surprised no-one has posted this "neat trick" version which doesn't use any JavaScript, it only uses CSS.
#radio1 {
display: none;
}
#wrapper {
/* NOTE: This wrapper div is not needed provided you can position the label for #radio1 on top of #radio2 using some other technique. */
position: relative;
}
#radio1:not(:checked) ~ * label[for="radio1"] {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
#radio1:checked ~ * label[for="radio1"] {
display: none;
}
/* Non-essential styles: */
label[for],
label:not([for="radio1"]) {
cursor: pointer;
border-radius: 7px;
}
label[for]:hover + label,
label:not([for="radio1"]):hover {
background-color: #ccc;
}
_x000D_
<input type="radio" name="group1" id="radio1" checked="checked" />
<p>Look mum, <strong>no JavaScript!</strong></p>
<div id="wrapper">
<label for="radio1"></label>
<label>
<input type="radio" name="group1" id="radio2" />
You can toggle me on and off!
</label>
</div>
_x000D_
#radio1
(<input type="radio" id="radio2" />
) is always hidden.:checked
and :not(:checked)
pseudo-class selectors with sibling selectors (+
and ~
) allow other elements' style to be affected depending on whether or not an <input type="checkbox" />
or <input type="radio" />
is checked.
#radio1
is un-checked (or when #radio2
is checked) that causes a <label>
to be overlayed on-top of #radio2
and that label has for="radio1"
, so clicking it will cause #radio1
to be checked, not #radio2
.:has()
selector function is supported but as of November 2020 only PrinceXML supports :has()
and it's currently looking like :has()
will be dropped from CSS4 entirely owing to the difficulty of implementation.This approach can be scaled to support multiple radio buttons:
#uncheckAll {
display: none;
}
#uncheckAll:checked ~ * label[for="uncheckAll"] {
display: none;
}
label {
cursor: pointer;
}
label:not([for]) {
position: relative;
}
label[for="uncheckAll"] {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
input[name="group1"]:not(:checked) + label[for="uncheckAll"] {
display: none;
}
_x000D_
<input type="radio" name="group1" id="uncheckAll" checked="checked" />
<label>
<input type="radio" name="group1" id="radio2" />
<label for="uncheckAll"></label>
You can toggle me on and off!
</label>
<label>
<input type="radio" name="group1" id="radio3" />
<label for="uncheckAll"></label>
And me!
</label>
<label>
<input type="radio" name="group1" id="aragorn" />
<label for="uncheckAll"></label>
And my sword!
</label>
<label>
<input type="radio" name="group1" id="gimli" />
<label for="uncheckAll"></label>
And my axe!
</label>
_x000D_
open C:\myfile.txt for append as #1
write #1, text1.text, text2.text
close()
This is the code I use in Visual Basic 6.0. It helps me to create a txt file on my drive, write two pieces of data into it, and then close the file... Give it a try...
PowerShell has built-in XML and XPath functions. You can use the Select-Xml cmdlet with an XPath query to select nodes from XML object and then .Node.'#text' to access node value.
[xml]$xml = Get-Content $serviceStatePath
$nodes = Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml
$nodes | ForEach-Object {$_.Node.'#text'}
Or shorter
[xml]$xml = Get-Content $serviceStatePath
Select-Xml "//Object[Property/@Name='ServiceState' and Property='Running']/Property[@Name='DisplayName']" $xml |
% {$_.Node.'#text'}
Complete answer:
1. Is there a function available in SQL?
Yes, the SQL 92 spec, Oct 97, pg. 171, section 6.16 specifies this functions:
CURRENT_TIME Time of day at moment of evaluation
CURRENT_DATE Date at moment of evaluation
CURRENT_TIMESTAMP Date & Time at moment of evaluation
2. It is implementation depended so each database has its own function for this?
Each database has its own implementations, but they have to implement the three function above if they comply with the SQL 92 specification (but depends on the version of the spec)
3. What is the function available in MySQL?
NOW() returns 2009-08-05 15:13:00
CURDATE() returns 2009-08-05
CURTIME() returns 15:13:00
Make sure that your self-signed certificate matches your site URL. If it does not, you will continue to get a certificate error even after explicitly trusting the certificate in Internet Explorer 8 (I don't have Internet Explorer 7, but Firefox will trust the certificate regardless of a URL mismatch).
If this is the problem, the red "Certificate Error" box in Internet Explorer 8 will show "Mismatched Address" as the error after you add your certificate. Also, "View Certificates" has an Issued to: label which shows what URL the certificate is valid against.
A very unusual scenario, which happened to me.
There was infinite recursion, which kept creating the objects.
More specifically, using DRF, I was overriding create method in a view, and I did
def create(self, request, *args, **kwargs):
....
....
return self.create(request, *args, **kwargs)
Inspired in this answer I came up with a bit more object-oriented solution.
This is only valid if you're intending to read characters
You can override BufferedReader and implement something like this:
public class SafeBufferedReader extends BufferedReader{
private long millisTimeout;
( . . . )
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return 0;
}
return super.read(cbuf, off, len);
}
protected void waitReady() throws IllegalThreadStateException, IOException {
if(ready()) return;
long timeout = System.currentTimeMillis() + millisTimeout;
while(System.currentTimeMillis() < timeout) {
if(ready()) return;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break; // Should restore flag
}
}
if(ready()) return; // Just in case.
throw new IllegalThreadStateException("Read timed out");
}
}
Here's an almost complete example.
I'm returning 0 on some methods, you should change it to -2 to meet your needs, but I think that 0 is more suitable with BufferedReader contract. Nothing wrong happened, it just read 0 chars. readLine method is a horrible performance killer. You should create a entirely new BufferedReader if you actually want to use readLine. Right now, it is not thread safe. If someone invokes an operation while readLines is waiting for a line, it will produce unexpected results
I don't like returning -2 where I am. I'd throw an exception because some people may just be checking if int < 0 to consider EOS. Anyway, those methods claim that "can't block", you should check if that statement is actually true and just don't override'em.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
/**
*
* readLine
*
* @author Dario
*
*/
public class SafeBufferedReader extends BufferedReader{
private long millisTimeout;
private long millisInterval = 100;
private int lookAheadLine;
public SafeBufferedReader(Reader in, int sz, long millisTimeout) {
super(in, sz);
this.millisTimeout = millisTimeout;
}
public SafeBufferedReader(Reader in, long millisTimeout) {
super(in);
this.millisTimeout = millisTimeout;
}
/**
* This is probably going to kill readLine performance. You should study BufferedReader and completly override the method.
*
* It should mark the position, then perform its normal operation in a nonblocking way, and if it reaches the timeout then reset position and throw IllegalThreadStateException
*
*/
@Override
public String readLine() throws IOException {
try {
waitReadyLine();
} catch(IllegalThreadStateException e) {
//return null; //Null usually means EOS here, so we can't.
throw e;
}
return super.readLine();
}
@Override
public int read() throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return -2; // I'd throw a runtime here, as some people may just be checking if int < 0 to consider EOS
}
return super.read();
}
@Override
public int read(char[] cbuf) throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return -2; // I'd throw a runtime here, as some people may just be checking if int < 0 to consider EOS
}
return super.read(cbuf);
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return 0;
}
return super.read(cbuf, off, len);
}
@Override
public int read(CharBuffer target) throws IOException {
try {
waitReady();
} catch(IllegalThreadStateException e) {
return 0;
}
return super.read(target);
}
@Override
public void mark(int readAheadLimit) throws IOException {
super.mark(readAheadLimit);
}
@Override
public Stream<String> lines() {
return super.lines();
}
@Override
public void reset() throws IOException {
super.reset();
}
@Override
public long skip(long n) throws IOException {
return super.skip(n);
}
public long getMillisTimeout() {
return millisTimeout;
}
public void setMillisTimeout(long millisTimeout) {
this.millisTimeout = millisTimeout;
}
public void setTimeout(long timeout, TimeUnit unit) {
this.millisTimeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
}
public long getMillisInterval() {
return millisInterval;
}
public void setMillisInterval(long millisInterval) {
this.millisInterval = millisInterval;
}
public void setInterval(long time, TimeUnit unit) {
this.millisInterval = TimeUnit.MILLISECONDS.convert(time, unit);
}
/**
* This is actually forcing us to read the buffer twice in order to determine a line is actually ready.
*
* @throws IllegalThreadStateException
* @throws IOException
*/
protected void waitReadyLine() throws IllegalThreadStateException, IOException {
long timeout = System.currentTimeMillis() + millisTimeout;
waitReady();
super.mark(lookAheadLine);
try {
while(System.currentTimeMillis() < timeout) {
while(ready()) {
int charInt = super.read();
if(charInt==-1) return; // EOS reached
char character = (char) charInt;
if(character == '\n' || character == '\r' ) return;
}
try {
Thread.sleep(millisInterval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore flag
break;
}
}
} finally {
super.reset();
}
throw new IllegalThreadStateException("readLine timed out");
}
protected void waitReady() throws IllegalThreadStateException, IOException {
if(ready()) return;
long timeout = System.currentTimeMillis() + millisTimeout;
while(System.currentTimeMillis() < timeout) {
if(ready()) return;
try {
Thread.sleep(millisInterval);
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Restore flag
break;
}
}
if(ready()) return; // Just in case.
throw new IllegalThreadStateException("read timed out");
}
}
While using mysql version 8.0 + , use the following syntax to update root password after starting mysql daemon with --skip-grant-tables option
UPDATE user SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your_new_password')
You can add the functions to the standard library and use it whenever you need.
Here is the code in C++
#include <stdio.h>
int power(int x, int y) //calculates x^y.
{
int product = 1;
for (int i = 0; i < y; i++)
{
product = product * x;
}
return (product);
}
int gpow_bin(int a) //highest power of 2 less/equal to than number itself.
{
int i, z, t;
for (i = 0;; i++)
{
t = power(2, i);
z = a / t;
if (z == 0)
{
break;
}
}
return (i - 1);
}
void bin_write(int x)
{
//printf("%d", 1);
int current_power = gpow_bin(x);
int left = x - power(2, current_power);
int lower_power = gpow_bin(left);
for (int i = 1; i < current_power - lower_power; i++)
{
printf("0");
}
if (left != 0)
{
printf("%d", 1);
bin_write(left);
}
}
void main()
{
//printf("%d", gpow_bin(67));
int user_input;
printf("Give the input:: ");
scanf("%d", &user_input);
printf("%d", 1);
bin_write(user_input);
}
You are missing the event parameter on your function.
$(document).on("click",".appDetails", function (event) {
alert(event.target.id);
});
I am using jquery for this. I mad a function to set desired height to the modal(You can change that according to your requirement).
Then I used Modal Shown event to call this function.
Remember not to use $("#modal").show()
rather use $("#modal").modal('show')
otherwise shown.bs.modal will not be fired.
That all I have for this scenario.
var offset=250; //You can set offset accordingly based on your UI_x000D_
function AdjustPopup() _x000D_
{_x000D_
$(".modal-body").css("height","auto");_x000D_
if ($(".modal-body:visible").height() > ($(window).height() - offset)) _x000D_
{_x000D_
$(".modal-body:visible").css("height", ($(window).height() - offset));_x000D_
}_x000D_
}_x000D_
//Execute the function on every trigger on show() event._x000D_
$(document).ready(function(){_x000D_
$('.modal').on('shown.bs.modal', function (e) {_x000D_
AdjustPopup();_x000D_
});_x000D_
});_x000D_
//Remember to show modal like this_x000D_
$("#MyModal").modal('show');
_x000D_
for what DB is the user? look at this example
mysql> create database databasename;
Query OK, 1 row affected (0.00 sec)
mysql> grant all on databasename.* to cmsuser@localhost identified by 'password';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
so to return to you question the "%" operator means all computers in your network.
like aspesa shows I'm also sure that you have to create or update a user. look for all your mysql users:
SELECT user,password,host FROM user;
as soon as you got your user set up you should be able to connect like this:
mysql -h localhost -u gmeier -p
hope it helps
A working method in android to populates the mapping list mime types.
private static void fileMimeTypeMapping() {
MIMETYPE_MAPPING.put("3gp", Collections.list("video/3gpp"));
MIMETYPE_MAPPING.put("7z", Collections.list("application/x-7z-compressed"));
MIMETYPE_MAPPING.put("accdb", Collections.list("application/msaccess"));
MIMETYPE_MAPPING.put("ai", Collections.list("application/illustrator"));
MIMETYPE_MAPPING.put("apk", Collections.list("application/vnd.android.package-archive"));
MIMETYPE_MAPPING.put("arw", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("avi", Collections.list("video/x-msvideo"));
MIMETYPE_MAPPING.put("bash", Collections.list("text/x-shellscript"));
MIMETYPE_MAPPING.put("bat", Collections.list("application/x-msdos-program"));
MIMETYPE_MAPPING.put("blend", Collections.list("application/x-blender"));
MIMETYPE_MAPPING.put("bin", Collections.list("application/x-bin"));
MIMETYPE_MAPPING.put("bmp", Collections.list("image/bmp"));
MIMETYPE_MAPPING.put("bpg", Collections.list("image/bpg"));
MIMETYPE_MAPPING.put("bz2", Collections.list("application/x-bzip2"));
MIMETYPE_MAPPING.put("cb7", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cba", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cbr", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cbt", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cbtc", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cbz", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("cc", Collections.list("text/x-c"));
MIMETYPE_MAPPING.put("cdr", Collections.list("application/coreldraw"));
MIMETYPE_MAPPING.put("class", Collections.list("application/java"));
MIMETYPE_MAPPING.put("cnf", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("conf", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("cpp", Collections.list("text/x-c++src"));
MIMETYPE_MAPPING.put("cr2", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("css", Collections.list("text/css"));
MIMETYPE_MAPPING.put("csv", Collections.list("text/csv"));
MIMETYPE_MAPPING.put("cvbdl", Collections.list("application/x-cbr"));
MIMETYPE_MAPPING.put("c", Collections.list("text/x-c"));
MIMETYPE_MAPPING.put("c++", Collections.list("text/x-c++src"));
MIMETYPE_MAPPING.put("dcr", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("deb", Collections.list("application/x-deb"));
MIMETYPE_MAPPING.put("dng", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("doc", Collections.list("application/msword"));
MIMETYPE_MAPPING.put("docm", Collections.list("application/vnd.ms-word.document.macroEnabled.12"));
MIMETYPE_MAPPING.put("docx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
MIMETYPE_MAPPING.put("dot", Collections.list("application/msword"));
MIMETYPE_MAPPING.put("dotx", Collections.list("application/vnd.openxmlformats-officedocument.wordprocessingml.template"));
MIMETYPE_MAPPING.put("dv", Collections.list("video/dv"));
MIMETYPE_MAPPING.put("eot", Collections.list("application/vnd.ms-fontobject"));
MIMETYPE_MAPPING.put("epub", Collections.list("application/epub+zip"));
MIMETYPE_MAPPING.put("eps", Collections.list("application/postscript"));
MIMETYPE_MAPPING.put("erf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("exe", Collections.list("application/x-ms-dos-executable"));
MIMETYPE_MAPPING.put("flac", Collections.list("audio/flac"));
MIMETYPE_MAPPING.put("flv", Collections.list("video/x-flv"));
MIMETYPE_MAPPING.put("gif", Collections.list("image/gif"));
MIMETYPE_MAPPING.put("gpx", Collections.list("application/gpx+xml"));
MIMETYPE_MAPPING.put("gz", Collections.list("application/gzip"));
MIMETYPE_MAPPING.put("gzip", Collections.list("application/gzip"));
MIMETYPE_MAPPING.put("h", Collections.list("text/x-h"));
MIMETYPE_MAPPING.put("heic", Collections.list("image/heic"));
MIMETYPE_MAPPING.put("heif", Collections.list("image/heif"));
MIMETYPE_MAPPING.put("hh", Collections.list("text/x-h"));
MIMETYPE_MAPPING.put("hpp", Collections.list("text/x-h"));
MIMETYPE_MAPPING.put("htaccess", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("ical", Collections.list("text/calendar"));
MIMETYPE_MAPPING.put("ics", Collections.list("text/calendar"));
MIMETYPE_MAPPING.put("iiq", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("impress", Collections.list("text/impress"));
MIMETYPE_MAPPING.put("java", Collections.list("text/x-java-source"));
MIMETYPE_MAPPING.put("jp2", Collections.list("image/jp2"));
MIMETYPE_MAPPING.put("jpeg", Collections.list("image/jpeg"));
MIMETYPE_MAPPING.put("jpg", Collections.list("image/jpeg"));
MIMETYPE_MAPPING.put("jps", Collections.list("image/jpeg"));
MIMETYPE_MAPPING.put("k25", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("kdc", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("key", Collections.list("application/x-iwork-keynote-sffkey"));
MIMETYPE_MAPPING.put("keynote", Collections.list("application/x-iwork-keynote-sffkey"));
MIMETYPE_MAPPING.put("kml", Collections.list("application/vnd.google-earth.kml+xml"));
MIMETYPE_MAPPING.put("kmz", Collections.list("application/vnd.google-earth.kmz"));
MIMETYPE_MAPPING.put("kra", Collections.list("application/x-krita"));
MIMETYPE_MAPPING.put("ldif", Collections.list("text/x-ldif"));
MIMETYPE_MAPPING.put("love", Collections.list("application/x-love-game"));
MIMETYPE_MAPPING.put("lwp", Collections.list("application/vnd.lotus-wordpro"));
MIMETYPE_MAPPING.put("m2t", Collections.list("video/mp2t"));
MIMETYPE_MAPPING.put("m3u", Collections.list("audio/mpegurl"));
MIMETYPE_MAPPING.put("m3u8", Collections.list("audio/mpegurl"));
MIMETYPE_MAPPING.put("m4a", Collections.list("audio/mp4"));
MIMETYPE_MAPPING.put("m4b", Collections.list("audio/m4b"));
MIMETYPE_MAPPING.put("m4v", Collections.list("video/mp4"));
MIMETYPE_MAPPING.put("markdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("mdown", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("md", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("mdb", Collections.list("application/msaccess"));
MIMETYPE_MAPPING.put("mdwn", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("mkd", Collections.list(MIMETYPE_TEXT_MARKDOWN));
MIMETYPE_MAPPING.put("mef", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("mkv", Collections.list("video/x-matroska"));
MIMETYPE_MAPPING.put("mobi", Collections.list("application/x-mobipocket-ebook"));
MIMETYPE_MAPPING.put("mov", Collections.list("video/quicktime"));
MIMETYPE_MAPPING.put("mp3", Collections.list("audio/mpeg"));
MIMETYPE_MAPPING.put("mp4", Collections.list("video/mp4"));
MIMETYPE_MAPPING.put("mpeg", Collections.list("video/mpeg"));
MIMETYPE_MAPPING.put("mpg", Collections.list("video/mpeg"));
MIMETYPE_MAPPING.put("mpo", Collections.list("image/jpeg"));
MIMETYPE_MAPPING.put("msi", Collections.list("application/x-msi"));
MIMETYPE_MAPPING.put("mts", Collections.list("video/MP2T"));
MIMETYPE_MAPPING.put("mt2s", Collections.list("video/MP2T"));
MIMETYPE_MAPPING.put("nef", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("numbers", Collections.list("application/x-iwork-numbers-sffnumbers"));
MIMETYPE_MAPPING.put("odf", Collections.list("application/vnd.oasis.opendocument.formula"));
MIMETYPE_MAPPING.put("odg", Collections.list("application/vnd.oasis.opendocument.graphics"));
MIMETYPE_MAPPING.put("odp", Collections.list("application/vnd.oasis.opendocument.presentation"));
MIMETYPE_MAPPING.put("ods", Collections.list("application/vnd.oasis.opendocument.spreadsheet"));
MIMETYPE_MAPPING.put("odt", Collections.list("application/vnd.oasis.opendocument.text"));
MIMETYPE_MAPPING.put("oga", Collections.list("audio/ogg"));
MIMETYPE_MAPPING.put("ogg", Collections.list("audio/ogg"));
MIMETYPE_MAPPING.put("ogv", Collections.list("video/ogg"));
MIMETYPE_MAPPING.put("one", Collections.list("application/msonenote"));
MIMETYPE_MAPPING.put("opus", Collections.list("audio/ogg"));
MIMETYPE_MAPPING.put("orf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("otf", Collections.list("application/font-sfnt"));
MIMETYPE_MAPPING.put("pages", Collections.list("application/x-iwork-pages-sffpages"));
MIMETYPE_MAPPING.put("pdf", Collections.list("application/pdf"));
MIMETYPE_MAPPING.put("pfb", Collections.list("application/x-font"));
MIMETYPE_MAPPING.put("pef", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("php", Collections.list("application/x-php"));
MIMETYPE_MAPPING.put("pl", Collections.list("application/x-perl"));
MIMETYPE_MAPPING.put("pls", Collections.list("audio/x-scpls"));
MIMETYPE_MAPPING.put("png", Collections.list("image/png"));
MIMETYPE_MAPPING.put("pot", Collections.list("application/vnd.ms-powerpoint"));
MIMETYPE_MAPPING.put("potm", Collections.list("application/vnd.ms-powerpoint.template.macroEnabled.12"));
MIMETYPE_MAPPING.put("potx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.template"));
MIMETYPE_MAPPING.put("ppa", Collections.list("application/vnd.ms-powerpoint"));
MIMETYPE_MAPPING.put("ppam", Collections.list("application/vnd.ms-powerpoint.addin.macroEnabled.12"));
MIMETYPE_MAPPING.put("pps", Collections.list("application/vnd.ms-powerpoint"));
MIMETYPE_MAPPING.put("ppsm", Collections.list("application/vnd.ms-powerpoint.slideshow.macroEnabled.12"));
MIMETYPE_MAPPING.put("ppsx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.slideshow"));
MIMETYPE_MAPPING.put("ppt", Collections.list("application/vnd.ms-powerpoint"));
MIMETYPE_MAPPING.put("pptm", Collections.list("application/vnd.ms-powerpoint.presentation.macroEnabled.12"));
MIMETYPE_MAPPING.put("pptx", Collections.list("application/vnd.openxmlformats-officedocument.presentationml.presentation"));
MIMETYPE_MAPPING.put("ps", Collections.list("application/postscript"));
MIMETYPE_MAPPING.put("psd", Collections.list("application/x-photoshop"));
MIMETYPE_MAPPING.put("py", Collections.list("text/x-python"));
MIMETYPE_MAPPING.put("raf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("rar", Collections.list("application/x-rar-compressed"));
MIMETYPE_MAPPING.put("reveal", Collections.list("text/reveal"));
MIMETYPE_MAPPING.put("rss", Collections.list("application/rss+xml"));
MIMETYPE_MAPPING.put("rtf", Collections.list("application/rtf"));
MIMETYPE_MAPPING.put("rw2", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("schema", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("sgf", Collections.list("application/sgf"));
MIMETYPE_MAPPING.put("sh-lib", Collections.list("text/x-shellscript"));
MIMETYPE_MAPPING.put("sh", Collections.list("text/x-shellscript"));
MIMETYPE_MAPPING.put("srf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("sr2", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("tar", Collections.list("application/x-tar"));
MIMETYPE_MAPPING.put("tar.bz2", Collections.list("application/x-bzip2"));
MIMETYPE_MAPPING.put("tar.gz", Collections.list("application/x-compressed"));
MIMETYPE_MAPPING.put("tbz2", Collections.list("application/x-bzip2"));
MIMETYPE_MAPPING.put("tcx", Collections.list("application/vnd.garmin.tcx+xml"));
MIMETYPE_MAPPING.put("tex", Collections.list("application/x-tex"));
MIMETYPE_MAPPING.put("tgz", Collections.list("application/x-compressed"));
MIMETYPE_MAPPING.put("tiff", Collections.list("image/tiff"));
MIMETYPE_MAPPING.put("tif", Collections.list("image/tiff"));
MIMETYPE_MAPPING.put("ttf", Collections.list("application/font-sfnt"));
MIMETYPE_MAPPING.put("txt", Collections.list("text/plain"));
MIMETYPE_MAPPING.put("vcard", Collections.list("text/vcard"));
MIMETYPE_MAPPING.put("vcf", Collections.list("text/vcard"));
MIMETYPE_MAPPING.put("vob", Collections.list("video/dvd"));
MIMETYPE_MAPPING.put("vsd", Collections.list("application/vnd.visio"));
MIMETYPE_MAPPING.put("vsdm", Collections.list("application/vnd.ms-visio.drawing.macroEnabled.12"));
MIMETYPE_MAPPING.put("vsdx", Collections.list("application/vnd.ms-visio.drawing"));
MIMETYPE_MAPPING.put("vssm", Collections.list("application/vnd.ms-visio.stencil.macroEnabled.12"));
MIMETYPE_MAPPING.put("vssx", Collections.list("application/vnd.ms-visio.stencil"));
MIMETYPE_MAPPING.put("vstm", Collections.list("application/vnd.ms-visio.template.macroEnabled.12"));
MIMETYPE_MAPPING.put("vstx", Collections.list("application/vnd.ms-visio.template"));
MIMETYPE_MAPPING.put("wav", Collections.list("audio/wav"));
MIMETYPE_MAPPING.put("webm", Collections.list("video/webm"));
MIMETYPE_MAPPING.put("woff", Collections.list("application/font-woff"));
MIMETYPE_MAPPING.put("wpd", Collections.list("application/vnd.wordperfect"));
MIMETYPE_MAPPING.put("wmv", Collections.list("video/x-ms-wmv"));
MIMETYPE_MAPPING.put("xcf", Collections.list("application/x-gimp"));
MIMETYPE_MAPPING.put("xla", Collections.list("application/vnd.ms-excel"));
MIMETYPE_MAPPING.put("xlam", Collections.list("application/vnd.ms-excel.addin.macroEnabled.12"));
MIMETYPE_MAPPING.put("xls", Collections.list("application/vnd.ms-excel"));
MIMETYPE_MAPPING.put("xlsb", Collections.list("application/vnd.ms-excel.sheet.binary.macroEnabled.12"));
MIMETYPE_MAPPING.put("xlsm", Collections.list("application/vnd.ms-excel.sheet.macroEnabled.12"));
MIMETYPE_MAPPING.put("xlsx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
MIMETYPE_MAPPING.put("xlt", Collections.list("application/vnd.ms-excel"));
MIMETYPE_MAPPING.put("xltm", Collections.list("application/vnd.ms-excel.template.macroEnabled.12"));
MIMETYPE_MAPPING.put("xltx", Collections.list("application/vnd.openxmlformats-officedocument.spreadsheetml.template"));
MIMETYPE_MAPPING.put("xrf", Collections.list("image/x-dcraw"));
MIMETYPE_MAPPING.put("yaml", Arrays.asList("application/yaml", "text/plain"));
MIMETYPE_MAPPING.put("yml", Arrays.asList("application/yaml", "text/plain"));
MIMETYPE_MAPPING.put("zip", Collections.list("application/zip"));
MIMETYPE_MAPPING.put("url", Collections.list("application/internet-shortcut"));
MIMETYPE_MAPPING.put("webloc", Collections.list("application/internet-shortcut"));
MIMETYPE_MAPPING.put("js", Arrays.asList("application/javascript", "text/plain"));
MIMETYPE_MAPPING.put("json", Arrays.asList("application/json", "text/plain"));
MIMETYPE_MAPPING.put("fb2", Arrays.asList("application/x-fictionbook+xml", "text/plain"));
MIMETYPE_MAPPING.put("html", Arrays.asList("text/html", "text/plain"));
MIMETYPE_MAPPING.put("htm", Arrays.asList("text/html", "text/plain"));
MIMETYPE_MAPPING.put("m", Arrays.asList("text/x-matlab", "text/plain"));
MIMETYPE_MAPPING.put("svg", Arrays.asList("image/svg+xml", "text/plain"));
MIMETYPE_MAPPING.put("swf", Arrays.asList("application/x-shockwave-flash", "application/octet-stream"));
MIMETYPE_MAPPING.put("xml", Arrays.asList("application/xml", "text/plain"));
}
int mid = 10;
for (double j = 2 * mid; j >= 0; j = j - 0.1) {
if (j == mid) {
System.out.println("Never happens"); // is NOT printed
}
if (Double.compare(j, mid) == 0) {
System.out.println("No way!"); // is NOT printed
}
if (Math.abs(j - mid) < 1e-6) {
System.out.println("Ha!"); // printed
}
}
System.out.println("Gotcha!");
Spent way too much time coming back to this page so just gonna leave this here:
File file = new ClassPathResource("data/data.json").getFile();
Directly from the w3schools website:
var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
To combine their example with a regular expression, you could do the following:
function checkUserName() {
var username = document.getElementsByName("username").value;
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(username)) {
alert("Please only use standard alphanumerics");
return false;
}
return true; //good user input
}
To stop Jenkins Please avoid shutting down the Java process or the Windows service. These are not usual commands. Use those only if your Jenkins is causing problems.
Use Jenkins' way to stop that protects from data loss.
http://[jenkins-server]/[command]
where [command] can be any one of the following
Example: if my local PC is running Jenkins at port 8080, it will be
http://localhost:8080/exit
Install ncftpput and ncftpget. They're usually part of the same package.
My main purpose was to get ICONs for TortoiseCVS. Many of the suggestions did not work for me: uninstall reinstall; regedit by renaming; rebooting multiple times. But what did work was to install TortoiseSVN. This made the icons for TortoiseCVS work. I checked out regedit. The SVN install put numbers in front of the icon names:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\ShellIconOverlayIdentifiers] 1TortoiseNormal 2TortoiseModified 3TortoiseConflict 4TortoiseLocked 5TortoiseReadOnly 6TortoiseDeleted 7TortoiseAdded 8TortoiseIgnored 9TortoiseUnversioned Groove Explorer Icon Overlay 1 (GFS Unread Stub) Groove Explorer Icon Overlay 2 (GFS Stub) Groove Explorer Icon Overlay 2.5 (GFS Unread Folder) Groove Explorer Icon Overlay 3 (GFS Folder) Groove Explorer Icon Overlay 4 (GFS Unread Mark) SharingPrivate TortoiseAdded TortoiseConflict TortoiseDeleted TortoiseIgnored TortoiseLocked TortoiseModified TortoiseNormal TortoiseReadOnly TortoiseUnversioned zEnhancedStorageShell zOffline Files zSkyDrivePro1 (ErrorConflict) zSkyDrivePro2 (SyncInProgress) zSkyDrivePro3 (InSync)
#/bin/bash
#pgm to monitor
tail -f /var/log/messages >> /tmp/log&
# background cmd pid
pid=$!
# loop to monitor running background cmd
while :
do
ps ax | grep $pid | grep -v grep
ret=$?
if test "$ret" != "0"
then
echo "Monitored pid ended"
break
fi
sleep 5
done
wait $pid
echo $?
Is something like this what you're looking for?
def write_vars_to_file(f, **vars):
for name, val in vars.items():
f.write("%s = %s\n" % (name, repr(val)))
Usage:
>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}
If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet
constructor:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
Fix it by adding the context as the constructor arg:
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);
ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher",
new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
Dialects are removed in recent SQL so use
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL57Dialect"/>
<td rowspan="2" style="text-align:left;vertical-align:top;padding:0">Save a lot</td>
That should do it.
Generally speaking, for boolean
or bit
data types, you would use 0
or 1
like so:
UPDATE tbl SET bitCol = 1 WHERE bitCol = 0
See also:
You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)
Once the user have choose a image you can read the file-path of the chosen image and place it into your html.
Example:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Javascript:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
Amit-
I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:
CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;
Drop the table you want to add columns to:
DROP TABLE TABLE_TO_CHANGE;
It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".
Now insert the data back into the new table:
INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4)
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;
When the data is inserted into your "new-old" table, you can drop the temp table.
DROP TABLE MY_TEMP_TABLE;
This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.
-CJ