The problem was that the test runner, is configured to not run tests from a remote drive. When I copied the project to a local drive it worked fine, but I needed it on a shared drive (can not remember why).
I read that it can be configured to work from a shared drive, but never got to do it as by the time I discovered the solution I had switched to MonoDevelop on Debian.
let originalString = "http://www.ihtc.cc?name=htc&title=iOS?????"
1. encodingQuery:
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
result:
"http://www.ihtc.cc?name=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
2. encodingURL:
let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
result:
"http:%2F%2Fwww.ihtc.cc%3Fname=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
This error can occur if there are syntax errors with Derived Query Methods. For example, if there are some mismatches with entity class fields and the Derived methods' names.
You can make a json object like:
globalVariable={example_attribute:"SomeValue"};
in fileA.js
And access it from fileB.js like:
globalVariable.example_attribute
**multiple delete not working**
function delete_selection()
{
$id_array = array();
$selection = $this->input->post("selection", TRUE);
$id_array = explode("|", $selection);
foreach ($id_array as $item):
if ($item != ''):
//DELETE ROW
$this->db->where('entry_id', $item);
$this->db->delete('helpline_entry');
endif;
endforeach;
}
Try this:
// convert from bitmap to byte array
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
// get the base 64 string
String imgString = Base64.encodeToString(getBytesFromBitmap(someImg),
Base64.NO_WRAP);
The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)
Example
a = int('0x100', 16)
print(a) #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100
This is simple program showing append('t') to the list.
n=['f','g','h','i','k']
for i in range(1):
temp=[]
temp.append(n[-2:])
temp.append('t')
print(temp)
Output: [['i', 'k'], 't']
Add a Primary Key (code below)
Run the correct delete (code below)
Consider WHY you woudln't want to keep that primary key.
Assuming MSSQL or compatible:
ALTER TABLE Employee ADD EmployeeID int identity(1,1) PRIMARY KEY;
WHILE EXISTS (SELECT COUNT(*) FROM Employee GROUP BY EmpID, EmpSSN HAVING COUNT(*) > 1)
BEGIN
DELETE FROM Employee WHERE EmployeeID IN
(
SELECT MIN(EmployeeID) as [DeleteID]
FROM Employee
GROUP BY EmpID, EmpSSN
HAVING COUNT(*) > 1
)
END
In your config.ini
file of eclipse eclipse\configuration\config.ini
check this three things:
osgi.framework=file\:plugins\\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
osgi.bundles=reference\:file\:org.eclipse.equinox.simpleconfigurator_1.0.0.v20080604.jar@1\:start
org.eclipse.equinox.simpleconfigurator.configUrl=file\:org.eclipse.equinox.simpleconfigurator\\bundles.info
And check whether these jars are in place or not, the jar files depend upon your version of eclipse .
You seem to be using Python as if it were the shell. Whenever I've needed to do something like what you're doing, I've used os.walk()
For example, as explained here: [x[0] for x in os.walk(directory)]
should give you all of the subdirectories, recursively.
I tried all the suggestions and nothing works for me.
Imagine the situation: you need a 2-way binding and you have a lookup with NUMBER values and you want to fill your SELECT with the values from this lookup and highlight the chosen option.
Using [value] or (ngModelChange) is a no-go, because you won't be able to select the chosen option after user initiated the change: [value] considers everything a string, as to (ngModelChange) - it obviously should not be used when user initiates the change, so it ruins the proper selection. Using [ngModel] guarantees the fixed format of received VALUE as INDEX: VALUE and it's easy to parse it correspondingly, HOWEVER once again - it ruins the selected option.
So we go with [ngValue] (which will take care of proper types), (change) and... [value], which guarantees the handler receives VALUE, not a DISPLAYED VALUE or INDEX: VALUE :) Below is my working clumsy solution:
<select
class="browser-default custom-select"
(change)="onEdit($event.target.value)"
>
<option [value]="">{{
'::Licences:SelectLicence' | abpLocalization
}}</option>
<ng-container *ngIf="licencesLookupData$ | async">
<option
*ngFor="let l of licencesLookupData$ | async"
[ngValue]="l.id"
[value]="l.id"
[selected]="l.id == selected.id"
>
{{ l.id }} {{ l.displayName | defaultValue }}
</option>
</ng-container>
</select>
onEdit(idString: string) {
const id = Number(idString);
if (isNaN(id)) {
this.onAdd();
return;
}
this.licencesLoading = true;
this.licencesService
.getById(id)
.pipe(finalize(() => (this.licencesLoading = false)), takeUntil(this.destroy))
.subscribe((state: Licences.LicenceWithFlatProperties) => {
this.selected = state;
this.buildForm();
this.get();
});
}
You also can use git filter-branch
for that.
git filter-branch -f --msg-filter "sed 's/errror/error/'" $flawed_commit..HEAD
It's not as easy as a trivial git commit --amend
, but it's especially useful, if you already have some merges after your erroneous commit message.
Note that this will try to rewrite every commit between HEAD
and the flawed commit, so you should choose your msg-filter
command very wisely ;-)
The parentheses are misplaced:
SELECT setval('payments_id_seq', 21, true); # next value will be 22
Otherwise you're calling setval
with a single argument, while it requires two or three.
Like Unix shells, PowerShell supports >
redirects with most of the variations known from Unix, including 2>&1
(though weirdly, order doesn't matter - 2>&1 > file
works just like the normal > file 2>&1
).
Like most modern Unix shells, PowerShell also has a shortcut for redirecting both standard error and standard output to the same device, though unlike other redirection shortcuts that follow pretty much the Unix convention, the capture all shortcut uses a new sigil and is written like so: *>
.
So your implementation might be:
& myjob.bat *>> $logfile
The approach you should take is to install pip
for Python 3.2.
You do this in the following way:
$ curl -O https://bootstrap.pypa.io/get-pip.py
$ sudo python3.2 get-pip.py
Then, you can install things for Python 3.2 with pip-3.2
, and install things for Python 2-7 with pip-2.7
. The pip
command will end up pointing to one of these, but I'm not sure which, so you will have to check.
CSS
ol {
margin: 0 0 1.5em;
padding: 0;
counter-reset: item;
}
ol > li {
margin: 0;
padding: 0 0 0 2em;
text-indent: -2em;
list-style-type: none;
counter-increment: item;
}
ol > li:before {
display: inline-block;
width: 1em;
padding-right: 0.5em;
font-weight: bold;
text-align: right;
content: counter(item) ".";
}
Follow the steps that are described on this answer just instead of using the drop down, type the port (8787) in "port range" an then "Add rule".
Go to the "Network & Security" -> Security Group settings in the left hand navigation
Find the Security Group that your instance is apart of Click on Inbound Rules Use the drop down and add HTTP (port 80) Click Apply and enjoy
Assuming you want an actual SQL Server MERGE
statement:
MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
ON target.webmeterID = source.webmeterID
AND target.DateTime = source.DateTime
WHEN MATCHED THEN
UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
INSERT (webmeterID, DateTime, kWh)
VALUES (source.webmeterID, source.DateTime, source.kWh);
If you also want to delete records in the target that aren't in the source:
MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
USING dbo.temp_energydata AS source
ON target.webmeterID = source.webmeterID
AND target.DateTime = source.DateTime
WHEN MATCHED THEN
UPDATE SET target.kWh = source.kWh
WHEN NOT MATCHED BY TARGET THEN
INSERT (webmeterID, DateTime, kWh)
VALUES (source.webmeterID, source.DateTime, source.kWh)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
Because this has become a bit more popular, I feel like I should expand this answer a bit with some caveats to be aware of.
First, there are several blogs which report concurrency issues with the MERGE
statement in older versions of SQL Server. I do not know if this issue has ever been addressed in later editions. Either way, this can largely be worked around by specifying the HOLDLOCK
or SERIALIZABLE
lock hint:
MERGE INTO dbo.energydata WITH (HOLDLOCK) AS target
[...]
You can also accomplish the same thing with more restrictive transaction isolation levels.
There are several other known issues with MERGE
. (Note that since Microsoft nuked Connect and didn't link issues in the old system to issues in the new system, these older issues are hard to track down. Thanks, Microsoft!) From what I can tell, most of them are not common problems or can be worked around with the same locking hints as above, but I haven't tested them.
As it is, even though I've never had any problems with the MERGE
statement myself, I always use the WITH (HOLDLOCK)
hint now, and I prefer to use the statement only in the most straightforward of cases.
ES5 Object.keys
var a = { a: 1, b: 2, c: 3 };
Object.keys(a).map(function(key){ return a[key] });
// result: [1,2,3]
Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.
So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title
attribute).
There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.
On the other hand, in HTML 5 you have two options:
input of type number
:
<input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
– only validates the range – if user enters a non-number, an empty value is submitted
– the field visual is enhanced with increment / decrement controls (browser dependent)
the pattern
attribute:
<input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
<input type="text" pattern="\d{3}" title="Format: 3 digits" />
– this gives you a full contorl over the format (anything you can specify by regular expression)
– no visual difference / enhancement
But here you still rely on browser capabilities, so do a server-side validation in either case.
some thing as follows ::
Add this After the body tag
This is a rough sketch, you will need to modify it according to your needs.
<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");
var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");
f.appendChild(i);
f.appendChild(s);
//and some more input elements here
//and dont forget to add a submit button
document.getElementsByTagName('body')[0].appendChild(f);
</script>
Just from reading that i would have never understood that "$@"
expands into a list of separate parameters. Whereas, "$*"
is one parameter consisting of all the parameters added together.
If it still makes no sense do this.
http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/
Had the exact same problem and none of the answers here helped me. Till I find this thread and post
Short: win32 modules are not guaranted to install correctly with pip. Install them directly from packages provided by developpers on github. It works like a charm.
You might want to take a look at HERE MAP SERVICE. They have direct traffic data you can use, which is exactly what you need: https://developer.here.com/api-explorer/rest/traffic/traffic-flow-bounding-box
For example, by querying an area of interest, you might get something like this:
{
"RWS": [
{
"RW": [
{
"FIS": [
{
"FI": [
{
"TMC": {
"PC": 32483,
"DE": "SOHO",
"QD": "+",
"LE": 0.71682
},
"CF": [
{
"TY": "TR",
"SP": 9.1,
"SU": 9.1,
"FF": 17,
"JF": 3.2911,
"CN": 0.9
}
]
}
]
}
],
....
This example shows a current average speed SU
of 9.1, where the free flow speed FF
would be 17. The Jam factor JF
is 3.3, which is still considered free flow but getting sluggish.
The units used (miles/km) can be defined in the API call.
To avoid dealing with TMC locations, you can ask for geocoordinates of the road segments by adding responseattributes=sh
in the request.
The abbreviations used can be found here Interpreting HERE Maps real-time traffic tags:
- "RWS" - A list of Roadway (RW) items
- "RW" = This is the composite item for flow across an entire roadway. A roadway item will be present for each roadway with traffic flow information available
- "FIS" = A list of Flow Item (FI) elements
- "FI" = A single flow item
- "TMC" = An ordered collection of TMC locations
- "PC" = Point TMC Location Code
- "DE" = Text description of the road
- "QD" = Queuing direction. '+' or '-'. Note this is the opposite of the travel direction in the fully qualified ID, For example for location 107+03021 the QD would be '-'
- "LE" = Length of the stretch of road. The units are defined in the file header
- "CF" = Current Flow. This element contains details about speed and Jam Factor information for the given flow item.
- "CN" = Confidence, an indication of how the speed was determined. -1.0 road closed. 1.0=100% 0.7-100% Historical Usually a value between .7 and 1.0 "FF" = The free flow speed on this
stretch of road.- "JF" = The number between 0.0 and 10.0 indicating the expected quality of travel. When there is a road closure, the Jam Factor will be 10. As the number approaches 10.0 the quality of travel is getting worse. -1.0 indicates that a Jam Factor could not be calculated
- "SP" = Speed (based on UNITS) capped by speed limit
- "SU" = Speed (based on UNITS) not capped by speed limit
- "TY" = Type information for the given Location Referencing container. This may be freely defined string
Also the source comes from https://developer.here.com/rest-apis/documentation/traffic/topics/additional-parameters.html
$(document).ready(function () {
$('#count_my_data').click(function () {
var count = 0;
while (true) {
try {
var v1 = mydata[count].TechnologyId.toString();
count = count + 1;
}
catch (e)
{ break; }
}
alert(count);
});
});
useEffect
can hook on a certain prop or state. so, the thing you need to do to avoid infinite loop hook is binding some variable or state to effect
For Example:
useEffect(myeffectCallback, [])
above effect will fire only once the component has rendered. this is similar to componentDidMount
lifecycle
const [something, setSomething] = withState(0)
const [myState, setMyState] = withState(0)
useEffect(() => {
setSomething(0)
}, myState)
above effect will fire only my state has changed this is similar to componentDidUpdate
except not every changing state will fire it.
You can read more detail though this link
The error is:
Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])
In JSON, platforms
look like this:
"platforms": [
{
"platform": "iphone"
},
{
"platform": "ipad"
},
{
"platform": "android_phone"
},
{
"platform": "android_tablet"
}
]
So try change your pojo to something like this:
private List platforms;
public List getPlatforms(){
return this.platforms;
}
public void setPlatforms(List platforms){
this.platforms = platforms;
}
EDIT: you will need change mobile_networks
too. Will look like this:
private List mobile_networks;
public List getMobile_networks() {
return mobile_networks;
}
public void setMobile_networks(List mobile_networks) {
this.mobile_networks = mobile_networks;
}
I gave up and inserted a simple jQuery code as below. This will add a tr after every tr, if you have so many trs like me. Demo: https://jsfiddle.net/acf9sph6/
<table>
<tbody>
<tr class="my-tr">
<td>one line</td>
</tr>
<tr class="my-tr">
<td>one line</td>
</tr>
<tr class="my-tr">
<td>one line</td>
</tr>
</tbody>
</table>
<script>
$(function () {
$("tr.my-tr").after('<tr class="tr-spacer"/>');
});
</script>
<style>
.tr-spacer
{
height: 20px;
}
</style>
remove partition by
and add group by
clause,
SELECT BrandId
,SUM(ICount) totalSum
FROM Table
WHERE DateId = 20130618
GROUP BY BrandId
Override all single element
$("*").css("cursor", "progress");
list[-1]
will retrieve the last element of the list without changing the list.
list.pop()
will retrieve the last element of the list, but it will mutate/change the original list. Usually, mutating the original list is not recommended.
Alternatively, if, for some reason, you're looking for something less pythonic, you could use list[len(list)-1]
, assuming the list is not empty.
I use method 3 because it's the most understandable for others (whenever you see an <a>
tag, you know it's a link) and when you are part of a team, you have to make simple things ;).
And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.
I got the same error and figured out that i wrote my script using Anaconda but pyinstaller
tries to pack script on pure python. So, modules not exist in pythons library folder cause this problem.
add setOnItemSelectedListener to spinner reference and get the data like that`
mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
selectedSize=adapterView.getItemAtPosition(position).toString();
This code provides nearly full randomness:
function generator() {_x000D_
const ran = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {_x000D_
ren = Math.random();_x000D_
if (ren == 0.5) return 0;_x000D_
return ren > 0.5 ? 1 : -1_x000D_
})_x000D_
return Array(6).fill(null).map(x => ran()[(Math.random() * 9).toFixed()]).join('')_x000D_
}_x000D_
_x000D_
console.log(generator())
_x000D_
This code provides complete randomness:
function generator() {_x000D_
_x000D_
const ran1 = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {_x000D_
ren = Math.random();_x000D_
if (ren == 0.5) return 0;_x000D_
return ren > 0.5 ? 1 : -1_x000D_
})_x000D_
const ran2 = () => ran1().sort((x, z) => {_x000D_
ren = Math.random();_x000D_
if (ren == 0.5) return 0;_x000D_
return ren > 0.5 ? 1 : -1_x000D_
})_x000D_
_x000D_
return Array(6).fill(null).map(x => ran2()[(Math.random() * 9).toFixed()]).join('')_x000D_
}_x000D_
_x000D_
console.log(generator())
_x000D_
Try it from
ftp://ip_my_s5:2221/mnt/sdcard/Pictures/Screenshots
which point onto /storage/emulated/0
You can use implicit transactions for this
SET IMPLICIT_TRANSACTIONS ON
update Staff set staff_Name='jas' where staff_id=7
ROLLBACK
As you request-- You can SET this setting ( SET IMPLICIT_TRANSACTIONS ON
) from a stored procedure by setting that stored procedure as the start up procedure.
But SET IMPLICIT TRANSACTION ON
command is connection specific. So any connection other than the one which running the start up stored procedure will not benefit from the setting you set.
2^31-1 bytes. So, a little less than 2^31-1 characters for varchar(max) and half that for nvarchar(max).
use
npm config set registry http://registry.npmjs.org/
so that npm requests for http
url instead of https
.
and then try the same npm install
command
A SQLite database is a regular file. It is created in your script current directory.
Firstly freq_series.plot
returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax
rather than fig
to be more consistent with other code examples.
You can get the list of the bars produced in the plot from the ax.patches
member. Then you can use the technique demonstrated in this matplotlib
gallery example to add the labels using the ax.text
method.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that,
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)
x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
121740.0, 123980.0, 126220.0, 128460.0, 130700.0]
# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)
rects = ax.patches
# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
ha='center', va='bottom')
This produces a labeled plot that looks like:
char source[1000000];
FILE *fp = fopen("TheFile.txt", "r");
if(fp != NULL)
{
while((symbol = getc(fp)) != EOF)
{
strcat(source, &symbol);
}
fclose(fp);
}
There are quite a few things wrong with this code:
sizeof(source)
, this is prone to buffer overflows.The
strcat()
function appends a copy of the null-terminated string s2 to the end of the null-terminated string s1, then add a terminating `\0'.
You are appending a character (not a NUL-terminated string!) to a string that may or may not be NUL-terminated. The only time I can imagine this working according to the man-page description is if every character in the file is NUL-terminated, in which case this would be rather pointless. So yes, this is most definitely a terrible abuse of strcat()
.
The following are two alternatives to consider using instead.
If you know the maximum buffer size ahead of time:
#include <stdio.h>
#define MAXBUFLEN 1000000
char source[MAXBUFLEN + 1];
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
size_t newLen = fread(source, sizeof(char), MAXBUFLEN, fp);
if ( ferror( fp ) != 0 ) {
fputs("Error reading file", stderr);
} else {
source[newLen++] = '\0'; /* Just to be safe. */
}
fclose(fp);
}
Or, if you do not:
#include <stdio.h>
#include <stdlib.h>
char *source = NULL;
FILE *fp = fopen("foo.txt", "r");
if (fp != NULL) {
/* Go to the end of the file. */
if (fseek(fp, 0L, SEEK_END) == 0) {
/* Get the size of the file. */
long bufsize = ftell(fp);
if (bufsize == -1) { /* Error */ }
/* Allocate our buffer to that size. */
source = malloc(sizeof(char) * (bufsize + 1));
/* Go back to the start of the file. */
if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ }
/* Read the entire file into memory. */
size_t newLen = fread(source, sizeof(char), bufsize, fp);
if ( ferror( fp ) != 0 ) {
fputs("Error reading file", stderr);
} else {
source[newLen++] = '\0'; /* Just to be safe. */
}
}
fclose(fp);
}
free(source); /* Don't forget to call free() later! */
Here is a complete list of steps - you may not need steps 1-3 but am including them for completeness:-
vscode:extension/vscjava.vscode-java-pack
and then clicking on the green Install button after it opens in VS Code.mvn archetype:generate -DgroupId=
com.companyname.appname-DartifactId=
appname-DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
. This will create an appname folder with Maven's Standard Directory Layout (i.e. src/main/java/com/companyname/appname
and src/main/test/com/companyname/appname
to begin with and a sample "Hello World!" Java file named appname.java
and associated unit test named appnameTest.java
).*Tasks: Configure task
then select Create tasks.json from template
.Choose maven ("Executes common Maven commands"). This creates a tasks.json file with "verify" and "test" tasks. More can be added corresponding to other Maven Build Lifecycle phases. To specifically address your requirement for classes to be built without a JAR file, a "compile" task would need to be added as follows:
{
"label": "compile",
"type": "shell",
"command": "mvn -B compile",
"group": "build"
},
Save the above changes and then open the Command Palette and select "Tasks: Run Build Task" then pick "compile" and then "Continue without scanning the task output". This invokes Maven, which creates a target
folder at the same level as the src
folder with the compiled class files in the target\classes
folder.
Addendum: How to run/debug a class
Following a question in the comments, here are some steps for running/debugging:-
Simple. Just change the image orientation flag.
UIImage *oldImage = [UIImage imageNamed:@"whatever.jpg"];
UIImageOrientation newOrientation;
switch (oldImage.imageOrientation) {
case UIImageOrientationUp:
newOrientation = UIImageOrientationLandscapeLeft;
break;
case UIImageOrientationLandscapeLeft:
newOrientation = UIImageOrientationDown;
break;
case UIImageOrientationDown:
newOrientation = UIImageOrientationLandscapeRight;
break;
case UIImageOrientationLandscapeRight:
newOrientation = UIImageOrientationUp;
break;
// you can also handle mirrored orientations similarly ...
}
UIImage *rotatedImage = [UIImage imageWithCGImage:oldImage.CGImage scale:1.0f orientation:newOrientation];
You can only close a window using javascript that was opened using javascript, i.e. when the window was opened using :
window.open
then
window.close
will work. Or else not.
Lists are a mutable type - in order to create a copy (rather than just passing the same list around), you need to do so explicitly:
listoflists.append((list[:], list[0]))
However, list
is already the name of a Python built-in - it'd be better not to use that name for your variable. Here's a version that doesn't use list
as a variable name, and makes a copy:
listoflists = []
a_list = []
for i in range(0,10):
a_list.append(i)
if len(a_list)>3:
a_list.remove(a_list[0])
listoflists.append((list(a_list), a_list[0]))
print listoflists
Note that I demonstrated two different ways to make a copy of a list above: [:]
and list()
.
The first, [:]
, is creating a slice (normally often used for getting just part of a list), which happens to contain the entire list, and thus is effectively a copy of the list.
The second, list()
, is using the actual list
type constructor to create a new list which has contents equal to the first list. (I didn't use it in the first example because you were overwriting that name in your code - which is a good example of why you don't want to do that!)
you can use ClearContents. ex,
Range("X").Cells.ClearContents
If you're using Ubuntu, check out the pkgcreator project: http://code.google.com/p/pkgcreator
Here is the complete code
#include <bits/stdc++.h>
using namespace std;
typedef unsigned char BYTE;
int main() {
//method 1;
std::vector<BYTE> data = {'H','E','L','L','O','1','2','3'};
//string constructor accepts only const char
std::string s((const char*)&(data[0]), data.size());
std::cout << s << std::endl;
//method 2
std::string s2(data.begin(),data.end());
std::cout << s2 << std::endl;
//method 3
std::string s3(reinterpret_cast<char const*>(&data[0]), data.size()) ;
std::cout << s3 << std::endl;
return 0;
}
You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()
).
If so, just use unset()
:
unset($arr[1]);
http://www.astro.uu.nl/~strous/AA/en/reken/juliaansedag.html
If you can get the time converted from a Gregorian Date into Julian day number, you can just create an operator to do comparisons of the zulian day number, which can be type double to get months, days, seconds, etc. Check out the above link for an algorithm for converting from Gregorian to Julian.
Anything after the "vmargs" is taken to be vm arguments. Just make sure it's before that, which is the last piece in eclipse.ini.
Use this annotation
@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
Sample XML:
<X>
<Y ATTRIB1=attrib1_value ATTRIB2=attrib2_value/>
</X>
string xPath="/" + X + "/" + Y +
"[@" + ATTRIB1 + "='" + attrib1_value + "']" +
"[@" + ATTRIB2 + "='" + attrib2_value + "']"
XPath Testbed: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm
import java.time.LocalTime;
private String ConvertSecondToHHMMSSString(int nSecondTime) {
return LocalTime.MIN.plusSeconds(nSecondTime).toString();
}
There are two way
null
private int var;
can be initialized as private Integer var;
Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:
public GoBoard(){
this.linien = 9;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
public GoBoard(int pLinien){
this.linien = pLinien;
}
If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:
// default constructor
public GoBoard(){
this(9); // calls other constructor
}
public GoBoard(int pLinien){
this.linien = pLinien;
this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
}
edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,
class GoTest {
private static final int JB_WIDTH = 400;
private static final int JB_HEIGHT = JB_WIDTH;
private static void initGui() {
JFrame frame = new JFrame("GoBoard");
GoBoard jboard = new GoBoard();
jboard.setLayout(new BorderLayout(10, 10));
JPanel holdingPanel = new JPanel(new BorderLayout());
int eb = 20;
holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
holdingPanel.add(jboard, BorderLayout.CENTER);
frame.add(holdingPanel, BorderLayout.CENTER);
jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//!! frame.setSize(400, 400);
frame.pack();
frame.setVisible(true);
}
// .... etc....
One of the best compressors (not specifically an obfuscator) is the YUI Compressor.
If this error occurs while using Material UI <Typography>
https://material-ui.com/api/typography/, then you can easily change the <p>
to a <span>
by changing the value of the component
attribute of the <Typography>
element :
<Typography component={'span'} variant={'body2'}>
According to the typography docs:
component : The component used for the root node. Either a string to use a DOM element or a component. By default, it maps the variant to a good default headline component.
So Typography is picking <p>
as a sensible default, which you can change. May come with side effects ... worked for me.
As an addition to Yorro's answer, it can also be done by using attributes.
Sample for int
type unique key combination:
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }
If the data type is string
, then MaxLength
attribute must be added:
[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }
[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }
If there is a domain/storage model separation concern, using Metadatatype
attribute/class can be an option: https://msdn.microsoft.com/en-us/library/ff664465%28v=pandp.50%29.aspx?f=255&MSPPError=-2147217396
A quick console app example:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace EFIndexTest
{
class Program
{
static void Main(string[] args)
{
using (var context = new AppDbContext())
{
var newUser = new User { UniqueKeyIntPart1 = 1, UniqueKeyIntPart2 = 1, UniqueKeyStringPart1 = "A", UniqueKeyStringPart2 = "A" };
context.UserSet.Add(newUser);
context.SaveChanges();
}
}
}
[MetadataType(typeof(UserMetadata))]
public class User
{
public int Id { get; set; }
public int UniqueKeyIntPart1 { get; set; }
public int UniqueKeyIntPart2 { get; set; }
public string UniqueKeyStringPart1 { get; set; }
public string UniqueKeyStringPart2 { get; set; }
}
public class UserMetadata
{
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 1)]
public int UniqueKeyIntPart1 { get; set; }
[Index("IX_UniqueKeyInt", IsUnique = true, Order = 2)]
public int UniqueKeyIntPart2 { get; set; }
[Index("IX_UniqueKeyString", IsUnique = true, Order = 1)]
[MaxLength(50)]
public string UniqueKeyStringPart1 { get; set; }
[Index("IX_UniqueKeyString", IsUnique = true, Order = 2)]
[MaxLength(50)]
public string UniqueKeyStringPart2 { get; set; }
}
public class AppDbContext : DbContext
{
public virtual DbSet<User> UserSet { get; set; }
}
}
It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.
If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate
and colMeans
, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.
However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for
loop.
> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 >
So in your case, if you just wanted to print the mean of your Tandem
object 5 times:
for (ii in 1:5) { Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL) TandemMean <- mean(Tandem) print(TandemMean) }
As mentioned above, replicate
is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.
set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) { tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) } tandem[1] tandem[100] tandem[20:25]
...creates this output:
> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { + tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } > > tandem[1] [[1]] [1] 1.511923 > tandem[100] [[1]] [1] 1.496777 > tandem[20:25] [[1]] [1] 1.500669 [[2]] [1] 1.487552 [[3]] [1] 1.503409 [[4]] [1] 1.501362 [[5]] [1] 1.499728 [[6]] [1] 1.492798 >
The first argument to a shell script is available as the variable $1
, so the simplest implementation would be
if [ "$1" == "-h" ]; then
echo "Usage: `basename $0` [somestuff]"
exit 0
fi
But what anubhava said.
Adding the following on top of your JS file will tell JSHint to supress the radix warning:
/*jshint -W065 */
See also: http://jshint.com/docs/#options
You'll want to use the static method Character.toString(char c) to convert the character into a string first. Then you can use the normal string concatenation functions.
Use the fnReloadAjax() by the DataTables.net author.
I'm copying the source code below - in case the original ever moves:
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
if ( typeof sNewSource != 'undefined' && sNewSource != null )
{
oSettings.sAjaxSource = sNewSource;
}
this.oApi._fnProcessingDisplay( oSettings, true );
var that = this;
var iStart = oSettings._iDisplayStart;
var aData = [];
this.oApi._fnServerParams( oSettings, aData );
oSettings.fnServerData( oSettings.sAjaxSource, aData, function(json) {
/* Clear the old information from the table */
that.oApi._fnClearTable( oSettings );
/* Got the data - add it to the table */
var aData = (oSettings.sAjaxDataProp !== "") ?
that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
for ( var i=0 ; i<aData.length ; i++ )
{
that.oApi._fnAddData( oSettings, aData[i] );
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
that.fnDraw();
if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true )
{
oSettings._iDisplayStart = iStart;
that.fnDraw( false );
}
that.oApi._fnProcessingDisplay( oSettings, false );
/* Callback user function - for event handlers etc */
if ( typeof fnCallback == 'function' && fnCallback != null )
{
fnCallback( oSettings );
}
}, oSettings );
}
/* Example call to load a new file */
oTable.fnReloadAjax( 'media/examples_support/json_source2.txt' );
/* Example call to reload from original file */
oTable.fnReloadAjax();
On Debian-like distributions you set that in /etc/default/tomcat[67]
There is some faster way (https://www.youtube.com/watch?v=TSjEMLBAYVc):
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
In computer programming, particularly in the C, C++, and C# programming languages, a variable or object declared with the volatile
keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile
keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." (c) Wikipedia
I just downloaded xlrd, created an excel document (excel 2007) for testing and got the same error (message says 'found PK\x03\x04\x14\x00\x06\x00'). Extension is a xlsx. Tried saving it to an older .xls format and error disappears .....
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
Explanation:
Give it an absolute positioning (the parent should have relative positioning). Then, the upper left corner is moved to the center. Because you don't know the width/height yet, you use css transform to translate the position relatively to the middle. translate(-50%, -50%) does reduce the x and y position of the upper left corner by 50% of width and height.
I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
You can try this tool I made:
It converts to JSON, XML and others.
It's all client side, too, so your data never leaves your computer.
You could also reuse SwingConstants.{LEFT,RIGHT}. They are not enums, but they do already exist and are used in many places.
Yes, case insensitivity can be enabled and disabled at will in Java regex.
It looks like you want something like this:
System.out.println(
"Have a meRry MErrY Christmas ho Ho hO"
.replaceAll("(?i)\\b(\\w+)(\\s+\\1)+\\b", "$1")
);
// Have a meRry Christmas ho
Note that the embedded Pattern.CASE_INSENSITIVE
flag is (?i)
not \?i
. Note also that one superfluous \b
has been removed from the pattern.
The (?i)
is placed at the beginning of the pattern to enable case-insensitivity. In this particular case, it is not overridden later in the pattern, so in effect the whole pattern is case-insensitive.
It is worth noting that in fact you can limit case-insensitivity to only parts of the whole pattern. Thus, the question of where to put it really depends on the specification (although for this particular problem it doesn't matter since \w
is case-insensitive.
To demonstrate, here's a similar example of collapsing runs of letters like "AaAaaA"
to just "A"
.
System.out.println(
"AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
.replaceAll("(?i)\\b([A-Z])\\1+\\b", "$1")
); // A e I O u
Now suppose that we specify that the run should only be collapsed only if it starts with an uppercase letter. Then we must put the (?i)
in the appropriate place:
System.out.println(
"AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
.replaceAll("\\b([A-Z])(?i)\\1+\\b", "$1")
); // A eeEeeE I O uuUuUuu
More generally, you can enable and disable any flag within the pattern as you wish.
java.util.regex.Pattern
/regex/i
(Pattern.CASE_INSENSITIVE
in Java), you can do /(?i)regex/
/first(?i)second(?-i)third/
/first(?i:second)third/
\b
between a \w
and a \s
)In pthread_exit
, ret
is an input parameter. You are simply passing the address of a variable to the function.
In pthread_join
, ret
is an output parameter. You get back a value from the function. Such value can, for example, be set to NULL
.
Long explanation:
In pthread_join
, you get back the address passed to pthread_exit
by the finished thread. If you pass just a plain pointer, it is passed by value so you can't change where it is pointing to. To be able to change the value of the pointer passed to pthread_join, it must be passed as a pointer itself, that is, a pointer to a pointer.
Or you could figure out the exacting amount of hours and minutes and have that displayed by puttin it into the timer app that already exist in every iphone :)
Adding the following two lines at the top of my .py script worked for me (first line was necessary):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
If you are not limited to just a camera which wasn't in one of your constraints perhaps you can move to using a range sensor like the Xbox Kinect. With this you can perform depth and colour based matched segmentation of the image. This allows for faster separation of objects in the image. You can then use ICP matching or similar techniques to even match the shape of the can rather then just its outline or colour and given that it is cylindrical this may be a valid option for any orientation if you have a previous 3D scan of the target. These techniques are often quite quick especially when used for such a specific purpose which should solve your speed problem.
Also I could suggest, not necessarily for accuracy or speed but for fun you could use a trained neural network on your hue segmented image to identify the shape of the can. These are very fast and can often be up to 80/90% accurate. Training would be a little bit of a long process though as you would have to manually identify the can in each image.
check ur WebApiConfig and add this
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
Since Java 5, you can use java.util.concurrent.TimeUnit
to avoid the use of Magic Numbers like 1000 and 60 in your code.
By the way, you should take care to leap seconds in your computation: the last minute of a year may have an additional leap second so it indeed lasts 61 seconds instead of expected 60 seconds. The ISO specification even plan for possibly 61 seconds. You can find detail in java.util.Date
javadoc.
basically 32bit architecture can address 4GB as you expected. There are some techniques which allows processor to address more data like AWE or PAE.
You can have one alternative of using placeholders as:
@Query("Select c from Registration c where c.place LIKE %?1%")
List<Registration> findPlaceContainingKeywordAnywhere(String place);
Use Java 8's removeIf(),
To remove safely,
letters.removeIf(x -> !x.equals("A"));
using System;
using System.Net;
using System.Net.Mail;
namespace SendMailViaGmail
{
class Program
{
static void Main(string[] args)
{
//Specify senders gmail address
string SendersAddress = "[email protected]";
//Specify The Address You want to sent Email To(can be any valid email address)
string ReceiversAddress = "[email protected]";
//Specify The password of gmial account u are using to sent mail(pw of [email protected])
const string SendersPassword = "Password";
//Write the subject of ur mail
const string subject = "Testing";
//Write the contents of your mail
const string body = "Hi This Is my Mail From Gmail";
try
{
//we will use Smtp client which allows us to send email using SMTP Protocol
//i have specified the properties of SmtpClient smtp within{}
//gmails smtp server name is smtp.gmail.com and port number is 587
SmtpClient smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(SendersAddress, SendersPassword),
Timeout = 3000
};
//MailMessage represents a mail message
//it is 4 parameters(From,TO,subject,body)
MailMessage message = new MailMessage(SendersAddress, ReceiversAddress, subject, body);
/*WE use smtp sever we specified above to send the message(MailMessage message)*/
smtp.Send(message);
Console.WriteLine("Message Sent Successfully");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
}
}
Step 1 : npm install bootstrap --save
Step : 2 : Paste below code in angular.json node_modules/bootstrap/dist/css/bootstrap.min.css
Step 3 : ng serve
I had the same problem on Windows 7 64-bit Pro. I adjusted network adapters binding using Control panel but nothing changed. Also metrics where showing that Win should use Ethernet adapter as primary, but it didn't.
Then a tried to uninstall Ethernet adapter driver and then install it again (without restart) and then I checked metrics for sure.
After this, Windows started prioritize Ethernet adapter.
The correct content-type for JSON data is application/json
. I assume that is what you are missing.
I'm a fan of xor hacks:
Swap 2 pointers without third temp pointer:
int * a;
int * b;
a ^= b;
b ^= a;
a ^= b;
Or I really like the xor linked list with only one pointer. (http://en.wikipedia.org/wiki/XOR_linked_list)
Each node in the linked list is the Xor of the previous node and the next node. To traverse forward, the address of the nodes are found in the following manner :
LLNode * first = head;
LLNode * second = first.linked_nodes;
LLNode * third = second.linked_nodes ^ first;
LLNode * fourth = third.linked_nodes ^ second;
etc.
or to traverse backwards:
LLNode * last = tail;
LLNode * second_to_last = last.linked_nodes;
LLNode * third_to_last = second_to_last.linked_nodes ^ last;
LLNode * fourth_to_last = third_to_last.linked_nodes ^ second_to_last;
etc.
While not terribly useful (you can't start traversing from an arbitrary node) I find it to be very cool.
With moment you can parse the date string you have:
var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")
That's for UTC, you'll have to convert the time zone from that point if you so desire.
Then you can get the day of the week:
dt.format('dddd');
In Javascript, there are synchronous and asynchronous functions.
Most functions in Javascript are synchronous. If you were to call several synchronous functions in a row
doSomething();
doSomethingElse();
doSomethingUsefulThisTime();
they will execute in order. doSomethingElse
will not start until doSomething
has completed. doSomethingUsefulThisTime
, in turn, will not start until doSomethingElse
has completed.
Asynchronous function, however, will not wait for each other. Let us look at the same code sample we had above, this time assuming that the functions are asynchronous
doSomething();
doSomethingElse();
doSomethingUsefulThisTime();
The functions will be initialized in order, but they will all execute roughly at the same time. You can't consistently predict which one will finish first: the one that happens to take the shortest amount of time to execute will finish first.
But sometimes, you want functions that are asynchronous to execute in order, and sometimes you want functions that are synchronous to execute asynchronously. Fortunately, this is possible with callbacks and timeouts, respectively.
Let's assume that we have three asynchronous functions that we want to execute in order, some_3secs_function
, some_5secs_function
, and some_8secs_function
.
Since functions can be passed as arguments in Javascript, you can pass a function as a callback to execute after the function has completed.
If we create the functions like this
function some_3secs_function(value, callback){
//do stuff
callback();
}
then you can call then in order, like this:
some_3secs_function(some_value, function() {
some_5secs_function(other_value, function() {
some_8secs_function(third_value, function() {
//All three functions have completed, in order.
});
});
});
In Javascript, you can tell a function to execute after a certain timeout (in milliseconds). This can, in effect, make synchronous functions behave asynchronously.
If we have three synchronous functions, we can execute them asynchronously using the setTimeout
function.
setTimeout(doSomething, 10);
setTimeout(doSomethingElse, 10);
setTimeout(doSomethingUsefulThisTime, 10);
This is, however, a bit ugly and violates the DRY principle[wikipedia]. We could clean this up a bit by creating a function that accepts an array of functions and a timeout.
function executeAsynchronously(functions, timeout) {
for(var i = 0; i < functions.length; i++) {
setTimeout(functions[i], timeout);
}
}
This can be called like so:
executeAsynchronously(
[doSomething, doSomethingElse, doSomethingUsefulThisTime], 10);
In summary, if you have asynchronous functions that you want to execute syncronously, use callbacks, and if you have synchronous functions that you want to execute asynchronously, use timeouts.
A small addition to previous answers, since I couldn't find a solution for a problem, which is not worth opening a new question, but led me here.
Here is a small code snippet, which combines lists
, zip()
and *args
, to provide a wrapper that can deal with an unknown amount of functions with an unknown amount of arguments.
def f1(var1, var2, var3):
print(var1+var2+var3)
def f2(var1, var2):
print(var1*var2)
def f3():
print('f3, empty')
def wrapper(a,b, func_list, arg_list):
print(a)
for f,var in zip(func_list,arg_list):
f(*var)
print(b)
f_list = [f1, f2, f3]
a_list = [[1,2,3], [4,5], []]
wrapper('begin', 'end', f_list, a_list)
Keep in mind, that zip()
does not provide a safety check for lists of unequal length, see zip iterators asserting for equal length in python.
No. Java literal null
is not an instance of any class. Therefore it can not be an instanceof any class. instanceof
will return either false
or true
therefore the <referenceVariable> instanceof <SomeClass>
returns false
when referenceVariable
value is null.
You can simply add your JavaScript in body segment like this:
<body>
<script src="myScript.js"> </script>
</body>
myScript
will be the file name for your JavaScript. Just write the code and enjoy!
In my opinion, there are three serious alternatives to keep an eye on, all of which are free:
All of these approach the problem in slightly different ways with differing UIs. I would suggest giving them all a try and seeing which one you prefer.
Inspired from Robert's answer, but when we use,
ng-click="searchAll = null"
in the filter, it makes the model values as null
and in-turn the search doesn't work with its normal functionality, so it would be better enough to use ng-click="searchAll = ''"
instead
I know this is a rather old post but I have another slightly simpler solution. You could create another class within and make it abstract. Next make an Abstract method name it whatever you like. In the original class make a method that takes the new class as a parameter, in this method call the abstract method. It will look something like this.
public class Demo {
public Demo(/.../){
}
public void view(Action a){
a.preform();
}
/**
* The Action Class is for making the Demo
* View Custom Code
*/
public abstract class Action {
public Action(/.../){
}
abstract void preform();
}
}
Now you can do something like this to call a method from within the class.
/...
Demo d = new Demo;
Action a = new Action() {
@Override
void preform() {
//Custom Method Code Goes Here
}
};
/.../
d.view(a)
Like I said I know its old but this way I think is a little easier. Hope it helps.
If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…
For example in one <VirtualHost>
that uses SSL add the two following directives:
SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth
Make sure the following apache modules are loaded (load them using a2enmod):
Obviously you'll have to change your AJAX requests url in order to use the apache proxy…
this solution will not cut words, it will add three dots after the first space. I edited @Raccoon29 solution and I replaced all functions with mb_ functions so that this will work for all languages such as arabic
function cut_string($str, $n_chars, $crop_str = '...') {
$buff = strip_tags($str);
if (mb_strlen($buff) > $n_chars) {
$cut_index = mb_strpos($buff, ' ', $n_chars);
$buff = mb_substr($buff, 0, ($cut_index === false ? $n_chars : $cut_index + 1), "UTF-8") . $crop_str;
}
return $buff;
}
You want to say
for i in array:
print(i, end=" ")
The syntax i in array
iterates over each member of the list. So, array[i]
was trying to access array[1]
, array[2]
, and array[3]
, but the last of these is out of bounds (array
has indices 0, 1, and 2).
You can get the same effect with print(" ".join(map(str,array)))
.
Get is supposed to return, one and exactly one record, to fix this use filter()
, and then take first element of the queryset returned to get the object you were expecting from get, also it would be useful to check if atleast one record is returned before taking out the first element to avoid IndexError
You can use do.call:
do.call("<-",list(parameter_name, parameter_value))
The most reliable way to check type of a variable in JavaScript is the following:
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
toType(new Boolean(true)) // returns "boolean"
toType(true); // returns "boolean"
The reason for this complication is that typeof true
returns "boolean"
while typeof new Boolean(true)
returns "object"
.
from manual:
: [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned.
As this returns always zero therefore is is similar to be used as true
Check out this answer: What Is the Purpose of the `:' (colon) GNU Bash Builtin?
For fully custom links, you'll need to use a UIWebView - you can intercept the calls out, so that you can go to some other part of your app instead when a link is pressed.
This is deletes the table table_name
.
Replace it with the name of the table, which shall be deleted.
DELETE FROM table_name;
To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:
# Root logger option
log4j.rootLogger=INFO, file
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
Follow this tutorial to learn more about log4j usage:
http://www.mkyong.com/logging/log4j-log4j-properties-examples/
For completeness, scaling text by 150% with cex = 1.5
, here is a full solution:
cex <- 1.5
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
plot(...)
par(cex.lab=1, cex.axis=1, cex.main=1)
I recommend wrapping things like this to reduce boilerplate, e.g.:
plot_cex <- function(x, y, cex=1.5, ...) {
par(cex.lab=cex, cex.axis=cex, cex.main=cex)
plot(x, y, ...)
par(cex.lab=1, cex.axis=1, cex.main=1)
invisible(0)
}
which you can then use like this:
plot_cex(x=1:5, y=rnorm(5), cex=1.3)
The ...
are known as ellipses in R and are used to pass additional parameters on to functions. Hence, they are commonly used for plotting. So, the following works as expected:
plot_cex(x=1:5, y=rnorm(5), cex=1.5, ylim=c(-0.5,0.5))
<html>
<script language="javascript" type="text/javascript">
var scrt_var = 10;
openPage = function() {
location.href = "2.html?Key="+scrt_var;
}
</script>
this is a <a href ="javascript:openPage()">Link </a>
</html>
By default the below sits in the application
folder, move it like suggested into the root dir.
leave the .htaccess file in CI root dir
As i have implemented, and it is working fine. you just need to add column width using matColumnDef="description"
for example :
<mat-table #table [dataSource]="dataSource" matSortDisableClear>
<ng-container matColumnDef="productId">
<mat-header-cell *matHeaderCellDef>product ID</mat-header-cell>
<mat-cell *matCellDef="let product">{{product.id}}</mat-cell>
</ng-container>
<ng-container matColumnDef="productName">
<mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
<mat-cell *matCellDef="let product">{{product.name}}</mat-cell>
</ng-container>
<ng-container matColumnDef="actions">
<mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
<mat-cell *matCellDef="let product">
<button (click)="view(product)">
<mat-icon>visibility</mat-icon>
</button>
</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>
here matColumnDef
is
productId
, productName
and action
now we apply width by matColumnDef
styling
.mat-column-productId {
flex: 0 0 10%;
}
.mat-column-productName {
flex: 0 0 50%;
}
and remaining width is equally allocated to other columns
I use Telegram.Bot
and got the ID the following way:
/authenticate
or foo
)private static async Task Main()
{
var botClient = new TelegramBotClient("key");
botClient.OnUpdate += BotClientOnOnUpdate;
Console.ReadKey();
}
private static async void BotClientOnOnUpdate(object? sender, UpdateEventArgs e)
{
var id = e.Update.ChannelPost.Chat.Id;
await botClient.SendTextMessageAsync(new ChatId(id), $"Hello World! Channel ID is {id}");
}
This translates to the getUpdates
method in the plain API, which has an array of Update
which then contains channel_post.chat.id
Don't use an array if you want named keys, use a plain object.
var a = {};
a["key1"] = "value1";
a["key2"] = "value2";
Then:
if ("key1" in a) {
// something
} else {
// something else
}
I just found 0(zero) and shift+0 works on vim.
Use Command Prompt, and then select Run as administrator.
Upgrade the pip version
To upgrade PIP, type this command, and then press Enter:-
python.exe -m pip install --upgrade pip
Go Back to python path C:\Users\Jack\AppData\Local\Programs\Python\Python37\Scripts
Type jupyter notebook
You will be redirected to http://localhost:8888/undefined/tree - Jupyter Home Page
Hope it helps !!!!!!!!!!!
No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.
You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.
Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto
is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100%
like this fiddle.
img {
width: 100%;
height: auto;
}
Here's my solution
if [[ "${cms}" != +(wordpress|magento|typo3) ]]; then
You need to do this:
var scope = {
splitterStyle: {
height: 100
}
};
And then apply this styling to the required elements:
<div id="horizontal" style={splitterStyle}>
In your code you are doing this (which is incorrect):
<div id="horizontal" style={height}>
Where height = 100
.
If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.
Other wise you can't do it.
right click the highlight whose color you want to change
select "Preference"
->General->Editors->Text Editors->Annotations->Occurrences->Text as Hightlited->color.
Select "Preference ->java->Editor->Restore Defaults
This works, as long as you remove the height attribute from the table.
<table id="content" border="0px" cellspacing="0px" cellpadding="0px">
<tr><td height='9px' bgcolor="#990000">Upper</td></tr>
<tr><td height='100px' bgcolor="#990099">Lower</td></tr>
</table>
add this code to the starting of the main CSS.
*,html,body{
margin:0 !important;
padding:0 !important;
box-sizing: border-box !important;;
}
Default values are only used if the arguments are not specified. In your case you did specify the arguments - both were supplied, with a value of NULL. (Yes, in this case NULL is considered a real value :-). Try:
EXEC TEST()
Share and enjoy.
Addendum: The default values for procedure parameters are certainly buried in a system table somewhere (see the SYS.ALL_ARGUMENTS
view), but getting the default value out of the view involves extracting text from a LONG field, and is probably going to prove to be more painful than it's worth. The easy way is to add some code to the procedure:
CREATE OR REPLACE PROCEDURE TEST(X IN VARCHAR2 DEFAULT 'P',
Y IN NUMBER DEFAULT 1)
AS
varX VARCHAR2(32767) := NVL(X, 'P');
varY NUMBER := NVL(Y, 1);
BEGIN
DBMS_OUTPUT.PUT_LINE('X=' || varX || ' -- ' || 'Y=' || varY);
END TEST;
I was able to convert string to DWORD and back with this code:
char strAddr[] = "127.0.0.1"
DWORD ip = inet_addr(strAddr); // ip contains 16777343 [0x0100007f in hex]
struct in_addr paddr;
paddr.S_un.S_addr = ip;
char *strAdd2 = inet_ntoa(paddr); // strAdd2 contains the same string as strAdd
I am working in a maintenance project of old MFC code, so converting deprecated functions calls is not applicable.
A link with 1 function defined
<a href="#" onclick="someFunc()">Click me To fire some functions</a>
Firing multiple functions from someFunc()
function someFunc() {
showAlert();
validate();
anotherFunction();
YetAnotherFunction();
}
They are the inverse of each other. JSON.stringify()
serializes a JS object into a JSON string, whereas JSON.parse()
will deserialize a JSON string into a JS object.
You can do that on javascript side .
<input type="submit" value="Send It!" onClick="return ActionDeterminator();">
When clicked, the JavaScript function ActionDeterminator() determines the alternate action URL. Example code.
function ActionDeterminator() {
if(document.myform.reason[0].checked == true) {
document.myform.action = 'http://google.com';
}
if(document.myform.reason[1].checked == true) {
document.myform.action = 'http://microsoft.com';
document.myform.method = 'get';
}
if(document.myform.reason[2].checked == true) {
document.myform.action = 'http://yahoo.com';
}
return true;
}
MongoVUE looks promising.
If you are the only the person working on the project, what you can do is:
git checkout master
git push origin +HEAD
This will set the tip of origin/master to the same commit as master (and so delete the commits between 41651df and origin/master)
I had the same problem because my "Dynamic Web Project" had no reference to the installed server i wanted to use and therefore had no reference to the Servlet API the server provides.
Following steps solved it without adding an extra Servlet-API to the Java Build Path (Eclipse version: Luna):
Edit: if there is no server listed you can create a new one on the Runtimes tab
To expand one what CheeseConQueso is saying, here are the entire steps to update a view using PHPMyAdmin:
SHOW CREATE VIEW your_view_name
CREATE VIEW
... syntax) to make sure it runs as you expect it to.CREATE VIEW...
syntax).I hope that helps somebody. Special thanks to CheesConQueso for his/her insightful answer.
I would achieve it in a one-liner as shown below:
using System;
using System.Collections;
namespace stackoverflowQuestions
{
class Program
{
static void Main(string[] args)
{
//get bit Array for number 20
var myBitArray = new BitArray(BitConverter.GetBytes(20));
}
}
}
Please note that every element of a BitArray
is stored as bool as shown in below snapshot:
So below code works:
if (myBitArray[0] == false)
{
//this code block will execute
}
but below code doesn't compile at all:
if (myBitArray[0] == 0)
{
//some code
}
Almost there. In your predicate, you want a relative path, so change
./book[/author/name = 'John']
to either
./book[author/name = 'John']
or
./book[./author/name = 'John']
and you will match your element. Your current predicate goes back to the root of the document to look for an author
.
Don’t need to specify a type
value of “text/css”
Every time you link to a CSS file:
<link rel="stylesheet" type="text/css" href="file.css">
You can simply write:
<link rel="stylesheet" href="file.css">
Because this post is the top one found on stackoverflow when searching for "ORA-00942: table or view does not exist insert", I want to mention another possible cause of this error (at least in Oracle 12c): a table uses a sequence to set a default value and the user executing the insert query does not have select privilege on the sequence. This was my problem and it took me an unnecessarily long time to figure it out.
To reproduce the problem, execute the following SQL as user1
:
create sequence seq_customer_id;
create table customer (
c_id number(10) default seq_customer_id.nextval primary key,
name varchar(100) not null,
surname varchar(100) not null
);
grant select, insert, update, delete on customer to user2;
Then, execute this insert statement as user2
:
insert into user1.customer (name,surname) values ('michael','jackson');
The result will be "ORA-00942: table or view does not exist" even though user2
does have insert and select privileges on user1.customer
table and is correctly prefixing the table with the schema owner name. To avoid the problem, you must grant select privilege on the sequence:
grant select on seq_customer_id to user2;
Based on your question, I believe the answer is how to trigger a blur, not just (or even) set the event:
$('#textArea').trigger('blur');
You should indeed start with the Mandelbrot set, and understand what it really is.
The idea behind it is relatively simple. You start with a function of complex variable
f(z) = z2 + C
where z is a complex variable and C is a complex constant. Now you iterate it starting from z = 0, i.e. you compute z1 = f(0), z2 = f(z1), z3 = f(z2) and so on. The set of those constants C for which the sequence z1, z2, z3, ... is bounded, i.e. it does not go to infinity, is the Mandelbrot set (the black set in the figure on the Wikipedia page).
In practice, to draw the Mandelbrot set you should:
The astounding fact about fractals is how we can obtain a tremendously complex set (in particular, the frontier of the Mandelbrot set) from easy and apparently innocuous requirements.
Enjoy!
The dict.items
iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()
will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items)
. And now, just as an example:
>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
... print key, value
...
world 2999
hello 34
The AttributeError
is an exception thrown when an object does not have the attribute you tried to access. The class dict
does not have any predictors
attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.
While not a complete tutorial on the subject of game engine design, I have found that this page has some good detail and examples on use of the component architecture for games.
There is no simple way to achieves this directly. But P99 has macros that allow you to create such type of function automatically:
P99_DECLARE_ENUM(color, red, green, blue);
in a header file, and
P99_DEFINE_ENUM(color);
in one compilation unit (.c file) should then do the trick, in that example the function then would be called color_getname
.
To get this to work for me I had to drill down in the Python directory using the Python command prompt (on WIN10 from VS CODE). In my case it was in my "AppData\Local\Programs\Python\python35-32" directory. From there now I ran the command...
python -m pip install --upgrade pip
This worked and I'm good to go.
Auto-incrementing the index in a loop:
myArr[(len(myArr)+1)]={"key":"val"}
To split vertically:
?+\ Mac
command: workbench.action.splitEditor
To split orthogonal (ie. horizontally in this case):
?+k+?+\ Mac
command: workbench.action.splitEditorOrthogonal
localhost/web is equal to localhost:80/web OR to 127.0.0.1:80/web
localhost:8080/web is equal to localhost:8080/web OR to 127.0.0.1:8080/web
To get the path, you can use:
var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url = window.location.href; // Returns full URL (https://example.com/path/example.html)
var origin = window.location.origin; // Returns base URL (https://example.com)
Here's the method I use...
function Querystring() {
var q = window.location.search.substr(1), qs = {};
if (q.length) {
var keys = q.split("&"), k, kv, key, val, v;
for (k = keys.length; k--; ) {
kv = keys[k].split("=");
key = kv[0];
val = decodeURIComponent(kv[1]);
if (qs[key] === undefined) {
qs[key] = val;
} else {
v = qs[key];
if (v.constructor != Array) {
qs[key] = [];
qs[key].push(v);
}
qs[key].push(val);
}
}
}
return qs;
}
It returns an object of strings and arrays and seems to work quite well. (Strings for single keys, arrays for the same key with multiple values.)
You can use checkout or co
$ svn co http://example.com/svn/app-name directory-name
Some short codes:-
You can use Hudson Groovy builder to do this.
First Job in pipeline
Second job in pipeline
Some things to note:
You should always declare your enum inside a namespace as enums are not proper namespaces and you will be tempted to use them like one.
Always have a break at the end of each switch clause execution will continue downwards to the end otherwise.
Always include the default:
case in your switch.
Use variables of enum type to hold enum values for clarity.
see here for a discussion of the correct use of enums in C++.
This is what you want to do.
namespace choices
{
enum myChoice
{
EASY = 1 ,
MEDIUM = 2,
HARD = 3
};
}
int main(int c, char** argv)
{
choices::myChoice enumVar;
cin >> enumVar;
switch (enumVar)
{
case choices::EASY:
{
// do stuff
break;
}
case choices::MEDIUM:
{
// do stuff
break;
}
default:
{
// is likely to be an error
}
};
}
var seconds_inputs = document.getElementsByClassName('deal_left_seconds');_x000D_
var total_timers = seconds_inputs.length;_x000D_
for ( var i = 0; i < total_timers; i++){_x000D_
var str_seconds = 'seconds_'; var str_seconds_prod_id = 'seconds_prod_id_';_x000D_
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
var cal_seconds = seconds_inputs[i].getAttribute('value');_x000D_
_x000D_
eval('var ' + str_seconds + seconds_prod_id + '= ' + cal_seconds + ';');_x000D_
eval('var ' + str_seconds_prod_id + seconds_prod_id + '= ' + seconds_prod_id + ';');_x000D_
}_x000D_
function timer() {_x000D_
for ( var i = 0; i < total_timers; i++) {_x000D_
var seconds_prod_id = seconds_inputs[i].getAttribute('data-value');_x000D_
_x000D_
var days = Math.floor(eval('seconds_'+seconds_prod_id) / 24 / 60 / 60);_x000D_
var hoursLeft = Math.floor((eval('seconds_'+seconds_prod_id)) - (days * 86400));_x000D_
var hours = Math.floor(hoursLeft / 3600);_x000D_
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));_x000D_
var minutes = Math.floor(minutesLeft / 60);_x000D_
var remainingSeconds = eval('seconds_'+seconds_prod_id) % 60;_x000D_
_x000D_
function pad(n) {_x000D_
return (n < 10 ? "0" + n : n);_x000D_
}_x000D_
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = pad(days);_x000D_
document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = pad(hours);_x000D_
document.getElementById('deal_min_' + seconds_prod_id).innerHTML = pad(minutes);_x000D_
document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(remainingSeconds);_x000D_
_x000D_
if (eval('seconds_'+ seconds_prod_id) == 0) {_x000D_
clearInterval(countdownTimer);_x000D_
document.getElementById('deal_days_' + seconds_prod_id).innerHTML = document.getElementById('deal_hrs_' + seconds_prod_id).innerHTML = document.getElementById('deal_min_' + seconds_prod_id).innerHTML = document.getElementById('deal_sec_' + seconds_prod_id).innerHTML = pad(0);_x000D_
} else {_x000D_
var value = eval('seconds_'+seconds_prod_id);_x000D_
value--;_x000D_
eval('seconds_' + seconds_prod_id + '= ' + value + ';');_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
var countdownTimer = setInterval('timer()', 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="hidden" class="deal_left_seconds" data-value="1" value="10">_x000D_
<div class="box-wrapper">_x000D_
<div class="date box"> <span class="key" id="deal_days_1">00</span> <span class="value">DAYS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
<div class="hour box"> <span class="key" id="deal_hrs_1">00</span> <span class="value">HRS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper">_x000D_
<div class="minutes box"> <span class="key" id="deal_min_1">00</span> <span class="value">MINS</span> </div>_x000D_
</div>_x000D_
<div class="box-wrapper hidden-md">_x000D_
<div class="seconds box"> <span class="key" id="deal_sec_1">00</span> <span class="value">SEC</span> </div>_x000D_
</div>
_x000D_
It somewhat depends on what you use as a CGI framework, but they are available in dictionaries accessible to the program. I'd point you to the docs, but I'm not getting through to python.org right now. But this note on mail.python.org will give you a first pointer. Look at the CGI and URLLIB Python libs for more.
Update
Okay, that link busted. Here's the basic wsgi ref
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
that's all you need
childView.frame = parentView.bounds
if you can use HTML5 you can do <input type="number" />
If not you will have to either do it through javascript as you said it doesnt get submited to do it from codebehind.
<input id="numbersOnly" onkeypress='validate()' />
function validate(){
var returnString;
var text = document.getElementByID('numbersOnly').value;
var regex = /[0-9]|\./;
var anArray = text.split('');
for(var i=0; i<anArray.length; i++){
if(!regex.test(anArray[i]))
{
anArray[i] = '';
}
}
for(var i=0; i<anArray.length; i++) {
returnString += anArray[i];
}
document.getElementByID('numbersOnly').value = returnString;
}
P.S didnt test the code but it should be more or less correct if not check for typos :D You might wanna add a few more things like what to do if the string is null or empty etc. Also you could make this quicker :D
For mysqli on Docker's official php containers:
Tagged php versions that support mysqli may still not come with mysqli configured out of the box, You can install it with the docker-php-ext-install
utility (see comment by Konstantin). This is built-in, but also available from the docker-php-extension-installer project.
They can be used to add mysqli either in a Dockerfile, for example:
FROM php:5.6.5-apache
COPY ./php.ini /usr/local/etc/php/
RUN docker-php-ext-install mysqli
or in a compose file that uses a generic php container and then injects mysqli installation as a setup step into command
:
web:
image: php:5.6.5-apache
volumes:
- app:/var/www/html/
ports:
- "80:80"
command: >
sh -c "docker-php-ext-install mysqli &&
apache2-foreground"
ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE Serde worked for me. My delimiter was '|' and one of the columns is enclosed in double quotes.
Query:
CREATE EXTERNAL TABLE EMAIL(MESSAGE_ID STRING, TEXT STRING, TO_ADDRS STRING, FROM_ADDRS STRING, SUBJECT STRING, DATE STRING)
ROW FORMAT SERDE 'ORG.APACHE.HADOOP.HIVE.SERDE2.OPENCSVSERDE'
WITH SERDEPROPERTIES (
"SEPARATORCHAR" = "|",
"QUOTECHAR" = "\"",
"ESCAPECHAR" = "\""
)
STORED AS TEXTFILE location '/user/abc/csv_folder';
You can achieve this with the following code:
$("input").change(function(e) {
for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {
var file = e.originalEvent.srcElement.files[i];
var img = document.createElement("img");
var reader = new FileReader();
reader.onloadend = function() {
img.src = reader.result;
}
reader.readAsDataURL(file);
$("input").after(img);
}
});
This is not an answer to your original question: "Appending output of a Batch file To log file?"
For reference, it's an answer to your followup question: "What lines should i add to my batch file which will make it execute after every 30mins?"
(But I would take Jon Skeet's advice: "You probably shouldn't do that in your batch file - instead, use Task Scheduler.")
Timeout:
Example (1 second):
TIMEOUT /T 1000 /NOBREAK
Sleep:
Example (1 second):
sleep -m 1000
Alternative methods:
Here's an answer to your 2nd followup question: "Along with the Timestamp?"
Create a date and time stamp in your batch files
Example:
echo *** Date: %DATE:/=-% and Time:%TIME::=-% *** >> output.log
I guess to use the external sdcard you need to use this:
new File("/mnt/external_sd/")
OR
new File("/mnt/extSdCard/")
in your case...
in replace of Environment.getExternalStorageDirectory()
Works for me. You should check whats in the directory mnt first and work from there..
You should use some type of selection method to choose which sdcard to use:
File storageDir = new File("/mnt/");
if(storageDir.isDirectory()){
String[] dirList = storageDir.list();
//TODO some type of selecton method?
}
You can't have duplicate ids. Ids are supposed to be unique. You might want to use a specialized class instead.
Using Node.js you can export the variable via module.
//first.js
const colorCode = {
black: "#000",
white: "#fff"
};
module.exports = { colorCode };
Then, import the module/variable in second file using require.
//second.js
const { colorCode } = require('./first.js')
You can use the import
and export
aproach from ES6 using Webpack/Babel, but in Node.js you need to enable a flag, and uses the .mjs extension.
Try Like This: For SQL SERVER 2008+
SELECT c.name AS ColName, t.name AS TableName
FROM sys.columns c
JOIN sys.tables t ON c.object_id = t.object_id
WHERE c.name LIKE '%MyColumnaName%'
Or
SELECT COLUMN_NAME, TABLE_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%MyName%'
Or Something Like This:
SELECT name
FROM sys.tables
WHERE OBJECT_ID IN ( SELECT id
FROM syscolumns
WHERE name like '%COlName%' )
This is the case from the question because the OP wants to commit to a new branch and also applies if your changes are compatible with the target branch without triggering an overwrite.
As in the accepted answer by John Brodie, you can simply checkout the new branch and commit the work:
git checkout -b branch_name
git add <files>
git commit -m "message"
If you get the error:
error: Your local changes to the following files would be overwritten by checkout:
...
Please commit your changes or stash them before you switch branches
Then you can stash your work, create a new branch, then pop your stash changes, and resolve the conflicts:
git stash
git checkout -b branch_name
git stash pop
It will be as if you had made those changes after creating the new branch. Then you can commit as usual:
git add <files>
git commit -m "message"
See the answer by Carl Norum with cherry-picking, which is the right tool in this case:
git checkout <target name>
git cherry-pick <original branch>
See the answer by joeytwiddle on this potential duplicate. Follow any of the above steps as appropriate, then roll back the original branch:
git branch -f <original branch> <earlier commit id>
If you have pushed your changes to a shared remote like GitHub, you should not attempt this roll-back unless you know what you are doing.
public class FilesStrings {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream("input.txt");
InputStreamReader input = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(input);
String data;
String result = new String();
while ((data = br.readLine()) != null) {
result = result.concat(data + " ");
}
System.out.println(result);
For the next guy or gal hitting this problem, here's what worked for me:
ob_start();
header('Content-Type: '.$mimetype);
ob_end_clean();
$fp = fopen($fullyQualifiedFilepath, 'rb');
fpassthru($fp);
exit;
You need all of that, and only that. If your mimetype varies, have a look at PHP's mime_content_type($filepath)
Loading that giant blob of data is not a great plan, but if you must, here's the outline of how you might do it using jQuery's $.ajax()
function.
<html><head>
<script src="jquery.js"></script>
<script>
getTxt = function (){
$.ajax({
url:'text.txt',
success: function (data){
//parse your data here
//you can split into lines using data.split('\n')
//an use regex functions to effectively parse it
}
});
}
</script>
</head><body>
<button type="button" id="btnGetTxt" onclick="getTxt()">Get Text</button>
</body></html>
If you want to change values not for whole row, but only for some columns:
x = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
x.iloc[1] = dict(A=10, B=-10)
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
You can use CSS3 transitions or maybe CSS3 animations to slide in an element.
For browser support: http://caniuse.com/
I made two quick examples just to show you how I mean.
CSS transition (on hover)
Relevant Code
.wrapper:hover #slide {
transition: 1s;
left: 0;
}
In this case, Im just transitioning the position from left: -100px;
to 0;
with a 1s. duration. It's also possible to move the element using transform: translate();
CSS animation
#slide {
position: absolute;
left: -100px;
width: 100px;
height: 100px;
background: blue;
-webkit-animation: slide 0.5s forwards;
-webkit-animation-delay: 2s;
animation: slide 0.5s forwards;
animation-delay: 2s;
}
@-webkit-keyframes slide {
100% { left: 0; }
}
@keyframes slide {
100% { left: 0; }
}
Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode
to forwards
, which will persist the end state, keeping the div visible when the animation ends.
Like I said, two quick example to show you how it could be done.
EDIT: For details regarding CSS Animations and Transitions see:
Animations
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations
Transitions
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
Hope this helped.
Something that could be implemented is static interface (instead of static method in an interface). All classes implementing a given static interface should implement the corresponding static methods. You could get static interface SI from any Class clazz using
SI si = clazz.getStatic(SI.class); // null if clazz doesn't implement SI
// alternatively if the class is known at compile time
SI si = Someclass.static.SI; // either compiler errror or not null
then you can call si.method(params)
.
This would be useful (for factory design pattern for example) because you can get (or check the implementation of) SI static methods implementation from a compile time unknown class !
A dynamic dispatch is necessary and you can override the static methods (if not final) of a class by extending it (when called through the static interface).
Obviously, these methods can only access static variables of their class.
I ended up finding MinimalistTelnet and adapted it to my uses. I ended up needing to be able to heavily modify the code due to the unique** device that I am attempting to attach to.
** Unique in this instance can be validly interpreted as brain-dead.
you could enter this code form for (today date & Names of the Day & hour) :
datetime.datetime.now().strftime('%y-%m-%d %a %H:%M:%S')
'19-09-09 Mon 17:37:56'
and enter this code for (today date simply):
datetime.date.today().strftime('%y-%m-%d')
'19-09-10'
for object :
datetime.datetime.now().date()
datetime.datetime.today().date()
datetime.datetime.utcnow().date()
datetime.datetime.today().time()
datetime.datetime.utcnow().date()
datetime.datetime.utcnow().time()
My own version of Kim T's code above which combines with some jQuery and allows for targeting of specific iframes.
$(function() {
callPlayer($('#iframe')[0], 'unMute');
});
function callPlayer(iframe, func, args) {
if ( iframe.src.indexOf('youtube.com/embed') !== -1) {
iframe.contentWindow.postMessage( JSON.stringify({
'event': 'command',
'func': func,
'args': args || []
} ), '*');
}
}
While working on a .Net app build with EF code first, I got this error message when trying to apply my migration where I had a Sql("UPDATE tableName SET columnName = value");
statement.
Turns out I misspelled the columnName.
Why not simply return your calculated value and let the caller modify the global variable. It's not a good idea to manipulate a global variable within a function, as below:
Var1 = 1
Var2 = 0
def function():
if Var2 == 0 and Var1 > 0:
print("Result One")
elif Var2 == 1 and Var1 > 0:
print("Result Two")
elif Var1 < 1:
print("Result Three")
return Var1 - 1
Var1 = function()
or even make local copies of the global variables and work with them and return the results which the caller can then assign appropriately
def function():
v1, v2 = Var1, Var2
# calculate using the local variables v1 & v2
return v1 - 1
Var1 = function()
You're looking for the onblur
event. Look here, for more details.
This is to show new line and return carriage in html, then you don't need to do it explicitly. You can do it in css by setting the white-space attribute pre-line value.
<span style="white-space: pre-line">@Model.CommentText</span>
There is an object serialization module, with the serialize function you can serialize any object.
You can also just use the pipeline with the AddScript Method:
string cmdArg = ".\script.ps1 -foo bar"
Collection<PSObject> psresults;
using (Pipeline pipeline = _runspace.CreatePipeline())
{
pipeline.Commands.AddScript(cmdArg);
pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
psresults = pipeline.Invoke();
}
return psresults;
It will take a string, and whatever parameters you pass it.
Detect Enter key pressed on whole document:
$(document).keypress(function (e) {
if (e.which == 13) {
alert('enter key is pressed');
}
});
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
Since it is not yet supported using angular CLI
so here is the possible way, before that please observe what happens when you create a component/service using CLI (ex. ng g c demoComponent
).
demoComponent
(ng g c demoComponent
).HTML,CSS,ts
and a spec
file dedicated to demoComponent.so do it in reverse order
app.module.ts
when removing the dependency you have to do two things.
I just change the type of input to the text and back to the file :D
The exact ranges for Chinese characters (except the extensions) are [\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD]
.
CJK Radicals Supplement is a Unicode block containing alternative, often positional, forms of the Kangxi radicals. They are used headers in dictionary indices and other CJK ideograph collections organized by radical-stroke.
Kanbun is a Unicode block containing annotation characters used in Japanese copies of classical Chinese texts, to indicate reading order.
CJK Unified Ideographs Extension-A is a Unicode block containing rare Han ideographs.
CJK Unified Ideographs is a Unicode block containing the most common CJK ideographs used in modern Chinese and Japanese.
CJK Compatibility Ideographs is a Unicode block created to contain Han characters that were encoded in multiple locations in other established character encodings, in addition to their CJK Unified Ideographs assignments, in order to retain round-trip compatibility between Unicode and those encodings.
For the details please refer to here, and the extensions are provided in other answers.
Outliers are quite similar to peaks, so a peak detector can be useful for identifying outliers. The method described here has quite good performance using z-scores. The animation part way down the page illustrates the method signaling on outliers, or peaks.
Peaks are not always the same as outliers, but they're similar frequently.
An example is shown here: This dataset is read from a sensor via serial communications. Occasional serial communication errors, sensor error or both lead to repeated, clearly erroneous data points. There is no statistical value in these point. They are arguably not outliers, they are errors. The z-score peak detector was able to signal on spurious data points and generated a clean resulting dataset:
If insert trigger is too expensive to use, but a delete trigger could be afforded, and there is an auto-increment id
, then after counting entire table once, and remembering the count as last-count
and the last-counted-id
,
then each day just need to count for id
> last-counted-id
, add that to last-count
, and store the new last-counted-id
.
The delete trigger would decrement last-count, if id of deleted record <= last-counted-id.
I'd simply import the moment module, then use a computed function to handle my moment() logic and return a value that's referenced in the template.
While I have not used this and thus can not speak on it's effectiveness, I did find https://github.com/brockpetrie/vue-moment for an alternate consideration
I stumbled upon this recently when removing rook ceph namespace - it got stuck in Terminating state.
The only thing that helped was removing kubernetes finalizer by directly calling k8s api with curl as suggested here.
kubectl get namespace rook-ceph -o json > tmp.json
tmp.json
(leave empty array "finalizers": []
)kubectl proxy
in another terminal for auth purposes and run following curl request to returned portcurl -k -H "Content-Type: application/json" -X PUT --data-binary @tmp.json 127.0.0.1:8001/k8s/clusters/c-mzplp/api/v1/namespaces/rook-ceph/finalize
Detailed rook ceph teardown here.
When you create an object in a .Net framework application, you don't need to think about how the data is stored in memory. Because the .Net Framework takes care of that for you. However, if you want to store the contents of an object to a file, send an object to another process or transmit it across the network, you do have to think about how the object is represented because you will need to convert to a different format. This conversion is called SERIALIZATION.
Serialization allows the developer to save the state of an object and recreate it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions like sending the object to a remote application by means of a Web Service, passing an object from one domain to another, passing an object through a firewall as an XML string, or maintaining security or user-specific information across applications.
Apply SerializableAttribute
to a type to indicate that instances of this type can be serialized. Apply the SerializableAttribute
even if the class also implements the ISerializable
interface to control the serialization process.
All the public and private fields in a type that are marked by the SerializableAttribute
are serialized by default, unless the type implements the ISerializable
interface to override the serialization process. The default serialization process excludes fields that are marked with NonSerializedAttribute
. If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply NonSerializedAttribute
to that field.
See MSDN for more details.
Edit 1
Any reason to not mark something as serializable
When transferring or saving data, you need to send or save only the required data. So there will be less transfer delays and storage issues. So you can opt out unnecessary chunk of data when serializing.
I would stack generator expressions:
with open(filename) as f_in:
lines = (line.rstrip() for line in f_in) # All lines including the blank ones
lines = (line for line in lines if line) # Non-blank lines
Now, lines
is all of the non-blank lines. This will save you from having to call strip on the line twice. If you want a list of lines, then you can just do:
with open(filename) as f_in:
lines = (line.rstrip() for line in f_in)
lines = list(line for line in lines if line) # Non-blank lines in a list
You can also do it in a one-liner (exluding with
statement) but it's no more efficient and harder to read:
with open(filename) as f_in:
lines = list(line for line in (l.strip() for l in f_in) if line)
I agree that this is ugly because of the repetition of tokens. You could just write a generator if you prefer:
def nonblank_lines(f):
for l in f:
line = l.rstrip()
if line:
yield line
Then call it like:
with open(filename) as f_in:
for line in nonblank_lines(f_in):
# Stuff
with open(filename) as f_in:
lines = filter(None, (line.rstrip() for line in f_in))
and on CPython (with deterministic reference counting)
lines = filter(None, (line.rstrip() for line in open(filename)))
In Python 2 use itertools.ifilter
if you want a generator and in Python 3, just pass the whole thing to list
if you want a list.
I fixed this for an instance of it happening to me by deleting the hidden .svn folder and then performing a checkout on the folder to the same URL.
This did not overwrite any of my modified files & just versioned all of the existing files instead of grabbing fresh copies from the server.
?"["
pretty much covers the various ways of accessing elements of things.
Under usage it lists these:
x[i]
x[i, j, ... , drop = TRUE]
x[[i, exact = TRUE]]
x[[i, j, ..., exact = TRUE]]
x$name
getElement(object, name)
x[i] <- value
x[i, j, ...] <- value
x[[i]] <- value
x$i <- value
The second item is sufficient for your purpose
Under Arguments
it points out that with [
the arguments i
and j
can be numeric, character or logical
So these work:
data[1,1]
data[1,"V1"]
As does this:
data$V1[1]
and keeping in mind a data frame is a list of vectors:
data[[1]][1]
data[["V1"]][1]
will also both work.
So that's a few things to be going on with. I suggest you type in the examples at the bottom of the help page one line at a time (yes, actually type the whole thing in one line at a time and see what they all do, you'll pick up stuff very quickly and the typing rather than copypasting is an important part of helping to commit it to memory.)
I accidentally installed 'serial' (sudo python -m pip install serial
) instead of 'pySerial' (sudo python -m pip install pyserial
), which lead to the same error.
If the previously mentioned solutions did not work for you, double check if you installed the correct library.
document.getElementById(currentInputChoosen).value -= +-100;
Works in my case, if you run into the same problem like me and can't find a solution for that case and find this SO question.
Sorry for little bit off-topic, but as i just found out that this works, i thought it might be worth sharing.
Don't know if it is a dirty workaround, or actually legit.
I'm encountering a similar issue and found two solutions that work as far as viewing the application directly in a browser
ngrok http 8080 -host-header="localhost:8080"
ngrok http --host-header=rewrite 8080
obviously replace 8080 with whatever port you're running on
this solution still raises an error when I use this in an embedded page, that pulls the bundle.js from the react app. I think since it rewrites the header to localhost, when this is embedded, it's looking to localhost, which the app is no longer running on
$CI =& get_instance();
if($CI->input->get('id'){
$id = $CI->input->get('id');
}
There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:
document.getElementById("iframe_id").contentWindow.document.body.onclick =
function() {
alert("iframe clicked");
}
EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:
$('#iframe_id').on('click', function(event) { });
Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.
Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.