other.component.ts
So final correct solution is :
import { Component, OnInit } from '@angular/core';
import { Location } from '@angular/common';
import { Router } from '@angular/router';
/* 'router' it must be in small case */
@Component({
selector: 'app-other',
templateUrl: './other.component.html',
styleUrls: ['./other.component.css']
})
export class OtherComponent implements OnInit {
public href: string = "";
url: string = "asdf";
constructor(private router : Router) {} // make variable private so that it would be accessible through out the component
ngOnInit() {
this.href = this.router.url;
console.log(this.router.url);
}
}
If you are like me, and starring at your angular/ionic typescript, which looks like..
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, {
headers: new HttpHeaders(
{
'Access-Control-Allow-Origin': 'https://localhost:5100',
'Access-Control-Allow-Methods': 'POST',
'Content-Type': 'application/pdf',
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
And while you are setting options but can't seem to figure why they aren't anywhere..
Well.. if you were like me and started this post
from a copy/paste of a get
, then...
Change to:
getPdf(endpoint: string): Observable<Blob> {
let url = this.url + '/' + endpoint;
let token = this.msal.accessToken;
console.log(token);
return this.http.post<Blob>(url, null, { // <----- notice the null *****
headers: new HttpHeaders(
{
'Authorization': 'Bearer ' + token,
'Accept': '*/*',
}),
//responseType: ResponseContentType.Blob,
});
}
You have 3 options to make your way:
1. Define a date value like '1970-01-01'
2. Select NULL from the dropdown to keep it blank.
3. Select CURRENT_TIMESTAMP to set current datetime as default value.
run - Create a container using image and Start the same. (Create & Start)
start - Start the container(s) in docker list which was in stopped state.
To declare a variable as a Decimal
, first declare it as a Variant
and then convert to Decimal
with CDec
. The type would be Variant/Decimal
in the watch window:
Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.
In the example below, we see that the expression:
0.1 + 0.11 = 0.21
is either True
or False
, depending on whether the collectibles (0.1,0.11) are declared as Double
or as Decimal
:
Public Sub TestMe()
Dim preciseA As Variant: preciseA = CDec(0.1)
Dim preciseB As Variant: preciseB = CDec(0.11)
Dim notPreciseA As Double: notPreciseA = 0.1
Dim notPreciseB As Double: notPreciseB = 0.11
Debug.Print preciseA + preciseB
Debug.Print preciseA + preciseB = 0.21 'True
Debug.Print notPreciseA + notPreciseB
Debug.Print notPreciseA + notPreciseB = 0.21 'False
End Sub
For get response in JSON format :
1.$response = (string) $res->getBody();
$response =json_decode($response); // Using this you can access any key like below
$key_value = $response->key_name; //access key
2. $response = json_decode($res->getBody(),true);
$key_value = $response['key_name'];//access key
The purpose of .iteritems()
was to use less memory space by yielding one result at a time while looping. I am not sure why Python 3 version does not support iteritems()
though it's been proved to be efficient than .items()
If you want to include a code that supports both the PY version 2 and 3,
try:
iteritems
except NameError:
iteritems = items
This can help if you deploy your project in some other system and you aren't sure about the PY version.
The accepted answer by Adam (flex: 1 1 0
) works perfectly for flexbox containers whose width is either fixed, or determined by an ancestor. Situations where you want the children to fit the container.
However, you may have a situation where you want the container to fit the children, with the children equally sized based on the largest child. You can make a flexbox container fit its children by either:
position: absolute
and not setting width
or right
, ordisplay: inline-block
For such flexbox containers, the accepted answer does NOT work, the children are not sized equally. I presume that this is a limitation of flexbox, since it behaves the same in Chrome, Firefox and Safari.
The solution is to use a grid instead of a flexbox.
Demo: https://codepen.io/brettdonald/pen/oRpORG
<p>Normal scenario — flexbox where the children adjust to fit the container — and the children are made equal size by setting {flex: 1 1 0}</p>
<div id="div0">
<div>
Flexbox
</div>
<div>
Width determined by viewport
</div>
<div>
All child elements are equal size with {flex: 1 1 0}
</div>
</div>
<p>Now we want to have the container fit the children, but still have the children all equally sized, based on the largest child. We can see that {flex: 1 1 0} has no effect.</p>
<div class="wrap-inline-block">
<div id="div1">
<div>
Flexbox
</div>
<div>
Inside inline-block
</div>
<div>
We want all children to be the size of this text
</div>
</div>
</div>
<div id="div2">
<div>
Flexbox
</div>
<div>
Absolutely positioned
</div>
<div>
We want all children to be the size of this text
</div>
</div>
<br><br><br><br><br><br>
<p>So let's try a grid instead. Aha! That's what we want!</p>
<div class="wrap-inline-block">
<div id="div3">
<div>
Grid
</div>
<div>
Inside inline-block
</div>
<div>
We want all children to be the size of this text
</div>
</div>
</div>
<div id="div4">
<div>
Grid
</div>
<div>
Absolutely positioned
</div>
<div>
We want all children to be the size of this text
</div>
</div>
body {
margin: 1em;
}
.wrap-inline-block {
display: inline-block;
}
#div0, #div1, #div2, #div3, #div4 {
border: 1px solid #888;
padding: 0.5em;
text-align: center;
white-space: nowrap;
}
#div2, #div4 {
position: absolute;
left: 1em;
}
#div0>*, #div1>*, #div2>*, #div3>*, #div4>* {
margin: 0.5em;
color: white;
background-color: navy;
padding: 0.5em;
}
#div0, #div1, #div2 {
display: flex;
}
#div0>*, #div1>*, #div2>* {
flex: 1 1 0;
}
#div0 {
margin-bottom: 1em;
}
#div2 {
top: 15.5em;
}
#div3, #div4 {
display: grid;
grid-template-columns: repeat(3,1fr);
}
#div4 {
top: 28.5em;
}
You can solve that using display table.
Here is the updated JSFiddle that solves your problem.
CSS
.body {
display: table;
background-color: green;
}
.left-side {
background-color: blue;
float: none;
display: table-cell;
border: 1px solid;
}
.right-side {
background-color: red;
float: none;
display: table-cell;
border: 1px solid;
}
HTML
<div class="row body">
<div class="col-xs-9 left-side">
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
<p>sdfsdf</p>
</div>
<div class="col-xs-3 right-side">
asdfdf
</div>
</div>
def match_string(words):
nums = 0
letter = 0
other = 0
for i in words :
if i.isalpha():
letter+=1
elif i.isdigit():
nums+=1
else:
other+=1
return nums,letter,other
x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>
i had this problem. i created a picture for my background with jpg format. before added this picture, i changed the format to png with rename the format. and then i got this error like you. i changed my format picture with picture editor like photoshop to png and replaced it with picture in my project and then i hadnt that error. sory for bad english
The password that you use to login to github.com portal does not work in VS Code CLI/Shell. You should copy PAT Token from URL https://github.com/settings/tokens by generating new token and paste that string in CLI as password.
I found this solution by Sebastian Ekström. It's quick, dirty, and works really well. Even if you don't know the parent's height:
.element {
position: relative;
top: 50%;
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
Read the full article here.
Try following css with addition of white-space
:
span {
display: block;
word-wrap:break-word;
width: 50px;
white-space: normal
}
If your files have inconsistent use of spaces and tabs, you may find it helpful to include the -t
argument to expand the tabs:
diff -ty file1 file2
string str1, str2, str3;
cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;
From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:
string str1 = "the dog jumped over the fence",
str2 = "the",
str3 = "that";
cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;
<div style="height: 100px;"> </div>
OR
<div id="foo"/> and set the style as #foo { height: 100px; }
<div class="bar"/> and set the style as .bar{ height: 100px; }
There's now an official solution to this problem. Autosizing TextViews introduced with Android O are available in the Support Library 26 and is backwards compatible all the way down to Android 4.0.
https://developer.android.com/preview/features/autosizing-textview.html
I'm not sure why https://stackoverflow.com/a/42940171/47680 which also included this information was deleted by an admin.
xargs -a your_file | sed 's/ /,/g'
This is a shorter way.
I just found this when googling to solve the same problem, and had to make a minor change to the solution to make it work in my situation, as I had 2 similar substrings, "Sun" and "Sunstruck" to search for. The offered solution was locating the wrong entry when searching for "Sun". Data in column B
I added another column C, formulaes C1=" "&B1&" " and changed the search to =COUNTIF(B1:B10,"* "&A1&" *")>0, the extra column to allow finding the first of last entry in the concatenated string.
public static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=dbName";
public static final String USERNAME = "xxxx";
public static final String PASSWORD = "xxxx";
/**
* This method
@param args command line argument
*/
public static void main(String[] args)
{
try
{
Connection connection;
DriverManager.registerDriver(new com.microsoft.sqlserver.jdbc.SQLServerDriver());
connection = DriverManager.getConnection(MainDriver.URL,MainDriver.USERNAME,
MainDriver.PASSWORD);
String query ="select * from employee";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next())
{
System.out.print("First Name: " + resultSet.getString("first_name"));
System.out.println(" Last Name: " + resultSet.getString("last_name"));
}
}catch(Exception ex)
{
ex.printStackTrace();
}
}
use this for horizontal divider
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="@color/honeycombish_blue" />
and this for vertical divider
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/honeycombish_blue" />
OR if you can use the LinearLayout divider, for horizontal divider
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<size android:height="1dp"/>
<solid android:color="#f6f6f6"/>
</shape>
and in LinearLayout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@drawable/divider"
android:orientation="vertical"
android:showDividers="middle" >
If you want to user vertical divider then in place of android:height="1dp"
in shape use android:width="1dp"
Tip: Don't forget the android:showDividers
item.
Just add layout_weight="1" to in your linearLayout which having Buttons.
Edit :- let me make it simple
follow something like below, tags name may not be correct, it is just an Idea
<LL>// Top Parrent LinearLayout
<LL1 height="fill_parent" weight="1" "other tags as requirement"> <TV /><Butons /></LL1> // this layout will fill your screen.
<LL2 height="wrap_content" weight="1" orientation="Horizontal" "other tags as requirement"> <BT1 /><BT2/ ></LL2> // this layout gonna take lower part of button height of your screen
<LL/> TOP PARENT CLOSED
You CAN use UTF-8 in the POST request, all you need is to specify the charset in your request.
You should use this request:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded; charset=utf-8" --data-ascii "content=derinhält&date=asdf" http://myserverurl.com/api/v1/somemethod
Instead of writing
<hr>
Write
<hr class="col-xs-12">
And it will display full width as normal.
I've had a few cranberry-vodkas tonight so I might be missing something...Is setting the range necessary? Why not use:
Activeworkbook.Sheets("Game").Range("A1").value = "Subtotal"
Does this fail as well?
Looks like you tried something similar:
'Worksheets("Game").Range("A1") = "Asdf"
However, Worksheets is a collection, so you can't reference "Game". I think you need to use the Sheets object instead.
You can use alias to improve the query:
UPDATE t1
SET t1.Value = t2.Value
FROM table1 AS t1
INNER JOIN
table2 AS t2
ON t1.ID = t2.ID
Try:
$('body').on({
hover: function() {
console.log("yeahhhh!!! but this doesn't work for me :(");
},
click: function() {
console.log("yeahhhh!!! but this doesn't work for me :(");
}
},'#my-button');
When using .on() and binding to a dynamic element, you need to refer to an element that already exists on the page (like body in the example). If you can use a more specific element that would improve performance.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.
This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.
I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.
public class Class1
{
private void btn_click(object sender, EventArgs e)
{
ServerRequest sr = new ServerRequest();
sr.Callback += new ServerRequest.CallbackEventHandler(sr_Callback);
sr.DoRequest("myrequest");
}
void sr_Callback(string something)
{
}
}
public class ServerRequest
{
public delegate void CallbackEventHandler(string something);
public event CallbackEventHandler Callback;
public void DoRequest(string request)
{
// do stuff....
if (Callback != null)
Callback("bla");
}
}
use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.
I know this post is really old but, to get the contents of an element in reference to its ID, this is what I would do:
window.onclick = e => {
console.log(e.target);
console.log(e.target.id, ' -->', e.target.innerHTML);
}
Sub Button1_Click()
Dim cn As Object
Dim rs As Object
Dim strSql As String
Dim strConnection As String
Set cn = CreateObject("ADODB.Connection")
strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
strSql = "SELECT Count(*) FROM mytable;"
cn.Open strConnection
Set rs = cn.Execute(strSql)
MsgBox rs.Fields(0) & " rows in MyTable"
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
I dont think youre returning json object from server. just a string.
you need the dataType of the return object to be json
Not quite, although generally you can usually use some workaround on one of the forms
[^abc]
, which is character by character not a
or b
or c
, a(?!b)
, which is a
not followed by b
(?<!a)b
, which is b
not preceeded by a
You are using an inline table value function. Therefore you must use Select * From function. If you want to use select function() you must use a scalar function.
https://msdn.microsoft.com/fr-fr/library/ms186755%28v=sql.120%29.aspx
Try mylist[0][0]
. This should return the first character.
This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.
There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.
This might be a better answer copied from this question. Please try it and give opinion here. Please vote up if found useful. Thank you.
<script type="text/javascript">
function generate_excel(tableid) {
var table= document.getElementById(tableid);
var html = table.outerHTML;
window.open('data:application/vnd.ms-excel;base64,' + base64_encode(html));
}
function base64_encode (data) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafal Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['btoa'] == 'function') {
// return btoa(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
}
</script>
For @return
tag use {{field1: Number, field2: String}}
, see: http://wiki.servoy.com/display/public/DOCS/Annotating+JavaScript+using+JSDoc
As @fijaaron says,
GRANT ALL
does not imply GRANT FILE
GRANT FILE
only works with *.*
So do
GRANT FILE ON *.* TO user;
An alternative to Martin's
select LEFT(name, CHARINDEX(' ', name + ' ') -1),
STUFF(name, 1, Len(Name) +1- CHARINDEX(' ',Reverse(name)), '')
from somenames
Sample table
create table somenames (Name varchar(100))
insert somenames select 'abcd efgh'
insert somenames select 'ijk lmn opq'
insert somenames select 'asd j. asdjja'
insert somenames select 'asb (asdfas) asd'
insert somenames select 'asd'
insert somenames select ''
insert somenames select null
Short answer:
As written in xsd:
<xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/>
<xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/>
If you provide an attribute with number, then the number is boundary. Otherwise attribute should appear exactly once.
I recommend looking at the dataset array.
The dataset array is a data type that ships with Statistics Toolbox. It is specifically designed to store hetrogeneous data in a single container.
The Statistics Toolbox demo page contains a couple vidoes that show some of the dataset array features. The first is titled "An Introduction to Dataset Arrays". The second is titled "An Introduction to Joins".
public View recentView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create a relative layout and add a button
relativeLayout = new RelativeLayout(this);
btn = new Button(this);
btn.setId((int)System.currentTimeMillis());
recentView = btn;
btn.setText("Click me");
relativeLayout.addView(btn);
setContentView(relativeLayout);
btn.setOnClickListener(new View.OnClickListener() {
@Overr ide
public void onClick(View view) {
//Create a textView, set a random ID and position it below the most recently added view
textView = new TextView(ActivityName.this);
textView.setId((int)System.currentTimeMillis());
layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.BELOW, recentView.getId());
textView.setText("Time: "+System.currentTimeMillis());
relativeLayout.addView(textView, layoutParams);
recentView = textView;
}
});
}
This can be modified to display each element of a String array in different TextViews.
for you to achieve that, you not only need to know how recursion works but you also need to understand the String method. here is a sample code that I used to achieve it: -
class PalindromeRecursive {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter a string");
String input=sc.next();
System.out.println("is "+ input + "a palindrome : " + isPalindrome(input));
}
public static boolean isPalindrome(String s)
{
int low=0;
int high=s.length()-1;
while(low<high)
{
if(s.charAt(low)!=s.charAt(high))
return false;
isPalindrome(s.substring(low++,high--));
}
return true;
}
}
Yattag http://www.yattag.org/ or https://github.com/leforestier/yattag provides an interesting API to create such XML document (and also HTML documents).
It's using context manager and with
keyword.
from yattag import Doc, indent
doc, tag, text = Doc().tagtext()
with tag('root'):
with tag('doc'):
with tag('field1', name='blah'):
text('some value1')
with tag('field2', name='asdfasd'):
text('some value2')
result = indent(
doc.getvalue(),
indentation = ' '*4,
newline = '\r\n'
)
print(result)
so you will get:
<root>
<doc>
<field1 name="blah">some value1</field1>
<field2 name="asdfasd">some value2</field2>
</doc>
</root>
Further from Nikolaus Gradwohl answer, I needed to get version number (i.e., 0.0.2) between('ui:' and '-') from below file content (filename: docker-compose.yml):
version: '3.1'
services:
ui:
image: repo-pkg.dev.io:21/website/ui:0.0.2-QA1
#network_mode: host
ports:
- 443:9999
ulimits:
nofile:test
and this is how it worked for me (python script):
import re, sys
f = open('docker-compose.yml', 'r')
lines = f.read()
result = re.search('ui:(.*)-', lines)
print result.group(1)
Result:
0.0.2
I assume with the second line you actually mean:
Thing *thing = new Thing("uiae");
which would be the standard way of creating new dynamic objects (necessary for dynamic binding and polymorphism) and storing their address to a pointer. Your code does what JaredPar described, namely creating two objects (one passed a const char*
, the other passed a const Thing&
), and then calling the destructor (~Thing()
) on the first object (the const char*
one).
By contrast, this:
Thing thing("uiae");
creates a static object which is destroyed automatically upon exiting the current scope.
You might want to try this example for version 2.6 of Python.
def my_print(text, begin, end):
"Print text in UPPER between 'begin' and 'end' in lower."
for obj in (text, begin, end):
assert isinstance(obj, str), 'Argument of wrong type!'
print begin.lower() + text.upper() + end.lower()
However, have you considered letting the function fail naturally instead?
items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
you can also get the line if there are other characters before token
items=re.findall("^.*token.*$",s,re.MULTILINE)
The above works like grep token on unix and keyword 'in' or .contains in python and C#
s='''
qwertyuiop
asdfghjkl
zxcvbnm
token qwerty
asdfghjklñ
'''
http://pythex.org/ matches the following 2 lines
....
....
token qwerty
We can merge two collection by using mongoDB sub query. Here is example, Commentss--
`db.commentss.insert([
{ uid:12345, pid:444, comment:"blah" },
{ uid:12345, pid:888, comment:"asdf" },
{ uid:99999, pid:444, comment:"qwer" }])`
Userss--
db.userss.insert([
{ uid:12345, name:"john" },
{ uid:99999, name:"mia" }])
MongoDB sub query for JOIN--
`db.commentss.find().forEach(
function (newComments) {
newComments.userss = db.userss.find( { "uid": newComments.uid } ).toArray();
db.newCommentUsers.insert(newComments);
}
);`
Get result from newly generated Collection--
db.newCommentUsers.find().pretty()
Result--
`{
"_id" : ObjectId("5511236e29709afa03f226ef"),
"uid" : 12345,
"pid" : 444,
"comment" : "blah",
"userss" : [
{
"_id" : ObjectId("5511238129709afa03f226f2"),
"uid" : 12345,
"name" : "john"
}
]
}
{
"_id" : ObjectId("5511236e29709afa03f226f0"),
"uid" : 12345,
"pid" : 888,
"comment" : "asdf",
"userss" : [
{
"_id" : ObjectId("5511238129709afa03f226f2"),
"uid" : 12345,
"name" : "john"
}
]
}
{
"_id" : ObjectId("5511236e29709afa03f226f1"),
"uid" : 99999,
"pid" : 444,
"comment" : "qwer",
"userss" : [
{
"_id" : ObjectId("5511238129709afa03f226f3"),
"uid" : 99999,
"name" : "mia"
}
]
}`
Hope so this will help.
In C shell - The ampersand is after the greater-than symbol
make >& filename
Performance-wise, I found the ServiceStack's serializer a bit faster than then others. It's JsonSerializer class in ServiceStack.Text namespace.
https://github.com/ServiceStack/ServiceStack.Text
ServiceStack is available through NuGet package: https://www.nuget.org/packages/ServiceStack/
anon, run: ./prog
looks a bit strange, as right part should be a target, so run: prog
looks better.
I would suggest simply:
.PHONY: run
run:
prog $(arg1)
and I would like to add, that arguments can be passed:
make arg1="asdf" run
arg1="asdf" make run
Try this:
MessageBox.Show("Some text", "Some title",
MessageBoxButtons.OK, MessageBoxIcon.Error);
Sometimes you have to do something funky. Let's say you want to read from a command (the date example by SDGuero for example) but you want to avoid multiple forks.
read month day year << DATE_COMMAND
$(date "+%m %d %Y")
DATE_COMMAND
echo $month $day $year
You could also pipe into the read command, but then you'd have to use the variables within a subshell:
day=n/a; month=n/a; year=n/a
date "+%d %m %Y" | { read day month year ; echo $day $month $year; }
echo $day $month $year
results in...
13 08 2013
n/a n/a n/a
Use This [Tested]
To get numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 1; // will return Numeric values
To get non-numeric
SELECT column1
FROM table
WHERE Isnumeric(column1) = 0; // will return non-numeric values
The answer of delfuego is the simplest way to solve the certificate problem. But, in my case, one of our third party url (using https), updated their certificate every 2 months automatically. It means that I have to import the cert to our Java trust store manually every 2 months as well. Sometimes it caused production problems.
So, I made a method to solve it with SecureRestClientTrustManager to be able to consume https url without importing the cert file. Here is the method:
public static String doPostSecureWithHeader(String url, String body, Map headers) throws Exception { log.info("start doPostSecureWithHeader " + url + " with param " + body); long startTime; long endTime; startTime = System.currentTimeMillis(); Client client; client = Client.create(); WebResource webResource; webResource = null; String output = null; try{ SSLContext sslContext = null; SecureRestClientTrustManager secureRestClientTrustManager = new SecureRestClientTrustManager(); sslContext = SSLContext.getInstance("SSL"); sslContext .init(null, new javax.net.ssl.TrustManager[] { secureRestClientTrustManager }, null); DefaultClientConfig defaultClientConfig = new DefaultClientConfig(); defaultClientConfig .getProperties() .put(com.sun.jersey.client.urlconnection.HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new com.sun.jersey.client.urlconnection.HTTPSProperties( getHostnameVerifier(), sslContext)); client = Client.create(defaultClientConfig); webResource = client.resource(url); if(headers!=null && headers.size()>0){ for (Map.Entry entry : headers.entrySet()){ webResource.setProperty(entry.getKey(), entry.getValue()); } } WebResource.Builder builder = webResource.accept("application/json"); if(headers!=null && headers.size()>0){ for (Map.Entry entry : headers.entrySet()){ builder.header(entry.getKey(), entry.getValue()); } } ClientResponse response = builder .post(ClientResponse.class, body); output = response.getEntity(String.class); } catch(Exception e){ log.error(e.getMessage(),e); if(e.toString().contains("One or more of query value parameters are null")){ output="-1"; } if(e.toString().contains("401 Unauthorized")){ throw e; } } finally { if (client!= null) { client.destroy(); } } endTime = System.currentTimeMillis(); log.info("time hit "+ url +" selama "+ (endTime - startTime) + " milliseconds dengan output = "+output); return output; }
I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)
I pulled this from the example code in your link:
IF !%1==! GOTO VIEWDATA
REM IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM PRINT LINE WITH STRING MATCH, THEN EXIT.
:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM SHOW ENTIRE FILE, 1 PAGE AT A TIME.
:EXIT0
!%1==!
is simply an idiomatic use of ==
intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The !
in this case is just a character placeholder. It could be anything. If %1
has content, then the equality will be false, if it does not you'll just be comparing !
to !
and it will be true.
!==!
is not an operator, so writing "asdf" !==! "fdas"
is pretty nonsensical.
The suggestion to use if not "asdf" == "fdas"
is definitely the way to go.
There is another hack I use and never saw in any StackOverflow response : using "src" attribute of an image will yield the complete base path of your site. For instance :
var dummy = new Image;
dummy.src = '$'; // using '' will fail on some browsers
var root = dummy.src.slice(0,-1); // remove trailing '$'
On an URL like http://domain.com/somesite/index.html
,
root
will be set to http://domain.com/somesite/
.
This also works for localhost or any valid base URL.
Note that this will cause a failed HTTP request on the $
dummy image.
You can use an existing image instead to avoid this, with only slight code changes.
Another variant uses a dummy link, with no side effect on HTTP requests :
var dummy = document.createElement ('a');
dummy.href = '';
var root = dummy.href;
I did not test it on every browser, though.
this is variation of Dennis method, looks more elegant in the scripts.
function definition:
define(){ IFS='\n' read -r -d '' ${1} || true; }
usage:
define VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF
echo "$VAR"
enjoy
p.s. made a 'read loop' version for shells that do not support read -d
. should work with set -eu
and unpaired backticks, but not tested very well:
define(){ o=; while IFS="\n" read -r a; do o="$o$a"'
'; done; eval "$1=\$o"; }
Here's some sample code for that.
<script>
var param1var = getQueryVariable("param1");
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
</script>
First, find the hash you want to your submodule to reference. then run
~/supery/subby $ git co hashpointerhere
~/supery/subby $ cd ../
~/supery $ git add subby
~/supery $ git commit -m 'updated subby reference'
that has worked for me to get my submodule to the correct hash reference and continue on with my work without getting any further conflicts.
If that <p>
tag is created from JavaScript, then you do have another option: use JSS to programmatically insert stylesheets into the document head. It does support '&:hover'
. https://cssinjs.org/
Flexbox can do this with just two css rules on a surrounding div.
.social-media{_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
}
_x000D_
<div class="social-media">_x000D_
<a href="mailto:[email protected]">_x000D_
<img class="fblogo" border="0" alt="Mail" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
<a href="https://www.facebook.com/OlympiaHaacht" target="_blank">_x000D_
<img class="fblogo" border="0" alt="Facebook" src="http://olympiahaacht.be/wp-content/uploads/2012/04/FacebookButtonRevised-e1334605872360.jpg"/></a>_x000D_
</div>
_x000D_
The right answer is:
android {
....
....
sourceSets {
main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
}
}
Furthermore, if your external source directory is not under src/main
, you could use a relative path like this:
sourceSets {
main.java.srcDirs += 'src/main/../../../<YOUR DIRECTORY>'
}
just make it function,
<script type="text/javascript">
function AlertIt() {
var answer = confirm ("Please click on OK to continue.")
if (answer)
window.location="http://www.continue.com";
}
</script>
<a href="javascript:AlertIt();">click me</a>
Use yepnope.js or Modernizr (which includes yepnope.js as Modernizr.load
).
UPDATE
Just to follow up, here's a good equivalent of what you currently have using yepnope, showing dependencies on multiple scripts:
yepnope({
load: ['script1.js', 'script2.js', 'script3.js'],
complete: function () {
// all the scripts have loaded, do whatever you want here
}
});
Checkout TickTick.
It's a true Bash JSON parser.
#!/bin/bash
. /path/to/ticktick.sh
# File
DATA=`cat data.json`
# cURL
#DATA=`curl http://foobar3000.com/echo/request.json`
tickParse "$DATA"
echo ``pathname``
echo ``headers["user-agent"]``
MarvinS.-
Try:
$.ajax({
url: uri+'?js',
success: function(data) {
var imgAttr = $("img", data).attr('src');
var htmlCode = $(data).html();
$('#imgSrc').html(imgAttr);
$('#fullHtmlOutput').html(htmlCode);
}
});
This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.
You can't decode a unicode
, and you can't encode a str
. Try doing it the other way around.
You can do this by reading from the boolean property at:
System.Web.Security.Roles.Enabled
This is a direct read from the enabled
attribute of the roleManager
element in the web.config
:
<configuration>
<system.web>
<roleManager enabled="true" />
</system.web>
</configuration>
Update:
For more information, check out this MSDN sample: https://msdn.microsoft.com/en-us/library/aa354509(v=vs.110).aspx
The typical way to achieve this is to export to CSV and then load the CSV into Excel.
You can using any MySQL command line tool to do this by including the INTO OUTFILE
clause on your SELECT
statement:
SELECT ... FROM ... WHERE ...
INTO OUTFILE 'file.csv'
FIELDS TERMINATED BY ','
See this link for detailed options.
Alternatively, you can use mysqldump to store dump into a separated value format using the --tab option, see this link.
mysqldump -u<user> -p<password> -h<host> --where=jtaskResult=2429 --tab=<file.csv> <database> TaskResult
Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv'
or INTO OUTFILE './output.csv'
, it will store the output file to the directory specified by show variables like 'datadir';
.
I don't believe the expression is sensical as it is.
Elvis means "if truthy, use the value, else use this other thing."
Your "other thing" is a closure, and the value is status != null
, neither of which would seem to be what you want. If status
is null, Elvis says true
. If it's not, you get an extra layer of closure.
Why can't you just use:
(it.description == desc) && ((status == null) || (it.status == status))
Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find
calls, just use an intermediate variable.
Attention!
while (calendar.get(Calendar.DAY_OF_WEEK) > calendar.getFirstDayOfWeek()) {
calendar.add(Calendar.DATE, -1); // Substract 1 day until first day of week.
}
is good idea, but there is some issue: For example, i'm from Ukraine and calendar.getFirstDayOfWeek() in my country is 2 (Monday). And today is 1 (Sunday). In this case calendar.add not called.
So, correct way is change ">" to "!=":
while (calendar.get(Calendar.DAY_OF_WEEK) != calendar.getFirstDayOfWeek()) {...
In order to create modular style sheets that are not dependent on the absolute location of a resource, authors may use relative URIs. Relative URIs (as defined in [RFC3986]) are resolved to full URIs using a base URI. RFC 3986, section 5, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document.
For example, suppose the following rule:
body { background: url("yellow") }
is located in a style sheet designated by the URI:
http://www.example.org/style/basic.css
The background of the source document's BODY will be tiled with whatever image is described by the resource designated by the URI
http://www.example.org/style/yellow
User agents may vary in how they handle invalid URIs or URIs that designate unavailable or inapplicable resources.
Taken from the CSS 2.1 spec.
From php docs:
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error.
The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data.
As far as i know it wouldn't be possible to change the spark.executor.memory
at run time. If you are running a stand-alone version, with pyspark and graphframes, you can launch the pyspark REPL
by executing the following command:
pyspark --driver-memory 2g --executor-memory 6g --packages graphframes:graphframes:0.7.0-spark2.4-s_2.11
Be sure to change the SPARK_VERSION
environment variable appropriately regarding the latest released version of Spark
Instead of using the referrer, you can implement window.postMessage
to communicate accross iframes/windows across domains.
You post to window.parent, and then parent returns the URL.
This works, but it requires asynchronous communication.
You will have to write a synchronous wrapper around the asynchronous methods, if you need it synchronous.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
// What browsers support the window.postMessage call now?
// IE8 does not allow postMessage across windows/tabs
// FF3+, IE8+, Chrome, Safari(5?), Opera10+
function SendMessage()
{
var win = document.getElementById("ifrmChild").contentWindow;
// http://robertnyman.com/2010/03/18/postmessage-in-html5-to-send-messages-between-windows-and-iframes/
// http://stackoverflow.com/questions/16072902/dom-exception-12-for-window-postmessage
// Specify origin. Should be a domain or a wildcard "*"
if (win == null || !window['postMessage'])
alert("oh crap");
else
win.postMessage("hello", "*");
//alert("lol");
}
function ReceiveMessage(evt) {
var message;
//if (evt.origin !== "http://robertnyman.com")
if (false) {
message = 'You ("' + evt.origin + '") are not worthy';
}
else {
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
var ta = document.getElementById("taRecvMessage");
if (ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
//evt.source.postMessage("thanks, got it ;)", event.origin);
} // End Function ReceiveMessage
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
//alert("standards-compliant");
// For standards-compliant web browsers (ie9+)
window.addEventListener("message", ReceiveMessage, false);
}
else {
//alert("not standards-compliant (ie8)");
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body>
<iframe id="ifrmChild" src="child.htm" frameborder="0" width="500" height="200" ></iframe>
<br />
<input type="button" value="Test" onclick="SendMessage();" />
</body>
</html>
Child.htm
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<!--
<link rel="shortcut icon" href="/favicon.ico">
<link rel="start" href="http://benalman.com/" title="Home">
<link rel="stylesheet" type="text/css" href="/code/php/multi_file.php?m=benalman_css">
<script type="text/javascript" src="/js/mt.js"></script>
-->
<script type="text/javascript">
/*
// Opera 9 supports document.postMessage()
// document is wrong
window.addEventListener("message", function (e) {
//document.getElementById("test").textContent = ;
alert(
e.domain + " said: " + e.data
);
}, false);
*/
// https://developer.mozilla.org/en-US/docs/Web/API/window.postMessage
// http://ejohn.org/blog/cross-window-messaging/
// http://benalman.com/projects/jquery-postmessage-plugin/
// http://benalman.com/code/projects/jquery-postmessage/docs/files/jquery-ba-postmessage-js.html
// .data – A string holding the message passed from the other window.
// .domain (origin?) – The domain name of the window that sent the message.
// .uri – The full URI for the window that sent the message.
// .source – A reference to the window object of the window that sent the message.
function ReceiveMessage(evt) {
var message;
//if (evt.origin !== "http://robertnyman.com")
if(false)
{
message = 'You ("' + evt.origin + '") are not worthy';
}
else
{
message = 'I got "' + evt.data + '" from "' + evt.origin + '"';
}
//alert(evt.source.location.href)
var ta = document.getElementById("taRecvMessage");
if(ta == null)
alert(message);
else
document.getElementById("taRecvMessage").innerHTML = message;
// http://javascript.info/tutorial/cross-window-messaging-with-postmessage
//evt.source.postMessage("thanks, got it", evt.origin);
evt.source.postMessage("thanks, got it", "*");
} // End Function ReceiveMessage
if (!window['postMessage'])
alert("oh crap");
else {
if (window.addEventListener) {
//alert("standards-compliant");
// For standards-compliant web browsers (ie9+)
window.addEventListener("message", ReceiveMessage, false);
}
else {
//alert("not standards-compliant (ie8)");
window.attachEvent("onmessage", ReceiveMessage);
}
}
</script>
</head>
<body style="background-color: gray;">
<h1>Test</h1>
<textarea id="taRecvMessage" rows="20" cols="20" ></textarea>
</body>
</html>
public partial class App : System.Windows.Application
{
public bool IsProcessOpen(string name)
{
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.Contains(name))
{
return true;
}
}
return false;
}
protected override void OnStartup(StartupEventArgs e)
{
// Get Reference to the current Process
Process thisProc = Process.GetCurrentProcess();
if (IsProcessOpen("name of application.exe") == false)
{
//System.Windows.MessageBox.Show("Application not open!");
//System.Windows.Application.Current.Shutdown();
}
else
{
// Check how many total processes have the same name as the current one
if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
{
// If ther is more than one, than it is already running.
System.Windows.MessageBox.Show("Application is already running.");
System.Windows.Application.Current.Shutdown();
return;
}
base.OnStartup(e);
}
}
I'm showing that a combination of lines.pop(0)
l.remove()
and del l
does the trick.
from matplotlib import pyplot
import numpy, weakref
a = numpy.arange(int(1e3))
fig = pyplot.Figure()
ax = fig.add_subplot(1, 1, 1)
lines = ax.plot(a)
l = lines.pop(0)
wl = weakref.ref(l) # create a weak reference to see if references still exist
# to this object
print wl # not dead
l.remove()
print wl # not dead
del l
print wl # dead (remove either of the steps above and this is still live)
I checked your large dataset and the release of the memory is confirmed on the system monitor as well.
Of course the simpler way (when not trouble-shooting) would be to pop it from the list and call remove
on the line object without creating a hard reference to it:
lines.pop(0).remove()
Newer versions: (from 8.4 - mentioned in release notes)
TABLE mytablename;
Longer but works on all versions:
SELECT * FROM mytablename;
You may wish to use \x
first if it's a wide table, for readability.
For long data:
SELECT * FROM mytable LIMIT 10;
or similar.
For wide data (big rows), in the psql
command line client, it's useful to use \x
to show the rows in key/value form instead of tabulated, e.g.
\x
SELECT * FROM mytable LIMIT 10;
Note that in all cases the semicolon at the end is important.
There appears to be a difference function that accepts time intervals to use as well as an option to not round the result. So, something like
Math.floor(moment(new Date()).diff(moment("02/26/1978","MM/DD/YYYY"),'years',true)))
I haven't tried this, and I'm not completely familiar with moment, but it seems like this should get what you want (without having to reset the month).
With the latest update to the extension all you need to do is just specify the "python.pythonPath"
as follows.
The values for "python.autoComplete.extraPaths"
will be determined during runtime, but you are still free to specify custom paths in there.
Please, remember to restart Visual Studio Code once the necessary changes have been made.
{
"editor.rulers": [80,100],
"python.pythonPath":"~/dev/venvs/proj/bin/python"
}
As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below
e.g.
Exec N'Select bla..'
the N defines string literal is unicode.
Using Regular Expressions with JavaScript. A regular expression is a special text string for describing a search pattern, which is written in the form of /pattern/modifiers where "pattern" is the regular expression itself, and "modifiers" are a series of characters indicating various options.
The character class is the most basic regex concept after a literal match. It makes one small sequence of characters match a larger set of characters. For example, [A-Z]
could stand for the upper case alphabet, and \d
could mean any digit.
From below example
contains_alphaNumeric
« It checks for string contains either letter or number (or) both letter and number. The hyphen (-) is ignored.onlyMixOfAlphaNumeric
« It checks for string contain both letters and numbers only of any sequence order.Example:
function matchExpression( str ) {
var rgularExp = {
contains_alphaNumeric : /^(?!-)(?!.*-)[A-Za-z0-9-]+(?<!-)$/,
containsNumber : /\d+/,
containsAlphabet : /[a-zA-Z]/,
onlyLetters : /^[A-Za-z]+$/,
onlyNumbers : /^[0-9]+$/,
onlyMixOfAlphaNumeric : /^([0-9]+[a-zA-Z]+|[a-zA-Z]+[0-9]+)[0-9a-zA-Z]*$/
}
var expMatch = {};
expMatch.containsNumber = rgularExp.containsNumber.test(str);
expMatch.containsAlphabet = rgularExp.containsAlphabet.test(str);
expMatch.alphaNumeric = rgularExp.contains_alphaNumeric.test(str);
expMatch.onlyNumbers = rgularExp.onlyNumbers.test(str);
expMatch.onlyLetters = rgularExp.onlyLetters.test(str);
expMatch.mixOfAlphaNumeric = rgularExp.onlyMixOfAlphaNumeric.test(str);
return expMatch;
}
// HTML Element attribute's[id, name] with dynamic values.
var id1 = "Yash", id2="777", id3= "Yash777", id4= "Yash777Image4"
id11= "image5.64", id22= "55-5.6", id33= "image_Yash", id44= "image-Yash"
id12= "_-.";
console.log( "Only Letters:\n ", matchExpression(id1) );
console.log( "Only Numbers:\n ", matchExpression(id2) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id3) );
console.log( "Only Mix of Letters and Numbers:\n ", matchExpression(id4) );
console.log( "Mixed with Special symbols" );
console.log( "Letters and Numbers :\n ", matchExpression(id11) );
console.log( "Numbers [-]:\n ", matchExpression(id22) );
console.log( "Letters :\n ", matchExpression(id33) );
console.log( "Letters [-]:\n ", matchExpression(id44) );
console.log( "Only Special symbols :\n ", matchExpression(id12) );
Out put:
Only Letters:
{containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: true, mixOfAlphaNumeric: false}
Only Numbers:
{containsNumber: true, containsAlphabet: false, alphaNumeric: true, onlyNumbers: true, onlyLetters: false, mixOfAlphaNumeric: false}
Only Mix of Letters and Numbers:
{containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Only Mix of Letters and Numbers:
{containsNumber: true, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: true}
Mixed with Special symbols
Letters and Numbers :
{containsNumber: true, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Numbers [-]:
{containsNumber: true, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters :
{containsNumber: false, containsAlphabet: true, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Letters [-]:
{containsNumber: false, containsAlphabet: true, alphaNumeric: true, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
Only Special symbols :
{containsNumber: false, containsAlphabet: false, alphaNumeric: false, onlyNumbers: false, onlyLetters: false, mixOfAlphaNumeric: false}
java Pattern Matching with Regular Expressions.
Disable all table constraints
ALTER TABLE TableName NOCHECK CONSTRAINT ConstraintName
-- Enable all table constraints
ALTER TABLE TableName CHECK CONSTRAINT ConstraintName
You can try to delete the JSON as follows:
var bleh = {first: '1', second: '2', third:'3'}
alert(bleh.first);
delete bleh.first;
alert(bleh.first);
Alternatively, you can also pass in the index to delete an attribute:
delete bleh[1];
However, to understand some of the repercussions of using deletes, have a look here
After some tests, here is a general object to array function convertor:
You have the object:
var obj = {
some_key_1: "some_value_1"
some_key_2: "some_value_2"
};
The function:
function ObjectToArray(o)
{
var k = Object.getOwnPropertyNames(o);
var v = Object.values(o);
var c = function(l)
{
this.k = [];
this.v = [];
this.length = l;
};
var r = new c(k.length);
for (var i = 0; i < k.length; i++)
{
r.k[i] = k[i];
r.v[i] = v[i];
}
return r;
}
Function Use:
var arr = ObjectToArray(obj);
You Get:
arr { key: [ "some_key_1", "some_key_2" ], value: [ "some_value_1", "some_value_2" ], length: 2 }
So then you can reach all keys & values like:
for (var i = 0; i < arr.length; i++)
{
console.log(arr.key[i] + " = " + arr.value[i]);
}
Result in console:
some_key_1 = some_value_1 some_key_2 = some_value_2
Edit:
Or in prototype form:
Object.prototype.objectToArray = function()
{
if (
typeof this != 'object' ||
typeof this.length != "undefined"
) {
return false;
}
var k = Object.getOwnPropertyNames(this);
var v = Object.values(this);
var c = function(l)
{
this.k = [];
this.v = [];
this.length = l;
};
var r = new c(k.length);
for (var i = 0; i < k.length; i++)
{
r.k[i] = k[i];
r.v[i] = v[i];
}
return r;
};
And then use like:
console.log(obj.objectToArray);
If you are using Git Gui on windows,
In short
Snagged from Oracle OTN forums
Use alter table to add column, for example:
alter table tableName add(columnName NUMBER);
Then create a sequence:
CREATE SEQUENCE SEQ_ID
START WITH 1
INCREMENT BY 1
MAXVALUE 99999999
MINVALUE 1
NOCYCLE;
and, the use update
to insert values in column like this
UPDATE tableName SET columnName = seq_test_id.NEXTVAL
There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:
MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.
Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (
.
) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs.+
and.-
are unnecessary.
<pre>_x000D_
<form name="myform" action="saveNew" method="post" enctype="multipart/form-data">_x000D_
<input type="text" id="name" name="name" /> _x000D_
<input type="submit"/>_x000D_
</form>_x000D_
</pre>_x000D_
_x000D_
<script language="JavaScript" type="text/javascript">_x000D_
var frmvalidator = new Validator("myform");_x000D_
frmvalidator.EnableFocusOnError(false);_x000D_
frmvalidator.EnableMsgsTogether();_x000D_
frmvalidator.addValidation("name", "req", "Plese Enter Name");_x000D_
</script>
_x000D_
before using above code you have to add the gen_validatorv31.js file
To save a bit time:
1) You can mark your app icon images all in finder and drag them into your Assets catalog all at once by dragging into one of the empty slots of the app icon imageset. When you hold your drag over the slot, several of the other slots look selected and when you drop those all will be filled up at once. Note that this works in XCode 8 (I haven't tried XCode 7), but in XCode 9 beta not yet.
2) The "Technical Q&A QA1686" apple documentation site has the sizes per app icon slot already calculated for you in a nice image and also contains the correct image names conventions.
I have a wrapper project (pyscreenshot) for scrot, imagemagick, pyqt, wx and pygtk. If you have one of them, you can use it. All solutions are included from this discussion.
Install:
easy_install pyscreenshot
Example:
import pyscreenshot as ImageGrab
# fullscreen
im=ImageGrab.grab()
im.show()
# part of the screen
im=ImageGrab.grab(bbox=(10,10,500,500))
im.show()
# to file
ImageGrab.grab_to_file('im.png')
I'm using CSS Dig. It is made for chrome, but I think it is a great tool!
This worked for me:
h1 {
display: inline;
overflow: hidden;
}
div {
position: relative;
float: right;
}
It's similar to the approach of the media object, by Stubbornella.
Edit: As they comment below, you need to place the element that's going to float before the element that's going to wrap (the one in your first fiddle)
You don't need the AND
keyword. Here's the correct syntax of the UPDATE statement:
UPDATE
shop_category
SET
name = 'Secolul XVI - XVIII',
name_eng = '16th to 18th centuries'
WHERE
category_id = 4768
If you're referring to the concept of accessors, then the simple goal is to hide the underlying storage from arbitrary manipulation. The most extreme mechanism for this is
function Foo(someValue) {
this.getValue = function() { return someValue; }
return this;
}
var myFoo = new Foo(5);
/* We can read someValue through getValue(), but there is no mechanism
* to modify it -- hurrah, we have achieved encapsulation!
*/
myFoo.getValue();
If you're referring to the actual JS getter/setter feature, eg. defineGetter
/defineSetter
, or { get Foo() { /* code */ } }
, then it's worth noting that in most modern engines subsequent usage of those properties will be much much slower than it would otherwise be. eg. compare performance of
var a = { getValue: function(){ return 5; }; }
for (var i = 0; i < 100000; i++)
a.getValue();
vs.
var a = { get value(){ return 5; }; }
for (var i = 0; i < 100000; i++)
a.value;
I've used JOpt and found it quite handy: http://jopt-simple.sourceforge.net/
The front page also provides a list of about 8 alternative libraries, check them out and pick the one that most suits your needs.
You can use Integer.parseInt()
or Integer.valueOf()
to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch the NumberFormatException
it can throw.
It may be helpful to note that valueOf() will return an Integer object, not the primitive int.
You can just pass it
def my_function(my_data):
my_data["schoolname"] = "something"
print my_data
or if you really want to
def my_function(**kwargs):
kwargs["schoolname"] = "something"
print kwargs
Prefixing the string with an @ indicates that it should be treated as a literal, i.e. no escaping.
For example if your string contains a path you would typically do this:
string path = "c:\\mypath\\to\\myfile.txt";
The @ allows you to do this:
string path = @"c:\mypath\to\myfile.txt";
Notice the lack of double slashes (escaping)
<div class="example" align="center">
<div class="menuholder">
<ul class="menu slide">
<li><a href="index.php?id=1" class="blue">Home</a></li>
<li><a href="index.php?id=14" class="blue">About Us</a></li>
<li><a href="index.php?id=4" class="blue">Mens</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=15">Coats & Jackets</a></dd>
<dd><a href="index.php?id=22">Chinos</a></dd>
<dd><a href="index.php?id=23">Jeans</a></dd>
<dd><a href="index.php?id=24">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=25">Linen</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=26">Polo Shirts</a></dd>
<dd><a href="index.php?id=16">Shirts Casual</a></dd>
<dd><a href="index.php?id=27">Shirts Formal</a></dd>
<dd><a href="index.php?id=28">Shorts</a></dd>
<dd><a href="index.php?id=18">Sportswear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=19">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=20">Trousers Casual</a></dd>
<dd><a href="index.php?id=29">Trousers Formal</a></dd>
<dd><a href="index.php?id=30">Nightwear</a></dd>
<dd><a href="index.php?id=17">Socks</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=21">Underwear</a></dd>
<dd><a href="index.php?id=31">Swimwear</a></dd>
</dl>
</div>
</li>
<!--menu-->
<li><a href="index.php?id=5" class="blue">Ladie's</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=32">Coats & Jackets</a></dd>
<dd><a href="index.php?id=33">Dresses</a></dd>
<dd><a href="index.php?id=34">Jeans</a></dd>
<dd><a href="index.php?id=35">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=36">Jumpsuits</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=37">Leggings & Jeggings</a></dd>
<dd><a href="index.php?id=38">Linen</a></dd>
<dd><a href="index.php?id=39">Lingerie & Underwear</a></dd>
<dd><a href="index.php?id=40">Maternity Wear</a></dd>
<dd><a href="index.php?id=41">Nightwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=42">Shorts</a></dd>
<dd><a href="index.php?id=43">Skirts</a></dd>
<dd><a href="index.php?id=44">Sportswear</a></dd>
<dd><a href="index.php?id=45">Suits & Tailoring</a></dd>
<dd><a href="index.php?id=46">Swimwear & Beachwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=47">Thermals</a></dd>
<dd><a href="index.php?id=48">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=49">Trousers & Chinos</a></dd>
<dd><a href="index.php?id=50">Socks</a></dd>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=7" class="blue">Girls</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=51">Coats & Jackets</a></dd>
<dd><a href="index.php?id=52">Dresses</a></dd>
<dd><a href="index.php?id=53">Jeans</a></dd>
<dd><a href="index.php?id=54">Joggers & Sweatshirts</a></dd>
<dd><a href="index.php?id=55">Jumpers & Cardigans</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=56">Jumpsuits & Playsuits</a></dd>
<dd><a href="index.php?id=57">Leggings</a></dd>
<dd><a href="index.php?id=58">Nightwear</a></dd>
<dd><a href="index.php?id=59">Shorts</a></dd>
<dd><a href="index.php?id=60">Skirts</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=61">Swimwear</a></dd>
<dd><a href="index.php?id=62">Tops & T-Shirts</a></dd>
<dd><a href="index.php?id=63">Trousers & Jeans</a></dd>
<dd><a href="index.php?id=64">Socks</a></dd>
<dd><a href="index.php?id=65">Underwear</a></dd>
</dl>
<dl>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=8" class="blue">Boys</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=66">Coats & Jackets</a></dd>
<dd><a href="index.php?id=67">Jeans</a></dd>
<dd><a href="index.php?id=68">Joggers & Sweatshirts</a></dd>
<dd><a href="index.php?id=69">Jumpers & Cardigans</a></dd>
<dd><a href="index.php?id=70">Nightwear</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=71">Shirts</a></dd>
<dd><a href="index.php?id=72">Shorts</a></dd>
<dd><a href="index.php?id=73">Sportswear</a></dd>
<dd><a href="index.php?id=74">Swimwear</a></dd>
<dd><a href="index.php?id=75">T-Shirts & Polo Shirts</a></dd>
</dl>
<dl>
<dd><a href="index.php?id=76">Trousers & Jeans</a></dd>
<dd><a href="index.php?id=77">Socks</a></dd>
<dd><a href="index.php?id=78">Underwear</a></dd>
</dl>
<dl>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=9" class="blue">Toddlers</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=79">Newborn</a></dd>
<dd><a href="index.php?id=80">0-2 Years</a></dd>
</dl>
</div>
</li><!--menu end-->
<!--menu-->
<li><a href="index.php?id=10" class="blue">Accessories</a>
<div class="subs">
<dl>
<dd><a href="index.php?id=81">Shoes</a></dd>
<dd><a href="index.php?id=82">Ties</a></dd>
<dd><a href="index.php?id=83">Caps</a></dd>
<dd><a href="index.php?id=84">Belts</a></dd>
</dl>
</div>
</li><!--menu end-->
<li><a href="index.php?id=13" class="blue">Contact Us</a></li>
</ul>
<div class="back"></div>
<div class="shadow"></div>
</div>
<div style="clear:both"></div>
</div>
CSS 3 Coding- Copy and Paste
<style>
body{margin:0px;}
.example {
width:980px;
height:40px;
margin:0px auto;
position:absolute;
margin-bottom:60px;
top:95px;
}
.menuholder {
float:left;
font:normal bold 11px/35px verdana, sans-serif;
overflow:hidden;
position:relative;
}
.menuholder .shadow {
-moz-box-shadow:0 0 20px rgba(0, 0, 0, 1);
-o-box-shadow:0 0 20px rgba(0, 0, 0, 1);
-webkit-box-shadow:0 0 20px rgba(0, 0, 0, 1);
background:#888;
box-shadow:0 0 20px rgba(0, 0, 0, 1);
height:10px;
left:5%;
position:absolute;
top:-9px;
width:100%;
z-index:100;
}
.menuholder .back {
-moz-transition-duration:.4s;
-o-transition-duration:.4s;
-webkit-transition-duration:.4s;
background-color:rgba(0, 0, 0, 0.88);
height:0;
width:980px; /*100%*/
}
.menuholder:hover div.back {
height:280px;
}
ul.menu {
display:block;
float:left;
list-style:none;
margin:0;
padding:0 125px;
position:relative;
}
ul.menu li {
float:left;
margin:0 10px 0 0;
}
ul.menu li > a {
-moz-border-radius:0 0 10px 10px;
-moz-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-moz-transition:all 0.3s ease-in-out;
-o-border-radius:0 0 10px 10px;
-o-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-o-transition:all 0.3s ease-in-out;
-webkit-border-bottom-left-radius:10px;
-webkit-border-bottom-right-radius:10px;
-webkit-box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
-webkit-transition:all 0.3s ease-in-out;
border-radius:0 0 10px 10px;
box-shadow:2px 2px 4px rgba(0, 0, 0, 0.9);
color:#eee;
display:block;
padding:0 10px;
text-decoration:none;
transition:all 0.3s ease-in-out;
}
ul.menu li a.red {
background:#a00;
}
ul.menu li a.orange {
background:#da0;
}
ul.menu li a.yellow {
background:#aa0;
}
ul.menu li a.green {
background:#060;
}
ul.menu li a.blue {
background:#073263;
}
ul.menu li a.violet {
background:#682bc2;
}
.menu li div.subs {
left:0;
overflow:hidden;
position:absolute;
top:35px;
width:0;
}
.menu li div.subs dl {
-moz-transition-duration:.2s;
-o-transition-duration:.2s;
-webkit-transition-duration:.2s;
float:left;
margin:0 130px 0 0;
overflow:hidden;
padding:40px 0 5% 2%;
width:0;
}
.menu dt {
color:#fc0;
font-family:arial, sans-serif;
font-size:12px;
font-weight:700;
height:20px;
line-height:20px;
margin:0;
padding:0 0 0 10px;
white-space:nowrap;
}
.menu dd {
margin:0;
padding:0;
text-align:left;
}
.menu dd a {
background:transparent;
color:#fff;
font-size:12px;
height:20px;
line-height:20px;
padding:0 0 0 10px;
text-align:left;
white-space:nowrap;
width:80px;
}
.menu dd a:hover {
color:#fc0;
}
.menu li:hover div.subs dl {
-moz-transition-delay:0.2s;
-o-transition-delay:0.2s;
-webkit-transition-delay:0.2s;
margin-right:2%;
width:21%;
}
ul.menu li:hover > a,ul.menu li > a:hover {
background:#aaa;
color:#fff;
padding:10px 10px 0;
}
ul.menu li a.red:hover,ul.menu li:hover a.red {
background:#c00;
}
ul.menu li a.orange:hover,ul.menu li:hover a.orange {
background:#fc0;
}
ul.menu li a.yellow:hover,ul.menu li:hover a.yellow {
background:#cc0;
}
ul.menu li a.green:hover,ul.menu li:hover a.green {
background:#080;
}
ul.menu li a.blue:hover,ul.menu li:hover a.blue {
background:#00c;
}
ul.menu li a.violet:hover,ul.menu li:hover a.violet {
background:#8a2be2;
}
.menu li:hover div.subs,.menu li a:hover div.subs {
width:100%;
}
This does exist, but it's actually a feature of git log
:
git log -p [--follow] [-1] <path>
Note that -p
can also be used to show the inline diff from a single commit:
git log -p -1 <commit>
Options used:
-p
(also -u
or --patch
) is hidden deeeeeeeep in the git-log
man page, and is actually a display option for git-diff
. When used with log
, it shows the patch that would be generated for each commit, along with the commit information—and hides commits that do not touch the specified <path>
. (This behavior is described in the paragraph on --full-diff
, which causes the full diff of each commit to be shown.)-1
shows just the most recent change to the specified file (-n 1
can be used instead of -1
); otherwise, all non-zero diffs of that file are shown.--follow
is required to see changes that occurred prior to a rename.As far as I can tell, this is the only way to immediately see the last set of changes made to a file without using git log
(or similar) to either count the number of intervening revisions or determine the hash of the commit.
To see older revisions changes, just scroll through the log, or specify a commit or tag from which to start the log. (Of course, specifying a commit or tag returns you to the original problem of figuring out what the correct commit or tag is.)
Credit where credit is due:
log -p
thanks to this answer.--follow
option.-n 1
option and atatko for mentioning the -1
variant.-p
"means" semantically.Here is a solution worked for me and also, I found all of the above solutions are correct. My excel model got corrupted and which is why my code (similar to this one) stopped working. Here is what worked for me and is working every time-
Supervised Learning: You give variously labelled example data as input, along with the correct answers. This algorithm will learn from it, and start predicting correct results based on the inputs thereafter. Example: Email Spam filter
Unsupervised Learning: You just give data and don't tell anything - like labels or correct answers. Algorithm automatically analyses patterns in the data. Example: Google News
var dt = new Date(); // current date of week
var currentWeekDay = dt.getDay();
var lessDays = currentWeekDay == 0 ? 6 : currentWeekDay - 1;
var wkStart = new Date(new Date(dt).setDate(dt.getDate() - lessDays));
var wkEnd = new Date(new Date(wkStart).setDate(wkStart.getDate() + 6));
This will work well.
Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories
, and it should work.
The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.
Here comes a solution with XSLT
:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="//element3">
<xsl:value-of select="element4/text()" />.<xsl:value-of select="element5/text()" />
</xsl:template>
</xsl:stylesheet>
A proper way to search for a substring is to use position
function instead of like
expression, which requires escaping %
, _
and an escape character (\
by default):
SELECT id FROM TAG_TABLE WHERE position(tag_name in 'aaaaaaaaaaa')>0;
Well, timing to the rescue again. It seems switch
is generally faster than if
statements.
So that, and the fact that the code is shorter/neater with a switch
statement leans in favor of switch
:
# Simplified to only measure the overhead of switch vs if
test1 <- function(type) {
switch(type,
mean = 1,
median = 2,
trimmed = 3)
}
test2 <- function(type) {
if (type == "mean") 1
else if (type == "median") 2
else if (type == "trimmed") 3
}
system.time( for(i in 1:1e6) test1('mean') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('mean') ) # 1.13 secs
system.time( for(i in 1:1e6) test1('trimmed') ) # 0.89 secs
system.time( for(i in 1:1e6) test2('trimmed') ) # 2.28 secs
Update With Joshua's comment in mind, I tried other ways to benchmark. The microbenchmark seems the best. ...and it shows similar timings:
> library(microbenchmark)
> microbenchmark(test1('mean'), test2('mean'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("mean") 709 771 864 951 16122411
2 test2("mean") 1007 1073 1147 1223 8012202
> microbenchmark(test1('trimmed'), test2('trimmed'), times=1e6)
Unit: nanoseconds
expr min lq median uq max
1 test1("trimmed") 733 792 843 944 60440833
2 test2("trimmed") 2022 2133 2203 2309 60814430
Final Update Here's showing how versatile switch
is:
switch(type, case1=1, case2=, case3=2.5, 99)
This maps case2
and case3
to 2.5
and the (unnamed) default to 99
. For more information, try ?switch
"^.*$"
literally just means select everything
"^" // anchors to the beginning of the line
".*" // zero or more of any character
"$" // anchors to end of line
I can't say enough good things about Nick Sieger's multipart-post library.
It adds support for multipart posting directly to Net::HTTP, removing your need to manually worry about boundaries or big libraries that may have different goals than your own.
Here is a little example on how to use it from the README:
require 'net/http/post/multipart'
url = URI.parse('http://www.example.com/upload')
File.open("./image.jpg") do |jpg|
req = Net::HTTP::Post::Multipart.new url.path,
"file" => UploadIO.new(jpg, "image/jpeg", "image.jpg")
res = Net::HTTP.start(url.host, url.port) do |http|
http.request(req)
end
end
You can check out the library here: http://github.com/nicksieger/multipart-post
or install it with:
$ sudo gem install multipart-post
If you're connecting via SSL you need to start the connection like this:
n = Net::HTTP.new(url.host, url.port)
n.use_ssl = true
# for debugging dev server
#n.verify_mode = OpenSSL::SSL::VERIFY_NONE
res = n.start do |http|
To add a new cookie, use HttpServletResponse.addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.
I could be misinterpreting your question, but, yes, this is possible. The way that I would go about doing it is this:
var oElement = document.getElementById('elementId'); // get a reference to your element
oElement.onclick = clickHandler; // assign its click function a function reference
function clickHandler() {
// this function will be called whenever the element is clicked
// and can also be called from the context of other functions
}
Now, whenever this element is clicked, the code in clickHandler
will execute. Similarly, you can execute the same code by calling the function from within the context of other functions (or even assign clickHandler
to handle events triggered by other elements)>
This will give you last 10 days result 110% working you will not get any type of issue
var date = new Date();
var day=date.getDate();
var month=date.getMonth() + 1;
var year=date.getFullYear();
var startDate=day+"/"+month+"/"+year;
var dayBeforeNineDays=moment().subtract(10, 'days').format('DD/MM/YYYY');
startDate=dayBeforeNineDays;
var endDate=day+"/"+month+"/"+year;
you can change the subtract days according to your requirements
Use FileUtils from Apache commons.
listFiles
public static Collection<File> listFiles(File directory,
String[] extensions,
boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files
Please try below stored procedure. I have already verified. I am getting proper result but without using groupby
.
CREATE DEFINER=`ks_root`@`%` PROCEDURE `first_five_record_per_id`()
BEGIN
DECLARE query_string text;
DECLARE datasource1 varchar(24);
DECLARE done INT DEFAULT 0;
DECLARE tenants varchar(50);
DECLARE cur1 CURSOR FOR SELECT rid FROM demo1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET @query_string='';
OPEN cur1;
read_loop: LOOP
FETCH cur1 INTO tenants ;
IF done THEN
LEAVE read_loop;
END IF;
SET @datasource1 = tenants;
SET @query_string = concat(@query_string,'(select * from demo where `id` = ''',@datasource1,''' order by rate desc LIMIT 5) UNION ALL ');
END LOOP;
close cur1;
SET @query_string = TRIM(TRAILING 'UNION ALL' FROM TRIM(@query_string));
select @query_string;
PREPARE stmt FROM @query_string;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
Path.GetFileName( Request.Url.AbsolutePath )
Solution for me was to just do it server side
I used the C# WebClient
library to get the data (in my case it was image data) and send it back to the client. There's probably something very similar in your chosen server-side language.
//Server side, api controller
[Route("api/ItemImage/GetItemImageFromURL")]
public IActionResult GetItemImageFromURL([FromQuery] string url)
{
ItemImage image = new ItemImage();
using(WebClient client = new WebClient()){
image.Bytes = client.DownloadData(url);
return Ok(image);
}
}
You can tweak it to whatever your own use case is. The main point is client.DownloadData()
worked without any CORS errors. Typically CORS issues are only between websites, hence it being okay to make 'cross-site' requests from your server.
Then the React fetch call is as simple as:
//React component
fetch(`api/ItemImage/GetItemImageFromURL?url=${imageURL}`, {
method: 'GET',
})
.then(resp => resp.json() as Promise<ItemImage>)
.then(imgResponse => {
// Do more stuff....
)}
Simply run this command. Don't forget to replace portnumber
, with your port ;)
kill -9 $(sudo lsof -t -i:portnumber)
I see this nice tutorial on how to get the like count from facebook using PHP.
public static function get_the_fb_like( $url = '' ){
$pageURL = 'http://nextopics.com';
$url = ($url == '' ) ? $pageURL : $url; // setting a value in $url variable
$params = 'select comment_count, share_count, like_count from link_stat where url = "'.$url.'"';
$component = urlencode( $params );
$url = 'http://graph.facebook.com/fql?q='.$component;
$fbLIkeAndSahre = json_decode( $this->file_get_content_curl( $url ) );
$getFbStatus = $fbLIkeAndSahre->data['0'];
return $getFbStatus->like_count;
}
here is a sample code.. I don't know how to paste the code with correct format in here, so just kindly visit this link for better view of the code.
In java/groovy try:
import java.awt.Toolkit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
...
java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension maximizedScreenSize = new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setPosition(new Point(0, 0));
driver.manage().window().setSize(maximizedScreenSize);
this will open browser in fullscreen
I know this question is old but here is how I solved it.
I copied the openssl.cnf
file from the bin
directory to the parent directory which is C:/Openssl/openssl.cnf
instead of C:/Openssl/bin/openssl.cnf
and worked fine.
The ContextSwitchDeadlock
doesn't necessarily mean your code has an issue, just that there is a potential. If you go to Debug > Exceptions
in the menu and expand the Managed Debugging Assistants
, you will find ContextSwitchDeadlock
is enabled. If you disable this, VS will no longer warn you when items are taking a long time to process. In some cases you may validly have a long-running operation. It's also helpful if you are debugging and have stopped on a line while this is processing - you don't want it to complain before you've had a chance to dig into an issue.
The .bashrc file is used for setting variables used by interactive login shells. If you want those environment variables available in Eclipse you need to put them in /etc/environment.
For anyone experiencing the problem of the info.plist not being included when trying to add localizations, like in Xcode 9.
You need make the info.plist localiazble by going into it and clicking on the localize button in the file inspector, as shown below.
The info.plist will then be included in the file resources for when you go to add new Localizations.
Just always compare the Date property of DateTime, instead of the full date time.
When you make your LINQ query, use date.Date in the query, ie:
var results = from c in collection
where c.Date == myDateTime.Date
select c;
This is for the text form of a timestamp that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted as the time. [updated 2016-01-14])
You can get the timestamp as a string using the .now()
or .utcnow()
of the datetime.datetime
:
>>> import datetime
>>> print datetime.datetime.utcnow()
2012-12-15 10:14:51.898000
The now
differs from utcnow
as expected -- otherwise they work the same way:
>>> print datetime.datetime.now()
2012-12-15 11:15:09.205000
You can render the timestamp to the string explicitly:
>>> str(datetime.datetime.now())
'2012-12-15 11:15:24.984000'
Or you can be even more explicit to format the timestamp the way you like:
>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 15. December 2012 11:19AM'
If you want the ISO format, use the .isoformat()
method of the object:
>>> datetime.datetime.now().isoformat()
'2013-11-18T08:18:31.809000'
You can use these in variables for calculations and printing without conversions.
>>> ts = datetime.datetime.now()
>>> tf = datetime.datetime.now()
>>> te = tf - ts
>>> print ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980
If Invalidating caches not helps, just close the project then re-open it. Steps:
You could do it like that:
File folder = new File("your/path");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println("File " + listOfFiles[i].getName());
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " + listOfFiles[i].getName());
}
}
Do you want to only get JPEG files or all files?
Had a similar question and had difficulty finding an answer. The following function allows you to paste an image with a transparency parameter over another image at a specific offset.
import Image
def trans_paste(fg_img,bg_img,alpha=1.0,box=(0,0)):
fg_img_trans = Image.new("RGBA",fg_img.size)
fg_img_trans = Image.blend(fg_img_trans,fg_img,alpha)
bg_img.paste(fg_img_trans,box,fg_img_trans)
return bg_img
bg_img = Image.open("bg.png")
fg_img = Image.open("fg.png")
p = trans_paste(fg_img,bg_img,.7,(250,100))
p.show()
Infinity is a reserved character in HTML. Following are its values in various forms.
To use in html code
<p>The html symbol is ∞ </p>_x000D_
<p>The html symbol is ∞ </p>_x000D_
<p>The html symbol is ∞ </p>
_x000D_
Reference : HTML Symbols - HTML Infinity Symbol
Actually, in Python 3 the module imp
is marked as DEPRECATED. Well, at least that's true for 3.4.
Instead the reload
function from the importlib
module should be used:
https://docs.python.org/3/library/importlib.html#importlib.reload
But be aware that this library had some API-changes with the last two minor versions.
After a long research I build this reg expression. I hope it will help others too.......
url = 'https://google.co.in';
var re = /[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/;
if (!re.test(url)) {
alert("url error");
return false;
}else{
alert('success')
}
The simulator is just an application, and as such you can run it like any other application.
To run the simulator straight from terminal prepend these locations with the open
command
Xcode 7.x, 8.x, and 9.x
In Xcode 7.x, the iPhone Simulator has moved again: /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
.
Xcode 6.x
In Xcode 6.x, the iPhone Simulator has moved yet again, and now resides here: /Applications/Xcode.app/Contents/Developer/Applications/iOS Simulator.app
.
Xcode 4.x, 5.x
In Xcode 4.x (through 4.5 on Mountain Lion) and Xcode 5.0.x on Mavericks, it lives here: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/
In my version of Xcode (4.5.2), I find it quite convenient to use the Open Developer Tool
menu from either the dock icon or the Xcode menu:
Xcode 3.x
In Xcode 3.x, it lives here:
/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone Simulator.app
In some future version of Xcode, it will probably move again, it's a squirrelly little app.
This is a user side fault and belongs to 4xx group. This is the right answer https://developers.rebrandly.com/docs/403-already-exists-errors
Just to complete Amit Garg answer, there are several ways to inject dependencies in AngularJS.
You can also use $inject
to add a dependency:
var MyController = function($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];
There is no .length property in C. The .length property can only be applied to arrays in object oriented programming (OOP) languages. The .length property is inherited from the object class; the class all other classes & objects inherit from in an OOP language. Also, one would use .length-1 to return the number of the last index in an array; using just the .length will return the total length of the array.
I would suggest something like this:
int index;
int jdex;
for( index = 0; index < (sizeof( my_array ) / sizeof( my_array[0] )); index++){
for( jdex = 0; jdex < (sizeof( my_array ) / sizeof( my_array[0] )); jdex++){
printf( "%d", my_array[index][jdex] );
printf( "\n" );
}
}
The line (sizeof( my_array ) / sizeof( my_array[0] )) will give you the size of the array in question. The sizeof property will return the length in bytes, so one must divide the total size of the array in bytes by how many bytes make up each element, each element takes up 4 bytes because each element is of type int, respectively. The array is of total size 16 bytes and each element is of 4 bytes so 16/4 yields 4 the total number of elements in your array because indexing starts at 0 and not 1.
What if you want your parts to contain commas? Well, quote them. And then what about the quotes? Well, double them up. In other words:
part1,"part2,with a comma and a quote "" in it",part3
PHP provides the https://php.net/str_getcsv function to parse a string as if it were a line in a CSV file which can be used with the above line instead of explode
:
print_r(str_getcsv('part1,"part2,with a comma and a quote "" in it",part3'));
Array
(
[0] => part1
[1] => part2,with a comma and a quote " in it
[2] => part3
)
As mentioned before, the use of x(end+1) = newElem
has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.
However, what should not be forgotten is that x = [x newElem]
will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]
All in all, if you want a solution that allows you to concatenate your existing vector x
with newElem
that may or may not be a scalar, this should do the trick:
x(end+(1:numel(newElem)))=newElem
In jQuery there is $.isPlainObject()
method for that:
Description: Check to see if an object is a plain object (created using "{}" or "new Object").
Have you escaped your forward slashes( / )? I've had trouble with those before
DateTimeFormat
, introduced in java 8:The idea is to define two formats: one for the input format, and one for the output format. Parse with the input formatter, then format with the output formatter.
Your input format looks quite standard, except the trailing Z
. Anyway, let's deal with this: "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
. The trailing 'Z'
is the interesting part. Usually there's time zone data here, like -0700
. So the pattern would be ...Z
, i.e. without apostrophes.
The output format is way more simple: "dd-MM-yyyy"
. Mind the small y
-s.
Here is the example code:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse("2018-04-10T04:00:00.000Z", inputFormatter);
String formattedDate = outputFormatter.format(date);
System.out.println(formattedDate); // prints 10-04-2018
SimpleDateFormat
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat outputFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = inputFormat.parse("2018-04-10T04:00:00.000Z");
String formattedDate = outputFormat.format(date);
System.out.println(formattedDate); // prints 10-04-2018
Others worked for me, but this did:
Tag.find().sort('name', 1).run(onComplete);
No need to worry for incrementing/decrementing numbers using Javascript. Now HTML itself provides an easy way for it.
<input type="number" value="50">
It is that simple.The problem is that it works fine only in some browsers.Mozilla has not yet supported this feature.
Hope this code will help
<html>
<head>
<style type="text/css">
.js #flash {display: none;}
</style>
<script type="text/javascript">
document.documentElement.className = 'js';
</script>
</head>
<body>
<!-- the rest of your code goes here -->
<script type="text/javascript" src="/scripts/jquery.js"></script>
<script type="text/javascript">
// Stuff to do as soon as the body finishes loading.
// No need for $(document).ready() here.
</script>
</body>
</html>
Here's a simple code that reads strings from stdin
, adds them into List<String>
, and then uses toArray
to convert it to String[]
(if you really need to work with arrays).
import java.util.*;
public class UserInput {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Scanner stdin = new Scanner(System.in);
do {
System.out.println("Current list is " + list);
System.out.println("Add more? (y/n)");
if (stdin.next().startsWith("y")) {
System.out.println("Enter : ");
list.add(stdin.next());
} else {
break;
}
} while (true);
stdin.close();
System.out.println("List is " + list);
String[] arr = list.toArray(new String[0]);
System.out.println("Array is " + Arrays.toString(arr));
}
}
#include <unistd.h>
int usleep(useconds_t useconds); //pass in microseconds
Without jQuery : DEMO
<div id="parentDiv" onclick="alert('parentDiv');">
<div id="childDiv" onclick="alert('childDiv');event.cancelBubble=true;">
AAA
</div>
</div>
The DOM interface, already keeps track of the initial state...
So doing the following is enough:
$("#reset").on("click", function () {
$('#my_select option').prop('selected', function() {
return this.defaultSelected;
});
});
I solved this problem following vestigal's tips here:
Can I set an unlimited length for maxJsonLength in web.config?
When I needed to post a large json to an action in a controller, I would get the famous "Error during deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.\r\nParameter name: input value provider".
What I did is create a new ValueProviderFactory, LargeJsonValueProviderFactory, and set the MaxJsonLength = Int32.MaxValue in the GetDeserializedObject method
public sealed class LargeJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(LargeJsonValueProviderFactory.EntryLimitedDictionary backingStore, string prefix, object value)
{
IDictionary<string, object> dictionary = value as IDictionary<string, object>;
if (dictionary != null)
{
foreach (KeyValuePair<string, object> keyValuePair in (IEnumerable<KeyValuePair<string, object>>) dictionary)
LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
}
else
{
IList list = value as IList;
if (list != null)
{
for (int index = 0; index < list.Count; ++index)
LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakeArrayKey(prefix, index), list[index]);
}
else
backingStore.Add(prefix, value);
}
}
private static object GetDeserializedObject(ControllerContext controllerContext)
{
if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
return (object) null;
string end = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
if (string.IsNullOrEmpty(end))
return (object) null;
var serializer = new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue};
return serializer.DeserializeObject(end);
}
/// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
/// <returns>A JSON value-provider object for the specified controller context.</returns>
/// <param name="controllerContext">The controller context.</param>
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
object deserializedObject = LargeJsonValueProviderFactory.GetDeserializedObject(controllerContext);
if (deserializedObject == null)
return (IValueProvider) null;
Dictionary<string, object> dictionary = new Dictionary<string, object>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase);
LargeJsonValueProviderFactory.AddToBackingStore(new LargeJsonValueProviderFactory.EntryLimitedDictionary((IDictionary<string, object>) dictionary), string.Empty, deserializedObject);
return (IValueProvider) new DictionaryValueProvider<object>((IDictionary<string, object>) dictionary, CultureInfo.CurrentCulture);
}
private static string MakeArrayKey(string prefix, int index)
{
return prefix + "[" + index.ToString((IFormatProvider) CultureInfo.InvariantCulture) + "]";
}
private static string MakePropertyKey(string prefix, string propertyName)
{
if (!string.IsNullOrEmpty(prefix))
return prefix + "." + propertyName;
return propertyName;
}
private class EntryLimitedDictionary
{
private static int _maximumDepth = LargeJsonValueProviderFactory.EntryLimitedDictionary.GetMaximumDepth();
private readonly IDictionary<string, object> _innerDictionary;
private int _itemCount;
public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
{
this._innerDictionary = innerDictionary;
}
public void Add(string key, object value)
{
if (++this._itemCount > LargeJsonValueProviderFactory.EntryLimitedDictionary._maximumDepth)
throw new InvalidOperationException("JsonValueProviderFactory_RequestTooLarge");
this._innerDictionary.Add(key, value);
}
private static int GetMaximumDepth()
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
if (appSettings != null)
{
string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
int result;
if (values != null && values.Length > 0 && int.TryParse(values[0], out result))
return result;
}
return 1000;
}
}
}
Then, in the Application_Start method from Global.asax.cs, replace the ValueProviderFactory with the new one:
protected void Application_Start()
{
...
//Add LargeJsonValueProviderFactory
ValueProviderFactory jsonFactory = null;
foreach (var factory in ValueProviderFactories.Factories)
{
if (factory.GetType().FullName == "System.Web.Mvc.JsonValueProviderFactory")
{
jsonFactory = factory;
break;
}
}
if (jsonFactory != null)
{
ValueProviderFactories.Factories.Remove(jsonFactory);
}
var largeJsonValueProviderFactory = new LargeJsonValueProviderFactory();
ValueProviderFactories.Factories.Add(largeJsonValueProviderFactory);
}
Pure CSS:
.app-tooltip {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.app-tooltip:before {_x000D_
content: attr(data-title);_x000D_
background-color: rgba(97, 97, 97, 0.9);_x000D_
color: #fff;_x000D_
font-size: 12px;_x000D_
padding: 10px;_x000D_
position: absolute;_x000D_
bottom: -50px;_x000D_
opacity: 0;_x000D_
transition: all 0.4s ease;_x000D_
font-weight: 500;_x000D_
z-index: 2;_x000D_
}_x000D_
_x000D_
.app-tooltip:after {_x000D_
content: '';_x000D_
position: absolute;_x000D_
opacity: 0;_x000D_
left: 5px;_x000D_
bottom: -16px;_x000D_
border-style: solid;_x000D_
border-width: 0 10px 10px 10px;_x000D_
border-color: transparent transparent rgba(97, 97, 97, 0.9) transparent;_x000D_
transition: all 0.4s ease;_x000D_
}_x000D_
_x000D_
.app-tooltip:hover:after,_x000D_
.app-tooltip:hover:before {_x000D_
opacity: 1;_x000D_
}
_x000D_
<div href="#" class="app-tooltip" data-title="Your message here"> Test here</div>
_x000D_
I am trying to avoid using VBA. But if has to be, then it has to be:)
There is quite simple UDF for you:
Function myCountIf(rng As Range, criteria) As Long
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
Next ws
End Function
and call it like this: =myCountIf(I:I,A13)
P.S. if you'd like to exclude some sheets, you can add If
statement:
Function myCountIf(rng As Range, criteria) As Long
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.name <> "Sheet1" And ws.name <> "Sheet2" Then
myCountIf = myCountIf + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
End If
Next ws
End Function
UPD:
I have four "reference" sheets that I need to exclude from being scanned/searched. They are currently the last four in the workbook
Function myCountIf(rng As Range, criteria) As Long
Dim i As Integer
For i = 1 To ThisWorkbook.Worksheets.Count - 4
myCountIf = myCountIf + WorksheetFunction.CountIf(ThisWorkbook.Worksheets(i).Range(rng.Address), criteria)
Next i
End Function
Use the "\uxxxx" escape format.
According to Wikipedia, the copyright symbol is unicode U+00A9 so your line should read:
String copyright = "\u00a9 2003-2008 My Company. All rights reserved.";
DateTime
inherits its equals
method from AbstractInstant
. It is implemented as such
public boolean equals(Object readableInstant) { // must be to fulfil ReadableInstant contract if (this == readableInstant) { return true; } if (readableInstant instanceof ReadableInstant == false) { return false; } ReadableInstant otherInstant = (ReadableInstant) readableInstant; return getMillis() == otherInstant.getMillis() && FieldUtils.equals(getChronology(), otherInstant.getChronology()); }
Notice the last line comparing chronology. It's possible your instances' chronologies are different.
Look for the url of the pac
file in internet explorer lan settings and download the pac file from the URL configured.
The pac file is just a javascript file with a function named FindProxyForURL
which returns different proxy hosts in different scenarios.
Try to find a host in that pac file which you think is for general web traffic and plug it into .npmrc in C:\Users\<username>\.npmrc
proxy=http://<username>:<pass>@proxyhost:<port>
https-proxy=http://<uname>:<pass>@proxyhost:<port>
Even though you may login with your domain and username on your corporate machine, It is highly possible that the user active directory domain name is not required for the proxy, only the username and password (which may be different than your Active Directory login)
Don't forget to fiddle with escaping special password characters.
Yes you can view XML
files of an Android APK
file. There is a tool for this: android-apktool
It is a tool for reverse engineering 3rd party, closed, binary Android apps
How to do this on your Windows System:
Now copy the APK
file also in that directory and run the following command in your command prompt:
apktool d HelloWorld.apk ./HelloWorld
This will create a directory "HelloWorld
" in your current directory. Inside it you can find the AndroidManifest.xml
file in decrypted format, and you can also find other XML
files inside the "HelloWorld/res/layout"
directory.
Here HelloWorld.apk
is your Android APK file.
See the below screen shot for more information:
X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!
There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.
Source: classroomm.com
great code; little hint: if you sometimes have to bypass more data and not only the viewmodel ..
if (model is ViewDataDictionary)
{
controller.ViewData = model as ViewDataDictionary;
} else {
controller.ViewData.Model = model;
}
Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).
# for completeness lets do the routine thing of connections and cursors
conn = sqlite3.connect(db_file, timeout=1000)
cursor = conn.cursor()
# get the count of tables with the name
tablename = 'KABOOM'
cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))
print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.
# check if the db has existing table named KABOOM
# if the count is 1, then table exists
if cursor.fetchone()[0] ==1 :
print('Table exists. I can do my custom stuff here now.... ')
pass
else:
# then table doesn't exist.
custRET = myCustFunc(foo,bar) # replace this with your custom logic
The viewport is all that matters, but you likely want the entire website to stay darkened even while scrolling. For this, you want to use position:fixed
instead of position:absolute
. Fixed will keep the element static on the screen as you scroll, giving the impression that the entire body is darkened.
Example: http://jsbin.com/okabo3/edit
div.fadeMe {
opacity: 0.5;
background: #000;
width: 100%;
height: 100%;
z-index: 10;
top: 0;
left: 0;
position: fixed;
}
<body>
<div class="fadeMe"></div>
<p>A bunch of content here...</p>
</body>
I had the same issue.
During the 1st development I used a .csv file (comma as separator) that I've modified a bit before saving it. After saving the commas became semicolon.
On Windows it is dependent on the "Regional and Language Options" customize screen where you find a List separator. This is the char Windows applications expect to be the CSV separator.
When testing from a brand new file I encountered that issue.
I've removed the 'sep' argument in read_csv method before:
df1 = pd.read_csv('myfile.csv', sep=',');
after:
df1 = pd.read_csv('myfile.csv');
That way, the issue disappeared.
alternatively in c or c++ after including stdio.h
char d=(char)(7);
printf("%c\n",d);
(char)7 is called the bell character.
It's your choice. There are basically three ways in a Java web application archive (WAR):
So that you can load it by ClassLoader#getResourceAsStream()
with a classpath-relative path:
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("foo.properties");
// ...
Properties properties = new Properties();
properties.load(input);
Here foo.properties
is supposed to be placed in one of the roots which are covered by the default classpath of a webapp, e.g. webapp's /WEB-INF/lib
and /WEB-INF/classes
, server's /lib
, or JDK/JRE's /lib
. If the propertiesfile is webapp-specific, best is to place it in /WEB-INF/classes
. If you're developing a standard WAR project in an IDE, drop it in src
folder (the project's source folder). If you're using a Maven project, drop it in /main/resources
folder.
You can alternatively also put it somewhere outside the default classpath and add its path to the classpath of the appserver. In for example Tomcat you can configure it as shared.loader
property of Tomcat/conf/catalina.properties
.
If you have placed the foo.properties
it in a Java package structure like com.example
, then you need to load it as below
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("com/example/foo.properties");
// ...
Note that this path of a context class loader should not start with a /
. Only when you're using a "relative" class loader such as SomeClass.class.getClassLoader()
, then you indeed need to start it with a /
.
ClassLoader classLoader = getClass().getClassLoader();
InputStream input = classLoader.getResourceAsStream("/com/example/foo.properties");
// ...
However, the visibility of the properties file depends then on the class loader in question. It's only visible to the same class loader as the one which loaded the class. So, if the class is loaded by e.g. server common classloader instead of webapp classloader, and the properties file is inside webapp itself, then it's invisible. The context class loader is your safest bet so you can place the properties file "everywhere" in the classpath and/or you intend to be able to override a server-provided one from the webapp on.
So that you can load it by ServletContext#getResourceAsStream()
with a webcontent-relative path:
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/foo.properties");
// ...
Note that I have demonstrated to place the file in /WEB-INF
folder, otherwise it would have been public accessible by any webbrowser. Also note that the ServletContext
is in any HttpServlet
class just accessible by the inherited GenericServlet#getServletContext()
and in Filter
by FilterConfig#getServletContext()
. In case you're not in a servlet class, it's usually just injectable via @Inject
.
So that you can load it the usual java.io
way with an absolute local disk file system path:
InputStream input = new FileInputStream("/absolute/path/to/foo.properties");
// ...
Note the importance of using an absolute path. Relative local disk file system paths are an absolute no-go in a Java EE web application. See also the first "See also" link below.
Just weigh the advantages/disadvantages in your own opinion of maintainability.
If the properties files are "static" and never needs to change during runtime, then you could keep them in the WAR.
If you prefer being able to edit properties files from outside the web application without the need to rebuild and redeploy the WAR every time, then put it in the classpath outside the project (if necessary add the directory to the classpath).
If you prefer being able to edit properties files programmatically from inside the web application using Properties#store()
method, put it outside the web application. As the Properties#store()
requires a Writer
, you can't go around using a disk file system path. That path can in turn be passed to the web application as a VM argument or system property. As a precaution, never use getRealPath()
. All changes in deploy folder will get lost on a redeploy for the simple reason that the changes are not reflected back in original WAR file.
The difference is ternary operator
return condition ? someData : Promise.reject(new Error('not OK'))
return condition ? someData : throw new Error('not OK')
This will capture requests for files like version
,
release
, and README.md
, etc. which should be
treated either as endpoints, if defined (as in the
case of /release), or as "not found."
I recently faced this issue on my MAC device when I was running flutter project on Android Studio
Steps to fix this.
brew tap dart-lang/dart
brew install dart
brew info dart
Please note the path to the Dart SDK:/usr/local/opt/dart/libexec
paste the Dart SDK path in Android Studio Settings
new syntax
<%= form_for :user, url: custom_user_path, method: :post do |f|%>
<%end%>
I can give an example commonly seen in project.
Here, option --no-ff
(i.e. true merge) creates a new commit with multiple parents, and provides a better history tracking. Otherwise, --ff
(i.e. fast-forward merge) is by default.
$ git checkout master
$ git checkout -b newFeature
$ ...
$ git commit -m 'work from day 1'
$ ...
$ git commit -m 'work from day 2'
$ ...
$ git commit -m 'finish the feature'
$ git checkout master
$ git merge --no-ff newFeature -m 'add new feature'
$ git log
// something like below
commit 'add new feature' // => commit created at merge with proper message
commit 'finish the feature'
commit 'work from day 2'
commit 'work from day 1'
$ gitk // => see details with graph
$ git checkout -b anotherFeature // => create a new branch (*)
$ ...
$ git commit -m 'work from day 3'
$ ...
$ git commit -m 'work from day 4'
$ ...
$ git commit -m 'finish another feature'
$ git checkout master
$ git merge anotherFeature // --ff is by default, message will be ignored
$ git log
// something like below
commit 'work from day 4'
commit 'work from day 3'
commit 'add new feature'
commit 'finish the feature'
commit ...
$ gitk // => see details with graph
(*) Note that here if the newFeature
branch is re-used, instead of creating a new branch, git will have to do a --no-ff
merge anyway. This means fast forward merge is not always eligible.
android:gravity
handles the alignment of its children,
android:layout_gravity
handles the alignment of itself.
So use one of these.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:baselineAligned="false"
android:gravity="center"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Main" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center" >
<ImageView
android:id="@+id/imageButton_speak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/image_bg"
android:src="@drawable/ic_speak" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center" >
<ImageView
android:id="@+id/imageButton_readtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/image_bg"
android:src="@drawable/ic_readtext" />
</LinearLayout>
...
</LinearLayout>
or
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
android:baselineAligned="false"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".Main" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" >
<ImageView
android:id="@+id/imageButton_speak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/image_bg"
android:src="@drawable/ic_speak" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1" >
<ImageView
android:id="@+id/imageButton_readtext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/image_bg"
android:src="@drawable/ic_readtext" />
</LinearLayout>
...
</LinearLayout>
>> /dev/null
redirects standard output (stdout
) to /dev/null
, which discards it.
(The >>
seems sort of superfluous, since >>
means append while >
means truncate and write, and either appending to or writing to /dev/null
has the same net effect. I usually just use >
for that reason.)
2>&1
redirects standard error (2
) to standard output (1
), which then discards it as well since standard output has already been redirected.
2 workarounds, rather than a solution: In my Git Bash, following command hangs and I don't get the prompt back:
% python
So I just use:
% winpty python
As some people have noted above, you can also use:
% python -i
2020-07-14: Git 2.27.0 has added optional experimental support for pseudo consoles, which allow running Python from the command line:
Be sure that android:debuggable="true"
is set in the application
tag of your manifest file, and then:
try this
html code
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="firstname">
<input type="submit" name="submit" value="Submit">
</form>
php code:
if(isset($_POST['Submit'])){
$firstname=isset($_POST['firstname'])?$_post['firstname']:"";
echo $firstname;
}
I tried to set up toolbar like @Gabriele Mariotti, but I had some problem with title. So then I set order to
toolbar.setTitle("Title")
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_good);
and it works.
You don't need to add --resource flag just type the following and laravel will create the whole desired resources
php artisan make:controller TodoController --model=todo
You need to achieve that using CSS
http://binnyva.blogspot.com/2006/01/icons-for-select-menu-options-in.html
The solution is to put an N in front of both the type and the SQL string to indicate it is a double-byte character string:
DECLARE @SQL NVARCHAR(100)
SET @SQL = N'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL
You have to check if the argument is undefined:
function func(a, b) {
if (a === undefined) a = "default value";
if (b === undefined) b = "default value";
}
1) To redirect to the login page / from the login page, don't use the Redirect() methods. Use FormsAuthentication.RedirectToLoginPage()
and FormsAuthentication.RedirectFromLoginPage()
!
2) You should just use RedirectToAction("action", "controller") in regular scenarios..
You want to redirect in side the Initialize method? Why? I don't see why would you ever want to do this, and in most cases you should review your approach imo.. If you want to do this for authentication this is DEFINITELY the wrong way (with very little chances foe an exception)
Use the [Authorize]
attribute on your controller or method instead :)
UPD: if you have some security checks in the Initialise method, and the user doesn't have access to this method, you can do a couple of things: a)
Response.StatusCode = 403;
Response.End();
This will send the user back to the login page. If you want to send him to a custom location, you can do something like this (cautios: pseudocode)
Response.Redirect(Url.Action("action", "controller"));
No need to specify the full url. This should be enough. If you completely insist on the full url:
Response.Redirect(new Uri(Request.Url, Url.Action("action", "controller")).ToString());
You can also use Json.NET.
return JsonConvert.SerializeObject(jsonResult.Data);
Currently the fastest implementation of md5 (based on Joseph Myers' code):
https://github.com/iReal/FastMD5
jsPerf comparaison: http://jsperf.com/md5-shootout/63
Pandas DataFrame columns are Pandas Series when you pull them out, which you can then call x.tolist()
on to turn them into a Python list. Alternatively you cast it with list(x)
.
import pandas as pd
data_dict = {'one': pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two': pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}
df = pd.DataFrame(data_dict)
print(f"DataFrame:\n{df}\n")
print(f"column types:\n{df.dtypes}")
col_one_list = df['one'].tolist()
col_one_arr = df['one'].to_numpy()
print(f"\ncol_one_list:\n{col_one_list}\ntype:{type(col_one_list)}")
print(f"\ncol_one_arr:\n{col_one_arr}\ntype:{type(col_one_arr)}")
Output:
DataFrame:
one two
a 1.0 1
b 2.0 2
c 3.0 3
d NaN 4
column types:
one float64
two int64
dtype: object
col_one_list:
[1.0, 2.0, 3.0, nan]
type:<class 'list'>
col_one_arr:
[ 1. 2. 3. nan]
type:<class 'numpy.ndarray'>
Just check if you have set the buffering option to false (by default its true). For response.redirect to work,
simply assign a variable to ()
or " "
, then when needed type
print(x, x, x, Hello World, x)
or something like that.
Hope this is a little less complicated:)
put this inside your Manifest like this in No fullscreen Mode
android:windowSoftInputMode="stateVisible|adjustPan"
in your manifest
<activity
android:windowSoftInputMode="stateVisible|adjustPan"
android:name="com.example.patronusgps.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Maybe this post is too old but it may help as a suggestion for someone looking around on this : Instead of using:
print_r($this->pdo->errorInfo());
Use PHP implode() function:
echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());
This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.
Hope it helps
you can append the file with >> sign. It insert the contents at the last of the file which we are using.e.g if file let its name is myfile contains xyz then cat >> myfile abc ctrl d
after the above process the myfile contains xyzabc.
May this code helps you.
$(document).ready(function(){_x000D_
$('.slectOne').on('change', function() {_x000D_
$('.slectOne').not(this).prop('checked', false);_x000D_
$('#result').html($(this).data( "id" ));_x000D_
if($(this).is(":checked"))_x000D_
$('#result').html($(this).data( "id" ));_x000D_
else_x000D_
$('#result').html('Empty...!');_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input type="checkbox" class="slectOne" data-id="1 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="2 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="3 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="4 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="5 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="6 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="7 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="8 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="9 selected"/>_x000D_
<input type="checkbox" class="slectOne" data-id="10 selected"/>_x000D_
<span id="result"></span>_x000D_
</body>_x000D_
</html>
_x000D_
Working link Click here
Security note: Disabling security checks is dangerous and should be avoided
You can disable security checks globally for all requests of the default client:
package main
import (
"fmt"
"net/http"
"crypto/tls"
)
func main() {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
_, err := http.Get("https://golang.org/")
if err != nil {
fmt.Println(err)
}
}
You can disable security check for a client:
package main
import (
"fmt"
"net/http"
"crypto/tls"
)
func main() {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client := &http.Client{Transport: tr}
_, err := client.Get("https://golang.org/")
if err != nil {
fmt.Println(err)
}
}
I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.
The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.
SHORT ANSWER (should be similar for MinGW too but I haven't tried it):
LONG ANSWER:
Below are the detailed steps that solved this issue for me:
Uninstall/delete the previous version of Cygwin (MinGW in your case)
Make sure that CLion is up-to-date
Run Cygwin setup (x64 for my 64-bit OS)
Install at least the following packages for Cygwin:
gcc
g++
make
Cmake
gdb
Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).
Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows
[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']
Add the 'bin' folder to the Path variable. For Cygwin, I added:
D:\cygwin64\bin
Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings
Select 'Build, Execution, Deployment' and then click on 'Toolchains'
Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)
For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)
'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]
Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'
See screenshot: Check all paths to the compiler, make and gdb
See screenshot: Check the configuration to run the project
There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active
Build your project and then run the project. You should see the output in the terminal window
Hope this helps! Good luck and enjoy CLion.
The suggestion to use .split(/[ ,]+/)
is good, but with natural sentences sooner or later you'll end up getting empty elements in the array. e.g. ['foo', '', 'bar']
.
Which is fine if that's okay for your use case. But if you want to get rid of the empty elements you can do:
var str = 'whatever your text is...';
str.split(/[ ,]+/).filter(Boolean);
Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes:
java.util.Base64
, java.util.Base64.Encoder
and java.util.Base64.Decoder
.
Example usage:
// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);
// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);
// decode a String
byte [] barr = Base64.getDecoder().decode(encoded);
In my case (on windows 10), it would connect fine to adb and I could type any adb
commands. But as soon as it got to the bootloader using adb reboot bootloader
I wasn't able to perform any fastboot
commands.
What I did notice that in the device manager that it refreshed when I connected to device. Next thing to do was to check what changed when connecting. Apparently the fastboot device was inside the Kedacom USB Device
. Not really sure what that was, but I updated the device to use a different driver, in my case the Fastboot interface (Google USB ID)
, and that fixed my waiting for device
issue
It seems your solution is not much ugly. You can use functions and make it proffesional like these ways
new.function <- function(filename){
readChar(filename, file.info(filename)$size)
}
new.function('foo.txt')
new.function <- function(){
filename <- 'foo.txt'
return (readChar(filename, file.info(filename)$size))
}
new.function()
Just use cd /d %root%
to switch driver letters and change directories.
Alternatively, use pushd %root%
to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd
to switch back.
Note that pushd
will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd
for that directory.
I had similar problem when importing phone number data from excel to mysql database. So a simple trick without the need to identify the length of the phone number (because the length of the phone numbers varied in my data):
UPDATE table SET phone_num = concat('0', phone_num)
I just concated 0 in front of the phone_num
.
Swift 4
private func createButton {
let sayButtonT = UIButton(type: .custom)
sayButtonT.addTarget(self, action: #selector(sayAction(_:)), for: .touchUpInside)
}
@objc private func sayAction(_ sender: UIButton?) {
}
Updating the value of a field does not update its value attribute in the DOM so that's why your selector is always matching a field, even when it's not actually empty.
Instead use the invalid
pseudo-class to achieve what you want, like so:
input:required {_x000D_
border: 1px solid green;_x000D_
}_x000D_
input:required:invalid {_x000D_
border: 1px solid red;_x000D_
}
_x000D_
<input required type="text" value="">_x000D_
_x000D_
<input required type="text" value="Value">
_x000D_
escapeRegExp = function(str) {
if (str == null) return '';
return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};
public static void Serialize(object value, Stream s)
{
using (StreamWriter writer = new StreamWriter(s))
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
{
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jsonWriter, value);
jsonWriter.Flush();
}
}
public static T Deserialize<T>(Stream s)
{
using (StreamReader reader = new StreamReader(s))
using (JsonTextReader jsonReader = new JsonTextReader(reader))
{
JsonSerializer ser = new JsonSerializer();
return ser.Deserialize<T>(jsonReader);
}
}
It is possible.
When you use Return inside a procedure, the control is transferred to the calling program which calls the procedure. It is like an exit in loops.
It won't return any value.
Assembly assembly = Assembly.LoadFile(@"....bin\Debug\TestCases.dll");
//get all types
var testTypes = from t in assembly.GetTypes()
let attributes = t.GetCustomAttributes(typeof(NUnit.Framework.TestFixtureAttribute), true)
where attributes != null && attributes.Length > 0
orderby t.Name
select t;
foreach (var type in testTypes)
{
//get test method in types.
var testMethods = from m in type.GetMethods()
let attributes = m.GetCustomAttributes(typeof(NUnit.Framework.TestAttribute), true)
where attributes != null && attributes.Length > 0
orderby m.Name
select m;
foreach (var method in testMethods)
{
MethodInfo methodInfo = type.GetMethod(method.Name);
if (methodInfo != null)
{
object result = null;
ParameterInfo[] parameters = methodInfo.GetParameters();
object classInstance = Activator.CreateInstance(type, null);
if (parameters.Length == 0)
{
// This works fine
result = methodInfo.Invoke(classInstance, null);
}
else
{
object[] parametersArray = new object[] { "Hello" };
// The invoke does NOT work;
// it throws "Object does not match target type"
result = methodInfo.Invoke(classInstance, parametersArray);
}
}
}
}
I couldn't synchronize and change the speed my setIntervals too and I was about to post a question. But I think I've found a way. It should certainly be improved because I'm a beginner. So, I'd gladly read your comments/remarks about this.
<body onload="foo()">
<div id="count1">0</div>
<div id="count2">2nd counter is stopped</div>
<button onclick="speed0()">pause</button>
<button onclick="speedx(1)">normal speed</button>
<button onclick="speedx(2)">speed x2</button>
<button onclick="speedx(4)">speed x4</button>
<button onclick="startTimer2()">Start second timer</button>
</body>
<script>
var count1 = 0,
count2 = 0,
greenlight = new Boolean(0), //blocks 2nd counter
speed = 1000, //1second
countingSpeed;
function foo(){
countingSpeed = setInterval(function(){
counter1();
counter2();
},speed);
}
function counter1(){
count1++;
document.getElementById("count1").innerHTML=count1;
}
function counter2(){
if (greenlight != false) {
count2++;
document.getElementById("count2").innerHTML=count2;
}
}
function startTimer2(){
//while the button hasn't been clicked, greenlight boolean is false
//thus, the 2nd timer is blocked
greenlight = true;
counter2();
//counter2() is greenlighted
}
//these functions modify the speed of the counters
function speed0(){
clearInterval(countingSpeed);
}
function speedx(a){
clearInterval(countingSpeed);
speed=1000/a;
foo();
}
</script>
If you want the counters to begin to increase once the page is loaded, put counter1()
and counter2()
in foo()
before countingSpeed
is called. Otherwise, it takes speed
milliseconds before execution.
EDIT : Shorter answer.
I experienced the same issue on nginx server (DigitalOcean) - all I had to do is to log in as root
and modify the file /etc/php5/fpm/php.ini
.
To find the line with the always_populate_raw_post_data
I first run grep
:
grep -n 'always_populate_raw_post_data' php.ini
That returned the line 704
704:;always_populate_raw_post_data = -1
Then simply open php.ini
on that line with vi
editor:
vi +704 php.ini
Remove the semi colon to uncomment it and save the file :wq
Lastly reboot the server and the error went away.
How about something like this...
Dim rs As RecordSet
Set rs = Currentdb.OpenRecordSet("SELECT PictureLocation, ID FROM MyAccessTable;")
Do While Not rs.EOF
Debug.Print rs("PictureLocation") & " - " & rs("ID")
rs.MoveNext
Loop
You can also use map:
a = [1, 1, 1, 1, 1]
b = 1
list(map(lambda x: x + b, a))
It gives:
[2, 2, 2, 2, 2]
Use a Java 8 Stream
.
myString.chars().mapToObj(i -> (char) i).collect(Collectors.toList());
Breakdown:
myString
.chars() // Convert to an IntStream
.mapToObj(i -> (char) i) // Convert int to char, which gets boxed to Character
.collect(Collectors.toList()); // Collect in a List<Character>
(I have absolutely no idea why String#chars()
returns an IntStream
.)
Here is one neat way with easy to understand algorithm.
import copy
nums = [2,3,4,5]
subsets = [[]]
for n in nums:
prev = copy.deepcopy(subsets)
[k.append(n) for k in subsets]
subsets.extend(prev)
print(subsets)
print(len(subsets))
# [[2, 3, 4, 5], [3, 4, 5], [2, 4, 5], [4, 5], [2, 3, 5], [3, 5], [2, 5], [5],
# [2, 3, 4], [3, 4], [2, 4], [4], [2, 3], [3], [2], []]
# 16 (2^len(nums))
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
To specifically answer a part of your question "Is there any situation in which it would be better to use one or the other?", consider a form with repeating sections. If the repeating section contains many select
tags, then the option
s must be rendered for each select, for every row.
In such a case, I would consider using datalist
with input
, because the same datalist
can be used for any number of input
s. This could potentially save a large amount of rendering time on the server, and would scale much better to any number of rows.
thelist.Max(e => e.age);
If you don't want to add id's to your data, you could track by the index in the array, which will cause the items to be keyed by their position in the array instead of their value.
Like this:
var myArray = [1,1,1,1,1];
<li ng-repeat="item in myArray track by $index">
or even a very classic old fashion method
IEnumerable<string> collection = new List<string>() { "a", "b", "c" };
for(int i = 0; i < collection.Count(); i++)
{
string str1 = collection.ElementAt(i);
// do your stuff
}
maybe you would like this method also :-)
I tried all of the above and if that doesn't work for you try the below CSS resolved the issue for me. Which just tells the browsers to not add any padding or margin.
* {
padding:0px;
margin:0px;
}
Even in base Python you can do the computation in generic form
result = sum(x**2 for x in some_vector) ** 0.5
x ** 2
is surely not an hack and the computation performed is the same (I checked with cpython source code). I actually find it more readable (and readability counts).
Using instead x ** 0.5
to take the square root doesn't do the exact same computations as math.sqrt
as the former (probably) is computed using logarithms and the latter (probably) using the specific numeric instruction of the math processor.
I often use x ** 0.5
simply because I don't want to add math
just for that. I'd expect however a specific instruction for the square root to work better (more accurately) than a multi-step operation with logarithms.
You can use the length()
method on File
which returns the size in bytes.
A Python solution:
python -c "import sys; print('\n'.join(' '.join(c) for c in zip(*(l.split() for l in sys.stdin.readlines() if l.strip()))))" < input > output
The above is based on the following:
import sys
for c in zip(*(l.split() for l in sys.stdin.readlines() if l.strip())):
print(' '.join(c))
This code does assume that every line has the same number of columns (no padding is performed).
The easiest way to change the background color of the jumbotron
If you want to change the background color of your jumbotron, then for that you can apply a background color to it using one of your custom class.
HTML Code:
<div class="jumbotron myclass">
<h1>My Heading</h1>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
</div>
CSS Code:
<style>
.myclass{
background-color: red;
}
</style>
One more version... (I think this one is pretty good)
static float NextFloat(Random random)
{
(float)(float.MaxValue * 2.0 * (rand.NextDouble()-0.5));
}
//inline version
float myVal = (float)(float.MaxValue * 2.0 * (rand.NextDouble()-0.5));
I think this...
And One more version...(not as good but posting anyway)
static float NextFloat(Random random)
{
return float.MaxValue * ((rand.Next() / 1073741824.0f) - 1.0f);
}
//inline version
float myVal = (float.MaxValue * ((rand.Next() / 1073741824.0f) - 1.0f));
I think this...
Testing of most of the functions on this page: (i7, release, without debug, 2^28 loops)
Sunsetquest1: min: 3.402823E+38 max: -3.402823E+38 time: 3096ms
SimonMourier: min: 3.402823E+38 max: -3.402819E+38 time: 14473ms
AnthonyPegram:min: 3.402823E+38 max: -3.402823E+38 time: 3191ms
JonSkeet: min: 3.402823E+38 max: -3.402823E+38 time: 3186ms
Sixlettervar: min: 1.701405E+38 max: -1.701410E+38 time: 19653ms
Sunsetquest2: min: 3.402823E+38 max: -3.402823E+38 time: 2930ms
If you have to use a distutils setup.py
script, there are some commandline options for forcing an installation destination. See http://docs.python.org/install/index.html#alternate-installation. If this problem repeats, you can setup a distutils configuration file, see http://docs.python.org/install/index.html#inst-config-files.
Setting the PYTHONPATH variable is described in tihos post.
My "DerivedData" with Xcode 10.2 and Mojave was here:
MacHD/Users/[MyUser]/Library/Developer/Xcode
string1=" This is Test String to strip leading space"
print string1
print string1.lstrip()
string2="This is Test String to strip trailing space "
print string2
print string2.rstrip()
string3=" This is Test String to strip leading and trailing space "
print string3
print string3.strip()
string4=" This is Test String to test all the spaces "
print string4
print string4.replace(" ", "")
to chnage line endings from LF to CRLF:
open Sublime and follow the steps:-
1 press Ctrl+shift+p then install package name line unify endings
then again press Ctrl+shift+p
2 in the blank input box type "Line unify ending "
3 Hit enter twice
Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF
If your column with DATE datatype has value like below : -
value in column : 10-NOV-2005 06:31:00
Then, You can Use TRUNC function in select query to convert your date-time value to only date like - DD/MM/YYYY or DD-MON-YYYY
select TRUNC(column_1) from table1;
result : 10-NOV-2005
You will see above result - Provided that NLS_DATE_FORMAT is set as like below :-
Alter session NLS_DATE_FORMAT = 'DD-MON-YYYY HH24:MI:SS';
in my case i click on recent apps shortcut on my cell phone and close all apps. This solution always work for me, because this error not related to code.
Try these steps:
cd /ios
pod install
This was what worked for me.
This will help you to overcome overflow: overlay
issues as well.
.div{
height: 300px;
overflow: auto;
visibility: hidden;
}
.div-content,
.div:hover {
visibility: visible;
}
Utilizing/Copying Darin Dimitrov's great response, this is how to access a custom attribute on a property and not a class:
The decorated property [of class Foo
]:
[MyCustomAttribute(SomeProperty = "This is a custom property")]
public string MyProperty { get; set; }
Fetching it:
PropertyInfo propertyInfo = typeof(Foo).GetProperty(propertyToCheck);
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
}
You can throw this in a loop and use reflection to access this custom attribute on each property of class Foo
, as well:
foreach (PropertyInfo propertyInfo in Foo.GetType().GetProperties())
{
string propertyName = propertyInfo.Name;
object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyCustomAttribute), true);
// Just in case you have a property without this annotation
if (attribute.Length > 0)
{
MyCustomAttribute myAttribute = (MyCustomAttribute)attribute[0];
string propertyValue = myAttribute.SomeProperty;
// TODO: whatever you need with this propertyValue
}
}
Major thanks to you, Darin!!
I just posted this on Disable Submit button until Input fields filled in. Works for me.
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}
In my case, web server prevented "OPTIONS" method
Check your web server for the options method
I'm using "webtier"
/www/webtier/domains/[domainname]/config/fmwconfig/components/OHS/VCWeb1/httpd.conf
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{REQUEST_METHOD} ^OPTIONS
RewriteRule .* . [F]
</IfModule>
change to
<IfModule mod_rewrite.c>
RewriteEngine off
RewriteCond %{REQUEST_METHOD} ^OPTIONS
RewriteRule .* . [F]
</IfModule>
The following should work as long as you're bound to anything that implements IEnumerable<string>. It will bind the column directly to the string itself, rather than to a Property Path of that string object.
<sdk:DataGridTextColumn Binding="{Binding}" />
I use it to amend more than just the last commit.
Let's say I made a mistake in commit A and then made commit B. Now I can only amend B.
So I do git reset --soft HEAD^^
, I correct and re-commit A and then re-commit B.
Of course, it's not very convenient for large commits… but you shouldn't do large commits anyway ;-)
Try
df.loc[df.my_channel > 20000, 'my_channel'] = 0
Note: Since v0.20.0, ix
has been deprecated in favour of loc
/ iloc
.
It is very simple. Just go to Edit=>Line=>Reindent
xcode-select --install
worked for me
This may seem a bit lengthy, but it worked for me without any error.
At first, Install phppgadmin from Ubuntu Software Center.
Then run these steps in terminal.
sudo apt-get install libpq-dev python-dev
pip install psycopg2
sudo apt-get install postgresql postgresql-contrib phppgadmin
Start the apache server
sudo service apache2 start
Now run this too in terminal, to edit the apache file.
sudo gedit /etc/apache2/apache2.conf
Add the following line to the opened file:
Include /etc/apache2/conf.d/phppgadmin
Now reload apache. Use terminal.
sudo /etc/init.d/apache2 reload
Now you will have to create a new database. Login as 'postgres' user. Continue in terminal.
sudo su - postgres
In case you have trouble with the password of 'postgres', you can change it using the answer here https://stackoverflow.com/a/12721020/1990793 and continue with the steps.
Now create a database
createdb <db_name>
Now create a new user to login to phppgadmin later, providing a new password.
createuser -P <new_user>
Now your postgressql has been setup, and you can go to:
http://localhost/phppgadmin/
and login using the new user you've created, in order to view the database.
The reason expr[expr[2] == 'hesc']
doesn't work is that for a data frame, x[y]
selects columns, not rows. If you want to select rows, change to the syntax x[y,]
instead:
> expr[expr[2] == 'hesc',]
expr_value cell_type
4 5.929771 hesc
5 5.873096 hesc
6 5.665857 hesc
Best aproach for me was:
private void grid_receptie_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
int X = 1;
foreach(DataGridViewRow row in grid_receptie.Rows)
{
row.Cells["NR_CRT"].Value = X;
X++;
}
}
^$ -- regex to accept empty string.And it wont match "/n" or "foobar/n" as you mentioned. You could test this regex on https://www.regextester.com/1924.
If you have your existing regex use or(|) in your regex to match empty string. For example /^[A-Za-z0-9&._ ]+$|^$/
Another way to address the timezone issue if you want to set the default timezone for the entire script to a certian timezone is to use
date_default_timezone_set()
then use one of the supported timezones.
Step Into The next expression on the currently-selected line to be executed is invoked, and execution suspends at the next executable line in the method that is invoked.
Step Over The currently-selected line is executed and suspends on the next executable line.
First of all, I don't see the reason for having an ID that's not unique, but I guess it's an ID that connects to another table. Second there is no need for subqueries, which beats up the server. You do this in one query, like this
SELECT id,GROUP_CONCAT(name, ':', value SEPARATOR "|") FROM sample GROUP BY id
You get fast and correct results, and you can split the result by that SEPARATOR "|". I always use this separator, because it's impossible to find it inside a string, therefor it's unique. There is no problem having two A's, you identify only the value. Or you can have one more colum, with the letter, which is even better. Like this :
SELECT id,GROUP_CONCAT(DISTINCT(name)), GROUP_CONCAT(value SEPARATOR "|") FROM sample GROUP BY name
if you're uncomfortable with returning addresses and have just a single variable eg. an integer value to return, you can even typecast it into (void *) before passing it, and then when you collect it in the main, again typecast it into (int). You have the value without throwing up ugly warnings.
If you look at the scope of the variable 'hoursWorked' you will see that it is a member of the class (declared as private int)
The two variables you are having trouble with are passed as parameters to the constructor.
The error message is because 'hours' is out of scope in the setter.
I manage to find the answer for this solution, have to do javascript injection for this to install atob
const atob:any = require('atob');
asn1(pem: any){
asn1parser.Enc.base64ToBuf = function (b64:any) {
return asn1parser.Enc.binToBuf(atob(b64));
};
const dertest = asn1parser.PEM.parseBlock(pem).der;
var hex = asn1parser.Enc.bufToHex(asn1parser.PEM.parseBlock(pem).der)
var buf = asn1parser.ASN1.parse(dertest);
var asn1 = JSON.stringify(asn1parser.ASN1.parse(dertest), asn1parser.ASN1._replacer, 2 );
If you are working on your own, and you want the closest thing to OOP as you would find in Java or C# or C++, see the javascript library, CrxOop. CrxOop provides syntax somewhat familiar to Java developers.
Just be careful, Java's OOP is not the same as that found in Javascript. To get the same behavior as in Java, use CrxOop's classes, not CrxOop's structures, and make sure all your methods are virtual. An example of the syntax is,
crx_registerClass("ExampleClass",
{
"VERBOSE": 1,
"public var publicVar": 5,
"private var privateVar": 7,
"public virtual function publicVirtualFunction": function(x)
{
this.publicVar1 = x;
console.log("publicVirtualFunction");
},
"private virtual function privatePureVirtualFunction": 0,
"protected virtual final function protectedVirtualFinalFunction": function()
{
console.log("protectedVirtualFinalFunction");
}
});
crx_registerClass("ExampleSubClass",
{
VERBOSE: 1,
EXTENDS: "ExampleClass",
"public var publicVar": 2,
"private virtual function privatePureVirtualFunction": function(x)
{
this.PARENT.CONSTRUCT(pA);
console.log("ExampleSubClass::privatePureVirtualFunction");
}
});
var gExampleSubClass = crx_new("ExampleSubClass", 4);
console.log(gExampleSubClass.publicVar);
console.log(gExampleSubClass.CAST("ExampleClass").publicVar);
The code is pure javascript, no transpiling. The example is taken from a number of examples from the official documentation.
@therefromhere's answer is the best one. However Node versions have moved ever onwards and upwards, and the versioning was complicated by the remerge of io.js. Following the steps in his answer, you will end up with Node version 0.10.25
- not the most recent version.
You should still purge any existing node/npm packages with
sudo apt-get purge nodejs npm
and then go and look at the nodesource deb install page at https://github.com/nodesource/distributions#debinstall.
All Node.js versions are listed on the above page with the Linux commands to install them. And these packages will work on both Debian and Ubuntu.
P.S. If you want to run Node v4.4 or higher on Ubuntu Precise or Debian Wheezy, you should review the information about running on older distros.
P.P.S. If your apt-get is failing, the script will not complete (Google references were failing my apt-get update
). You should see messages about the NodeSource signing key being added to your keyring and a final message instructing you to Run 'apt-get install nodejs' to install Node.js
.
P.P.P.S. npm is installed with node. Once installed, you can update to the latest npm with sudo npm install npm -g
use overflow:auto
it will give a scroller to your text within the div
:).
In addition to:
myFilePath = replace(myFilePath, "/", "\")
myFilePath = replace(myFilePath, "http:", "")
also replace space:
myFilePath = replace(myFilePath, " ", "%20")
What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.
If you load the search criteria from elsewhere, then you should probably have some mapping logic.
If you are using Mercurial, this is done via "import". So at the command line, the hg import
command, or (you may find the --no-commit
option useful), or "Repository" => "Import..." in Hg Workbench.
Note that these will commit the changes by default; you can avoid this using hg import --no-commit
option if using the command-line, or if you used Hg Workbench, you might find it useful to issue hg rollback
after the merge.
If the Java way is the OO way, then yes, creating a class with public fields breaks the principles around information hiding which say that an object should manage its own internal state. (So as I'm not just spouting jargon at you, a benefit of information hiding is that the internal workings of a class are hidden behind an interface - say you wanted to change the mechanism by which your struct class saved one of its fields, you'll probably need to go back and change any classes that use the class...)
You also can't take advantage of the support for JavaBean naming compliant classes, which will hurt if you decide to, say, use the class in a JavaServer Page which is written using Expression Language.
The JavaWorld article Why Getter and Setter Methods are Evil article also might be of interest to you in thinking about when not to implement accessor and mutator methods.
If you're writing a small solution and want to minimise the amount of code involved, the Java way may not be the right way - I guess it always depends on you and the problem you're trying to solve.
Try that:
foreach ($images[1] as $key => &$image) {
if (yourConditionGoesHere) {
unset($images[1][$key])
}
}
unset($image); // detach reference after loop
Normally, foreach
operates on a copy of your array so any changes you make, are made to that copy and don't affect the actual array.
So you need to unset the values via $images[$key]
;
The reference on &$image
prevents the loop from creating a copy of the array which would waste memory.
You could include .PDB
symbol files associated to the assembly which contain metadata information and when an exception is thrown it will contain full information in the stacktrace of where this exception originated. It will contain line numbers of each method in the stack.
If you have perl installed, then perl -i -n -e"print unless m{(ERROR|REFERENCE)}"
should do the trick.
Here's the method I use:
public void AddOrUpdateAppConnectionStrings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.ConnectionStrings.ConnectionStrings;
if (settings[key] == null)
{
settings.Add(new ConnectionStringSettings(key,value));
}
else
{
settings[key].ConnectionString = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.ConnectionStrings.SectionInformation.Name);
Properties.Settings.Default.Reload();
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
You can try DBVisualizer some features are not free, but you can get an evaluate license...