I use shortlog for this:
$ git shortlog master..
Username (3):
Write something
Add something
Bump to 1.3.8
GO to rules in firebase and edit rules ..... (provide a timestamp or set to false) My solution.
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.time < timestamp.date(2021, 8, 18);
}
}
}
I would do it like this:
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)
In case you have some more complex formula it will be handy
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
I've used Wiredesignz's MY_Language class with great success.
I've just published it on github, as I can't seem to find a trace of it anywhere.
https://github.com/meigwilym/CI_Language
My only changes are to rename the class to CI_Lang, in accordance with the new v2 changes.
php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data.
I have used following function to parse csv string to associative array
public function csvToArray($file) {
$rows = array();
$headers = array();
if (file_exists($file) && is_readable($file)) {
$handle = fopen($file, 'r');
while (!feof($handle)) {
$row = fgetcsv($handle, 10240, ',', '"');
if (empty($headers))
$headers = $row;
else if (is_array($row)) {
array_splice($row, count($headers));
$rows[] = array_combine($headers, $row);
}
}
fclose($handle);
} else {
throw new Exception($file . ' doesn`t exist or is not readable.');
}
return $rows;
}
if your csv file name is mycsv.csv then you call this function as:
$dataArray = csvToArray(mycsv.csv);
you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/
I'm a bit late to the party, but bumped in to this issue whilst working with the openidc auth module.
I ended up noticing that cookies were not being cleared properly, and I had at least 10 mod_auth_openidc_state_... cookies, all of which would be sent by my browser whenever I made a request.
If this sounds familiar to you, double check your cookies!
That meta tag basically specifies which character set a website is written with.
Here is a definition of UTF-8:
UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.
With webdriver aka selenium2 you can use implicit wait configuration as mentionned on https://www.selenium.dev/documentation/en/webdriver/waits/#implicit-wait
Using Java:
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
Or using python:
from selenium import webdriver
ff = webdriver.Firefox()
ff.implicitly_wait(10) # seconds
ff.get("http://somedomain/url_that_delays_loading")
myDynamicElement = ff.find_element_by_id("myDynamicElement")
gdb has --init-command <somefile>
where somefile has a list of gdb commands to run, I use this to have //GDB
comments in my code, then `
echo "file ./a.out" > run
grep -nrIH "//GDB"|
sed "s/\(^[^:]\+:[^:]\+\):.*$/\1/g" |
awk '{print "b" " " $1}'|
grep -v $(echo $0|sed "s/.*\///g") >> run
gdb --init-command ./run -ex=r
as a script, which puts the command to load the debug symbols, and then generates a list of break commands to put a break point for each //GDB
comment, and starts it running
You need to
#include <string>
<iostream>
declares cout
, cin
, not string
.
Recursion refers to a method which solves a problem by solving a smaller version of the problem and then using that result plus some other computation to formulate the answer to the original problem. Often times, in the process of solving the smaller version, the method will solve a yet smaller version of the problem, and so on, until it reaches a "base case" which is trivial to solve.
For instance, to calculate a factorial for the number X
, one can represent it as X times the factorial of X-1
. Thus, the method "recurses" to find the factorial of X-1
, and then multiplies whatever it got by X
to give a final answer. Of course, to find the factorial of X-1
, it'll first calculate the factorial of X-2
, and so on. The base case would be when X
is 0 or 1, in which case it knows to return 1
since 0! = 1! = 1
.
You may find this query useful:
SELECT *
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName'
AND blocking_session_id <> 0
This Javascript function presents a complete "Save As" Dialog box to the user who runs this through the browser. The user presses OK and the file is saved.
Edit: The following code only works with IE Browser since Firefox and Chrome have considered this code a security problem and has blocked it from working.
// content is the data you'll write to file<br/>
// filename is the filename<br/>
// what I did is use iFrame as a buffer, fill it up with text
function save_content_to_file(content, filename)
{
var dlg = false;
with(document){
ir=createElement('iframe');
ir.id='ifr';
ir.location='about.blank';
ir.style.display='none';
body.appendChild(ir);
with(getElementById('ifr').contentWindow.document){
open("text/plain", "replace");
charset = "utf-8";
write(content);
close();
document.charset = "utf-8";
dlg = execCommand('SaveAs', false, filename+'.txt');
}
body.removeChild(ir);
}
return dlg;
}
Invoke the function:
save_content_to_file("Hello", "C:\\test");
I found this works pretty well for IP addresses. It validates like the top answer but it also makes sure the ip is isolated so no text or more numbers/decimals are after or before the ip.
(?<!\S)(?:(?:\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\b|.\b){7}(?!\S)
128M == 134217728
, the number you are seeing.
The memory limit is working fine. When it says it tried to allocate 32 bytes, that the amount requested by the last operation before failing.
Are you building any huge arrays or reading large text files? If so, remember to free any memory you don't need anymore, or break the task down into smaller steps.
run
gradle clean
then try
gradle build
it worked for me
I had a similar problem with truncated tar files being produced by a cron job and redirecting standard out to a file fixed the issue.
From talking to a colleague, cron creates a pipe and limits the amount of output that can be sent to standard out. I fixed mine by removing -v from my tar command, making it much less verbose and keeping the error output in the same spot as the rest of my cron jobs. If you need the verbose tar output, you'll need to redirect to a file, though.
I'd say they are different concepts but not too different to say "chalk and cheese".
A temp table is good for re-use or to perform multiple processing passes on a set of data.
A CTE can be used either to recurse or to simply improved readability.
And, like a view or inline table valued function can also be treated like a macro to be expanded in the main query
A temp table is another table with some rules around scope
I have stored procs where I use both (and table variables too)
try...
String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));
I dont think this is the "correct" way to doing this... but it works :)
For anyone who comes here, as I did, looking for the syntax to change origin to a different location you can find that documentation here: https://help.github.com/articles/changing-a-remote-s-url/. Using git remote add
to do this will result in "fatal: remote origin already exists."
Nutshell:
git remote set-url origin https://github.com/username/repo
(The marked answer is correct, I'm just hoping to help anyone as lost as I was... haha)
Here is a simple filter pipe for array of objects that contain attributes with string values (ES6)
filter-array-pipe.js
import {Pipe} from 'angular2/core';
// # Filter Array of Objects
@Pipe({ name: 'filter' })
export class FilterArrayPipe {
transform(value, args) {
if (!args[0]) {
return value;
} else if (value) {
return value.filter(item => {
for (let key in item) {
if ((typeof item[key] === 'string' || item[key] instanceof String) &&
(item[key].indexOf(args[0]) !== -1)) {
return true;
}
}
});
}
}
}
Your component
myobjComponent.js
import {Component} from 'angular2/core';
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import {FilterArrayPipe} from 'filter-array-pipe';
@Component({
templateUrl: 'myobj.list.html',
providers: [HTTP_PROVIDERS],
pipes: [FilterArrayPipe]
})
export class MyObjList {
static get parameters() {
return [[Http]];
}
constructor(_http) {
_http.get('/api/myobj')
.map(res => res.json())
.subscribe(
data => this.myobjs = data,
err => this.logError(err))
);
}
resetQuery(){
this.query = '';
}
}
In your template
myobj.list.html
<input type="text" [(ngModel)]="query" placeholder="... filter" >
<div (click)="resetQuery()"> <span class="icon-cross"></span> </div>
</div>
<ul><li *ngFor="#myobj of myobjs| filter:query">...<li></ul>
What you are trying to do is add additional information to each item in the list that you already created so
alist[ 'from form', 'stuff 2', 'stuff 3']
for j in range( 0,len[alist]):
temp= []
temp.append(alist[j]) # alist[0] is 'from form'
temp.append('t') # slot for first piece of data 't'
temp.append('-') # slot for second piece of data
blist.append(temp) # will be alist with 2 additional fields for extra stuff assocated with each item in alist
You can define your escape character, but you can only use it with a LIKE
clause.
Example:
SELECT columns FROM table
WHERE column LIKE '%\%%' ESCAPE '\'
Here it will search for %
in whole string and this is how one can use ESCAPE
identifier in SQL Server
.
When you reference Range like that it's called an unqualified reference because you don't specifically say which sheet the range is on. Unqualified references are handled by the "_Global" object that determines which object you're referring to and that depends on where your code is.
If you're in a standard module, unqualified Range will refer to Activesheet. If you're in a sheet's class module, unqualified Range will refer to that sheet.
inputTemplateContent is a variable that contains a reference to a range, probably a named range. If you look at the RefersTo property of that named range, it likely points to a sheet other than the Activesheet at the time the code executes.
The best way to fix this is to avoid unqualified Range references by specifying the sheet. Like
With ThisWorkbook.Worksheets("Template")
.Range(inputTemplateHeader).Value = NO_ENTRY
.Range(inputTemplateContent).Value = NO_ENTRY
End With
Adjust the workbook and worksheet references to fit your particular situation.
I would go about it somewhat like this:
<html>
<head>
<title>Print Test Page</title>
<script>
printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
function printDiv(divId) {
window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
</script>
</head>
<body>
<h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
<b>Div 1:</b> <a href="javascript:printDiv('div1')">Print</a><br>
<div id="div1">This is the div1's print output</div>
<br><br>
<b>Div 2:</b> <a href="javascript:printDiv('div2')">Print</a><br>
<div id="div2">This is the div2's print output</div>
<br><br>
<b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>
<div id="div3">This is the div3's print output</div>
<iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
</body>
</html>
You can do it using dynamic
instead of object
:
dynamic item = AnyFunction(....);
string value = item.name;
Note that the Dynamic Language Runtime (DLR) has built-in caching mechanisms, so subsequent calls are very fast.
You can create a C# like extension/helper method by (RE) implementing the Collections interface and adding- example for Java Collection:
public class RockCollection<T extends Comparable<T>> implements Collection<T> {
private Collection<T> _list = new ArrayList<T>();
//###########Custom extension methods###########
public T doSomething() {
//do some stuff
return _list
}
//proper examples
public T find(Predicate<T> predicate) {
return _list.stream()
.filter(predicate)
.findFirst()
.get();
}
public List<T> findAll(Predicate<T> predicate) {
return _list.stream()
.filter(predicate)
.collect(Collectors.<T>toList());
}
public String join(String joiner) {
StringBuilder aggregate = new StringBuilder("");
_list.forEach( item ->
aggregate.append(item.toString() + joiner)
);
return aggregate.toString().substring(0, aggregate.length() - 1);
}
public List<T> reverse() {
List<T> listToReverse = (List<T>)_list;
Collections.reverse(listToReverse);
return listToReverse;
}
public List<T> sort(Comparator<T> sortComparer) {
List<T> listToReverse = (List<T>)_list;
Collections.sort(listToReverse, sortComparer);
return listToReverse;
}
public int sum() {
List<T> list = (List<T>)_list;
int total = 0;
for (T aList : list) {
total += Integer.parseInt(aList.toString());
}
return total;
}
public List<T> minus(RockCollection<T> listToMinus) {
List<T> list = (List<T>)_list;
int total = 0;
listToMinus.forEach(list::remove);
return list;
}
public Double average() {
List<T> list = (List<T>)_list;
Double total = 0.0;
for (T aList : list) {
total += Double.parseDouble(aList.toString());
}
return total / list.size();
}
public T first() {
return _list.stream().findFirst().get();
//.collect(Collectors.<T>toList());
}
public T last() {
List<T> list = (List<T>)_list;
return list.get(_list.size() - 1);
}
//##############################################
//Re-implement existing methods
@Override
public int size() {
return _list.size();
}
@Override
public boolean isEmpty() {
return _list == null || _list.size() == 0;
}
Non of these worked for me... when I converted the timestamp back it's 4 years off.
This worked perfectly: =(A2-DATE(1970,1,1))*86400
Credit goes to: Filip Czaja http://fczaja.blogspot.ca
Original Post: http://fczaja.blogspot.ca/2011/06/convert-excel-date-into-timestamp.html
This issue came for me due to the fact that .. i was running server with selenium-server-standalone-2.32.0 and client registered with selenium-server-standalone-2.37.0 .. When i made both selenium-server-standalone-2.32.0 and ran then things worked fine
A more up to date answer for anyone else who comes across this:
(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)
Compile automatically:
To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option
Show all errors in one place:
The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.
Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.
While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.
sizeWithFont:
is now deprecated, use sizeWithAttributes:
instead:
UIFont *font = [UIFont fontWithName:@"Helvetica" size:30];
NSDictionary *userAttributes = @{NSFontAttributeName: font,
NSForegroundColorAttributeName: [UIColor blackColor]};
NSString *text = @"hello";
...
const CGSize textSize = [text sizeWithAttributes: userAttributes];
Here use asp:CompareValidator, and compare the value to "select" option.
Use Operator="NotEqual" ValueToCompare="0"
to prevent the user from submitting the "select".
<asp:CompareValidator ControlToValidate="ddlReportType" ID="CompareValidator1"
ValidationGroup="g1" CssClass="errormesg" ErrorMessage="Please select a type"
runat="server" Display="Dynamic"
Operator="NotEqual" ValueToCompare="0" Type="Integer" />
When you do above, if you select the "select " option from dropdown it will show the ErrorMessage
.
Like everyone else said here, the support library (com.android.support
) is being included more than once in your project. Try adding this in your build.gradle
at the root level and it should exclude the support library from being exported via other project dependencies.
configurations {
all*.exclude group: 'com.android.support', module: 'support-v4'
}
If you have more then one support libs included in the dependencies like this, you may want to remove one of them:
A Mocha test case example:
describe('Check version of node', function () {
it('Should test version assert', async function () {
var version = process.version;
var check = parseFloat(version.substr(1,version.length)) > 12.0;
console.log("version: "+version);
console.log("check: " +check);
assert.equal(check, true);
});});
Use this javascript function as an example on how to accomplish this.
function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe
// and the domains are different.
var myresult = true;
try {
var tophref = top.location.href;
var tophostname = top.location.hostname.toString();
var myhref = location.href;
if (tophref === myhref) {
myresult = true;
} else if (tophostname !== "www.yourdomain.com") {
myresult = false;
}
} catch (error) {
// error is a permission error that top.location.href is not accessible
// (which means parent domain <> iframe domain)!
myresult = false;
}
return myresult;
}
>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
[3, 0, 1, 2],
[2, 0, 1, 1],
[4, 0, 2, 3],
[0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False, True, True, True],
[False, True, True, True],
[ True, True, True, True],
[False, True, True, False],
[ True, True, True, True]], dtype=bool)
>>>
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
[0, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 0],
[1, 1, 1, 1]])
You can shorten this with:
>>> c = (a < 3).astype(int)
For those who switched to Kotlin just use
string.toLong()
That will call Long.parseLong(string)
under the hood
you can try this... ALTER TABLE Your_Table ADD table_ID int NOT NULL PRIMARY KEY auto_increment;
Look at a JUnit report. JUnit is already organized by package. Each package has (or can have) TestSuite classes, each of which in turn run multiple TestCases. Each TestCase can have multiple test methods of the form public void test*()
, each of which will actually become an instance of the TestCase class to which they belong. Each test method (TestCase instance) has a name and a pass/fail criteria.
What my management requires is the concept of individual TestStep items, each of which reports their own pass/fail criteria. Failure of any test step must not prevent the execution of subsequent test steps.
In the past, test developers in my position organized TestCase classes into packages that correspond to the part(s) of the product under test, created a TestCase class for each test, and made each test method a separate "step" in the test, complete with its own pass/fail criteria in the JUnit output. Each TestCase is a standalone "test", but the individual methods, or test "steps" within the TestCase, must occur in a specific order.
The TestCase methods were the steps of the TestCase, and test designers got a separate pass/fail criterion per test step. Now the test steps are jumbled, and the tests (of course) fail.
For example:
Class testStateChanges extends TestCase
public void testCreateObjectPlacesTheObjectInStateA()
public void testTransitionToStateBAndValidateStateB()
public void testTransitionToStateCAndValidateStateC()
public void testTryToDeleteObjectinStateCAndValidateObjectStillExists()
public void testTransitionToStateAAndValidateStateA()
public void testDeleteObjectInStateAAndObjectDoesNotExist()
public void cleanupIfAnythingWentWrong()
Each test method asserts and reports its own separate pass/fail criteria. Collapsing this into "one big test method" for the sake of ordering loses the pass/fail criteria granularity of each "step" in the JUnit summary report. ...and that upsets my managers. They are currently demanding another alternative.
Can anyone explain how a JUnit with scrambled test method ordering would support separate pass/fail criteria of each sequential test step, as exemplified above and required by my management?
Regardless of the documentation, I see this as a serious regression in the JUnit framework that is making life difficult for lots of test developers.
In my case because I assigned the post data to the header, this is how I get it:
protected void Page_Load(object sender, EventArgs e){
...
postValue = Request.Headers["Key"];
This is how I attached the value and key to the POST
:
var request = new NSMutableUrlRequest(url){
HttpMethod = "POST",
Headers = NSDictionary.FromObjectAndKey(FromObject(value), FromObject("key"))
};
webView.LoadRequest(request);
The simple way to create Current TimeStamp. like below,
func generateCurrentTimeStamp () -> String {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy_MM_dd_hh_mm_ss"
return (formatter.string(from: Date()) as NSString) as String
}
Btw you can also use the ui-sref attribute in your templates to pass objects
ui-sref="myState({ myParam: myObject })"
Add it in database migrations, that way everyone gets it as they update. Handle all of your logic in the ruby/rails code, so you never have to mess with explicit ID settings.
Let me try to make it simple, suppose URL of the site is http://example.com/ and let's suppose you need to sign up by filling username and password, so we go to the login page say http://example.com/login.php now and view it's source code and search for the action URL it will be in form tag something like
<form name="loginform" method="post" action="userinfo.php">
now take userinfo.php to make absolute URL which will be 'http://example.com/userinfo.php', now run a simple python script
import requests
url = 'http://example.com/userinfo.php'
values = {'username': 'user',
'password': 'pass'}
r = requests.post(url, data=values)
print r.content
I Hope that this helps someone somewhere someday.
You should install IIS sub components from
Control Panel
-> Programs and Features
-> Turn Windows features on or off
Internet Information Services
has subsection World Wide Web Services
/ Application Development Features
There you must check ASP.NET
(.NET Extensibility
, ISAPI Extensions
, ISAPI Filters
will be selected automatically). Double check that specific versions are checked. Under Windows Server 2012 R2, these options are split into 4 & 4.5.
Run from cmd
:
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir
Finally check in IIS manager, that your application uses application pool with .NET framework version v4.0.
Also, look at this answer.
Use setInterval
:
$(function(){
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
// stuff you want to do every second
}
Here's an article on the difference between setTimeout
and setInterval
. Both will provide the functionality you need, they just require different implementations.
You also need to include the Log4J JAR file in the classpath.
Note that slf4j-log4j12-1.6.4.jar
is only an adapter to make it possible to use Log4J via the SLF4J API. It does not contain the actual implementation of Log4J.
I recommend php-ffmpeg library.
Extracting image
You can extract a frame at any timecode using the
FFMpeg\Media\Video::frame
method.This code returns a
FFMpeg\Media\Frame
instance corresponding to the second 42. You can pass anyFFMpeg\Coordinate\TimeCode
as argument, see dedicated documentation below for more information.
$frame = $video->frame(FFMpeg\Coordinate\TimeCode::fromSeconds(42));
$frame->save('image.jpg');
If you want to extract multiple images from the video, you can use the following filter:
$video
->filters()
->extractMultipleFrames(FFMpeg\Filters\Video\ExtractMultipleFramesFilter::FRAMERATE_EVERY_10SEC, '/path/to/destination/folder/')
->synchronize();
$video
->save(new FFMpeg\Format\Video\X264(), '/path/to/new/file');
By default, this will save the frames as jpg images.
You are able to override this using setFrameFileType
to save the frames in another format:
$frameFileType = 'jpg'; // either 'jpg', 'jpeg' or 'png'
$filter = new ExtractMultipleFramesFilter($frameRate, $destinationFolder);
$filter->setFrameFileType($frameFileType);
$video->addFilter($filter);
The getting and setting of variables within classes refers to either retrieving ("getting") or altering ("setting") their contents.
Consider a variable members
of a class family
. Naturally, this variable would need to be an integer, since a family can never consist of two point something people.
So you would probably go ahead by defining the members
variable like this:
class family {
var members:Int
}
This, however, will give people using this class the possibility to set the number of family members to something like 0 or 1. And since there is no such thing as a family of 1 or 0, this is quite unfortunate.
This is where the getters and setters come in. This way you can decide for yourself how variables can be altered and what values they can receive, as well as deciding what content they return.
Returning to our family class, let's make sure nobody can set the members
value to anything less than 2:
class family {
var _members:Int = 2
var members:Int {
get {
return _members
}
set (newVal) {
if newVal >= 2 {
_members = newVal
} else {
println('error: cannot have family with less than 2 members')
}
}
}
}
Now we can access the members
variable as before, by typing instanceOfFamily.members
, and thanks to the setter function, we can also set it's value as before, by typing, for example: instanceOfFamily.members = 3
. What has changed, however, is the fact that we cannot set this variable to anything smaller than 2 anymore.
Note the introduction of the _members
variable, which is the actual variable to store the value that we set through the members
setter function. The original members
has now become a computed property, meaning that it only acts as an interface to deal with our actual variable.
Have you looked into rasdial?
Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network
ie
rasdial "VPN NETWORK NAME" "Username" *
it will then prompt for a password, else you can use "username" "password", this is however less secure
http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265
Your method showFile() declares that it can throw an IOException. Since this is a checked exception, any call to showFile() method must handle the exception somehow. One option is to wrap the call to showFile() in a try-catch block.
try {
showFile();
}
catch(IOException e) {
// Code to handle an IOException here
}
Here's an example, first the method signature:
private string[] SplitInternal()
{
return Regex.Matches(Format, @"([^/\[\]]|\[[^]]*\])+")
.Cast<Match>()
.Select(m => m.Value)
.Where(s => !string.IsNullOrEmpty(s))
.ToArray();
}
Here's the test:
/// <summary>
///A test for SplitInternal
///</summary>
[TestMethod()]
[DeploymentItem("Git XmlLib vs2008.dll")]
public void SplitInternalTest()
{
string path = "pair[path/to/@Key={0}]/Items/Item[Name={1}]/Date";
object[] values = new object[] { 2, "Martin" };
XPathString xp = new XPathString(path, values);
PrivateObject param0 = new PrivateObject(xp);
XPathString_Accessor target = new XPathString_Accessor(param0);
string[] expected = new string[] {
"pair[path/to/@Key={0}]",
"Items",
"Item[Name={1}]",
"Date"
};
string[] actual;
actual = target.SplitInternal();
CollectionAssert.AreEqual(expected, actual);
}
_splitpath should do what you need. You could of course do it manually but _splitpath
handles all special cases as well.
EDIT:
As BillHoag mentioned it is recommended to use the more safe version of _splitpath
called _splitpath_s when available.
Or if you want something portable you could just do something like this
std::vector<std::string> splitpath(
const std::string& str
, const std::set<char> delimiters)
{
std::vector<std::string> result;
char const* pch = str.c_str();
char const* start = pch;
for(; *pch; ++pch)
{
if (delimiters.find(*pch) != delimiters.end())
{
if (start != pch)
{
std::string str(start, pch);
result.push_back(str);
}
else
{
result.push_back("");
}
start = pch + 1;
}
}
result.push_back(start);
return result;
}
...
std::set<char> delims{'\\'};
std::vector<std::string> path = splitpath("C:\\MyDirectory\\MyFile.bat", delims);
cout << path.back() << endl;
In Python, strings are immutable, so you can't change their characters in-place.
You can, however, do the following:
for i in str:
srr += i
The reasons this works is that it's a shortcut for:
for i in str:
srr = srr + i
The above creates a new string with each iteration, and stores the reference to that new string in srr
.
As of 6-6-15 the Web Root location is at /tmp/deployment/application/ROOT using Tomcat.
Here is a sample implementation:
import java.util.*;
public class MyBSTree<K,V> implements MyTree<K,V>{
private BSTNode<K,V> _root;
private int _size;
private Comparator<K> _comparator;
private int mod = 0;
public MyBSTree(Comparator<K> comparator){
_comparator = comparator;
}
public Node<K,V> root(){
return _root;
}
public int size(){
return _size;
}
public boolean containsKey(K key){
if(_root == null){
return false;
}
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return true;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
return false;
}
private int compare(K k1, K k2){
if(_comparator != null){
return _comparator.compare(k1,k2);
}
else {
Comparable<K> comparable = (Comparable<K>)k1;
return comparable.compareTo(k2);
}
}
public V get(K key){
Node<K,V> node = node(key);
return node != null ? node.value() : null;
}
private BSTNode<K,V> node(K key){
if(_root != null){
BSTNode<K,V> node = _root;
while (node != null){
int comparison = compare(key, node.key());
if(comparison == 0){
return node;
}else if(comparison <= 0){
node = node._left;
}else {
node = node._right;
}
}
}
return null;
}
public void add(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
if(_root == null){
_root = new BSTNode<K, V>(key, value);
}
BSTNode<K,V> prev = null, curr = _root;
boolean lastChildLeft = false;
while(curr != null){
int comparison = compare(key, curr.key());
prev = curr;
if(comparison == 0){
curr._value = value;
return;
}else if(comparison < 0){
curr = curr._left;
lastChildLeft = true;
}
else{
curr = curr._right;
lastChildLeft = false;
}
}
mod++;
if(lastChildLeft){
prev._left = new BSTNode<K, V>(key, value);
}else {
prev._right = new BSTNode<K, V>(key, value);
}
}
private void removeNode(BSTNode<K,V> curr){
if(curr.left() == null && curr.right() == null){
if(curr == _root){
_root = null;
}else{
if(curr.isLeft()) curr._parent._left = null;
else curr._parent._right = null;
}
}
else if(curr._left == null && curr._right != null){
curr._key = curr._right._key;
curr._value = curr._right._value;
curr._left = curr._right._left;
curr._right = curr._right._right;
}
else if(curr._left != null && curr._right == null){
curr._key = curr._left._key;
curr._value = curr._left._value;
curr._right = curr._left._right;
curr._left = curr._left._left;
}
else { // both left & right exist
BSTNode<K,V> x = curr._left;
// find right-most node of left sub-tree
while (x._right != null){
x = x._right;
}
// move that to current
curr._key = x._key;
curr._value = x._value;
// delete duplicate data
removeNode(x);
}
}
public V remove(K key){
BSTNode<K,V> curr = _root;
V val = null;
while(curr != null){
int comparison = compare(key, curr.key());
if(comparison == 0){
val = curr._value;
removeNode(curr);
mod++;
break;
}else if(comparison < 0){
curr = curr._left;
}
else{
curr = curr._right;
}
}
return val;
}
public Iterator<MyTree.Node<K,V>> iterator(){
return new MyIterator();
}
private class MyIterator implements Iterator<Node<K,V>>{
int _startMod;
Stack<BSTNode<K,V>> _stack;
public MyIterator(){
_startMod = MyBSTree.this.mod;
_stack = new Stack<BSTNode<K, V>>();
BSTNode<K,V> node = MyBSTree.this._root;
while (node != null){
_stack.push(node);
node = node._left;
}
}
public void remove(){
throw new UnsupportedOperationException();
}
public boolean hasNext(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
return !_stack.empty();
}
public Node<K,V> next(){
if(MyBSTree.this.mod != _startMod){
throw new ConcurrentModificationException();
}
if(!hasNext()){
throw new NoSuchElementException();
}
BSTNode<K,V> node = _stack.pop();
BSTNode<K,V> x = node._right;
while (x != null){
_stack.push(x);
x = x._left;
}
return node;
}
}
@Override
public String toString(){
if(_root == null) return "[]";
return _root.toString();
}
private static class BSTNode<K,V> implements Node<K,V>{
K _key;
V _value;
BSTNode<K,V> _left, _right, _parent;
public BSTNode(K key, V value){
if(key == null){
throw new IllegalArgumentException("key");
}
_key = key;
_value = value;
}
public K key(){
return _key;
}
public V value(){
return _value;
}
public Node<K,V> left(){
return _left;
}
public Node<K,V> right(){
return _right;
}
public Node<K,V> parent(){
return _parent;
}
boolean isLeft(){
if(_parent == null) return false;
return _parent._left == this;
}
boolean isRight(){
if(_parent == null) return false;
return _parent._right == this;
}
@Override
public boolean equals(Object o){
if(o == null){
return false;
}
try{
BSTNode<K,V> node = (BSTNode<K,V>)o;
return node._key.equals(_key) && ((_value == null && node._value == null) || (_value != null && _value.equals(node._value)));
}catch (ClassCastException ex){
return false;
}
}
@Override
public int hashCode(){
int hashCode = _key.hashCode();
if(_value != null){
hashCode ^= _value.hashCode();
}
return hashCode;
}
@Override
public String toString(){
String leftStr = _left != null ? _left.toString() : "";
String rightStr = _right != null ? _right.toString() : "";
return "["+leftStr+" "+_key+" "+rightStr+"]";
}
}
}
My solution, as a jQuery extension based on Robert Koritnik's answer:
$.fn.fitToWidth=function(){
$(this).wrapInner("<span style='display:inline;font:inherit;white-space:inherit;'></span>").each(function(){
var $t=$(this);
var a=$t.outerWidth(),
$s=$t.children("span"),
f=parseFloat($t.css("font-size"));
while($t.children("span").outerWidth() > a) $t.css("font-size",--f);
$t.html($s.html());
});
}
This actually creates a temporary span inheriting important properties, and compares the width difference. Granted, the while loop needs to be optimised (reduce by a percentage difference calculated between the two sizes).
Example usage:
$(function(){
$("h1").fitToWidth();
});
In ECMAScript 2021, you can use replaceAll
can be used.
const str = "string1 string1 string1"
const newStr = str.replaceAll("string1", "string2");
console.log(newStr)
// "string2 string2 string2"
I just run: C:\Users[Username]\AppData\Local\Android\sdk\SDK Manager.exe
Install SDK Platform Android M Preview
And run Android Studio again.
It's working for me :D
Here's a cool way to do custom wildcard expression validations in a form (from: Advanced form validation with AngularJS and filters):
<form novalidate="">
<input type="text" id="name" name="name" ng-model="newPerson.name"
ensure-expression="(persons | filter:{name: newPerson.name}:true).length !== 1">
<!-- or in your case:-->
<input type="text" id="fruitName" name="fruitName" ng-model="data.fruitName"
ensure-expression="(blacklist | filter:{fruitName: data.fruitName}:true).length !== 1">
</form>
app.directive('ensureExpression', ['$http', '$parse', function($http, $parse) {
return {
require: 'ngModel',
link: function(scope, ele, attrs, ngModelController) {
scope.$watch(attrs.ngModel, function(value) {
var booleanResult = $parse(attrs.ensureExpression)(scope);
ngModelController.$setValidity('expression', booleanResult);
});
}
};
}]);
jsFiddle demo (supports expression naming and multiple expressions)
It's similar to ui-validate
, but you don't need a scope specific validation function (this works generically) and ofcourse you don't need ui.utils this way.
One thing that wasn't mentioned completely (although @BlooB kinda mentioned it) is that map returns a map object NOT a list. This is a big difference when it comes to time performance on initialization and iteration. Consider these two tests.
import time
def test1(iterable):
a = time.clock()
map(str, iterable)
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
def test2(iterable):
a = time.clock()
[ x for x in map(str, iterable)]
a = time.clock() - a
b = time.clock()
[ str(x) for x in iterable ]
b = time.clock() - b
print(a,b)
test1(range(2000000)) # Prints ~1.7e-5s ~8s
test2(range(2000000)) # Prints ~9s ~8s
As you can see initializing the map function takes almost no time at all. However iterating through the map object takes longer than simply iterating through the iterable. This means that the function passed to map() is not applied to each element until the element is reached in the iteration. If you want a list use list comprehension. If you plan to iterate through in a for loop and will break at some point, then use map.
Other answers generally pointed out the difference between Bash and a POSIX shell standard. However, when writing portable shell scripts and being used to Bash syntax, a list of typical bashisms and corresponding pure POSIX solutions is very handy. Such list has been compiled when Ubuntu switched from Bash to Dash as default system shell and can be found here: https://wiki.ubuntu.com/DashAsBinSh
Moreover, there is a great tool called checkbashisms that checks for bashisms in your script and comes handy when you want to make sure that your script is portable.
if you get error: Committing is not possible because you have unmerged files.
git checkout master
git merge --squash bugfix
git add .
git commit -m "Message"
fixed all the Conflict files
git add .
you could also use
git add [filename]
No multi-line comments in R as of version 2.12 and unlikely to change. In most environments, you can comment blocks by highlighting and toggle-comment. In emacs, this is 'M-x ;'.
If you are using opencv3, you can print Mat like python numpy style
:
Mat xTrainData = (Mat_<float>(5,2) << 1, 1, 1, 1, 2, 2, 2, 2, 2, 2);
cout << "xTrainData (python) = " << endl << format(xTrainData, Formatter::FMT_PYTHON) << endl << endl;
Output as below, you can see it'e more readable, see here for more information.
But in most case, there is no need to output all the data in Mat, you can output by row range like 0 ~ 2 row:
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include <iomanip>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
//row: 6, column: 3,unsigned one channel
Mat image1(6, 3, CV_8UC1, 5);
// output row: 0 ~ 2
cout << "image1 row: 0~2 = "<< endl << " " << image1.rowRange(0, 2) << endl << endl;
//row: 8, column: 2,unsigned three channel
Mat image2(8, 2, CV_8UC3, Scalar(1, 2, 3));
// output row: 0 ~ 2
cout << "image2 row: 0~2 = "<< endl << " " << image2.rowRange(0, 2) << endl << endl;
return 0;
}
Output as below:
If you have pandas available,
numpy.arange(10000).reshape(250,40)
print(pandas.DataFrame(a).to_string(header=False, index=False))
avoids the side effect of requiring a reset of numpy.set_printoptions(threshold=sys.maxsize)
and you don't get the numpy.array and brackets. I find this convenient for dumping a wide array into a log file
I was getting this error 2013 and none of the above preference changes did anything to fix the problem. I restarted mysql service and the problem went away.
This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery
SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )
Here's an example of parsing posted JSON data and echoing it back.
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/foo', methods=['POST'])
def foo():
data = request.json
return jsonify(data)
To post JSON with curl:
curl -i -H "Content-Type: application/json" -X POST -d '{"userId":"1", "username": "fizz bizz"}' http://localhost:5000/foo
Or to use Postman:
As an alternative answer, there's a command line to invoke directly the Control Panel, which is javaws -viewer
, should work for both openJDK and Oracle's JDK (thanks @Nasser for checking the availability in Oracle's JDK)
Same caution to run as the user you need to access permissions with applies.
Just remove the slash after Data
and prepend the root:
<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>
The simplest is just
string filename = ...
Thread thread = new Thread(() => download(filename));
thread.Start();
The advantage(s) of this (over ParameterizedThreadStart
) is that you can pass multiple parameters, and you get compile-time checking without needing to cast from object
all the time.
[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
string[] formats = { "MM/dd/yyyy" };
DateTime parsedDateTime;
return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
DateTimeStyles.None, out parsedDateTime);
}
Simply specify the date time formats that you wish to accept in the array named formats.
I think you need two case statements:
SELECT *
FROM sys.indexes i
JOIN sys.partitions p
ON i.index_id = p.index_id
JOIN sys.allocation_units a
ON
-- left side of join on statement
CASE
WHEN a.type IN (1, 3)
THEN a.container_id
WHEN a.type IN (2)
THEN a.container_id
END
=
-- right side of join on statement
CASE
WHEN a.type IN (1, 3)
THEN p.hobt_id
WHEN a.type IN (2)
THEN p.partition_id
END
This is because:
Not directly the requested answer, but maybe the root-cause of the question:
You can also prevent commands from even getting into the history, by prefixing them with a space character:
# This command will be in the history
echo Hello world
# This will not
echo Hello world
For tables that are full height (the page scrolls, not the table)
Note: I move the whole <thead>...</thead>
beause In my case I had two rows (Title and filters)
With JS (jQuery)
$( function() {
let marginTop = 0; // Add margin if the page has a top nav-bar
let $thead = $('.table-fixed-head').find('thead');
let offset = $thead.first().offset().top - marginTop;
let lastPos = 0;
$(window).on('scroll', function () {
if ( window.scrollY > offset )
{
if ( lastPos === 0 )
{
// Add a class for styling
$thead.addClass('floating-header');
}
lastPos = window.scrollY - offset;
$thead.css('transform', 'translateY(' + ( lastPos ) + 'px)');
}
else if ( lastPos !== 0 )
{
lastPos = 0;
$thead.removeClass('floating-header');
$thead.css('transform', 'translateY(' + 0 + 'px)');
}
});
});
CSS (Just for styling)
thead.floating-header>tr>th {
background-color: #efefef;
}
thead.floating-header>tr:last-child>th {
border-bottom: 1px solid #aaa;
}
You can use the rotate attribute
<item>
<rotate
android:fromDegrees="90"
android:toDegrees="90"
android:pivotX="50%"
android:pivotY="50%" >
<shape
android:shape="line"
android:top="1dip" >
<stroke
android:width="1dip"
/>
</shape>
</rotate>
</item>
I have the same problem (MSB3021) with WPF project in VS2008 (on Windows 7 x32). The problem appearing if i try to re-run application too quick after previous run. After a few minutes exe-file unlocked by itself and i can re-run application again. But such a long pause angers me. The only thing that really helped me was running VS as Administrator.
If you plan on performing more than simple one liners, it would be better to implement your own class and override the appropriate operators as they apply to your case.
Taken from Mathematics in Python:
class Vector:
def __init__(self, data):
self.data = data
def __repr__(self):
return repr(self.data)
def __add__(self, other):
data = []
for j in range(len(self.data)):
data.append(self.data[j] + other.data[j])
return Vector(data)
x = Vector([1, 2, 3])
print x + x
I had the same problem. I was able to solve the problem from application side, under the following scenario:
JDK8, spring framework 4.2.4.RELEASE, apache tomcat 7.0.63, Oracle Database 11g Enterprise Edition 11.2.0.4.0
I used the database connection pooling apache tomcat-jdbc
:
You can take the following configuration parameters as a reference:
<Resource name="jdbc/exampleDB"
auth="Container"
type="javax.sql.DataSource"
factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
testWhileIdle="true"
testOnBorrow="true"
testOnReturn="false"
validationQuery="SELECT 1 FROM DUAL"
validationInterval="30000"
timeBetweenEvictionRunsMillis="30000"
maxActive="100"
minIdle="10"
maxWait="10000"
initialSize="10"
removeAbandonedTimeout="60"
removeAbandoned="true"
logAbandoned="true"
minEvictableIdleTimeMillis="30000"
jmxEnabled="true"
jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;
org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"
username="your-username"
password="your-password"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe"/>
This configuration was sufficient to fix the error. This works fine for me in the scenario mentioned above.
For more details about the setup apache tomcat-jdbc: https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html
I think you want preg_split
:
$input = "A B C D";
$words = preg_split('/\s+/', $input);
var_dump($words);
In my case, this error comes from my trial to remove dependencies to MSVC-version dependent runtime library DLL (msvcr10.dll or so) and/or remove static runtime library too, to remove excess fat from my executables.
So I use /NODEFAULTLIB linker switch, my self-made "msvcrt-light.lib" (google for it when you need), and mainCRTStartup()
/ WinMainCRTStartup()
entries.
It is IMHO since Visual Studio 2015, so I stuck to older compilers.
However, defining symbol _NO_CRT_STDIO_INLINE removes all hassle, and a simple "Hello World" application is again 3 KB small and doesn't depend to unusual DLLs. Tested in Visual Studio 2017.
To switch between different images when the ImageButton is clicked I used a boolean like this:
ImageButton imageButton;
boolean buttonOn;
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!buttonOn) {
buttonOn = true;
imageButton.setBackground(getResources().getDrawable(R.drawable.button_is_on));
} else {
buttonOn = false;
imageButton.setBackground(getResources().getDrawable(R.drawable.button_is_off));
}
}
});
I had a similar problem, trying to capture a 'shift+click' but since I was using a third party control with a callback rather than the standard click
handler, I didn't have access to the event object and its associated e.shiftKey
.
I ended up handling the mouse down event to record the shift-ness and then using it later in my callback.
var shiftHeld = false;
$('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });
Posted just in case someone else ends up here searching for a solution to this problem.
I believe you are looking for the setTimeout function.
To make your code a little neater, define a separate function for onclick in a <script>
block:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
onclick="myClick();"
You have to drop the constraint before drop your table.
You can use those queries to find all FKs in your table and find the FKs in the tables in which your table is used.
Declare @SchemaName VarChar(200) = 'Your Schema name'
Declare @TableName VarChar(200) = 'Your Table Name'
-- Find FK in This table.
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
'ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.parent_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
-- Find the FKs in the tables in which this table is used
SELECT
' IF EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id =
OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' + FK.name + ']'
+ ''') AND parent_object_id = OBJECT_ID(N''' +
'[' + OBJECT_SCHEMA_NAME(FK.parent_object_id) + '].[' +
OBJECT_NAME(FK.parent_object_id) + ']' + ''')) ' +
' ALTER TABLE ' + OBJECT_SCHEMA_NAME(FK.parent_object_id) +
'.[' + OBJECT_NAME(FK.parent_object_id) +
'] DROP CONSTRAINT ' + FK.name
, S.name , O.name, OBJECT_NAME(FK.parent_object_id)
FROM sys.foreign_keys AS FK
INNER JOIN Sys.objects As O
ON (O.object_id = FK.referenced_object_id )
INNER JOIN SYS.schemas AS S
ON (O.schema_id = S.schema_id)
WHERE
O.name = @TableName
And S.name = @SchemaName
Add one more slash after file://
in the value of xsi:schemaLocation
. (You have two; you need three. Think protocol://host/path
where protocol
is 'file'
and host
is empty here, yielding three slashes in a row.) You can also eliminate the double slashes along the path
. I believe that the double slashes help with file systems that allow spaces in file and directory names, but you wisely avoided that complication in your path naming.
xsi:schemaLocation="http://www.w3schools.com file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd"
Still not working? I suggest that you carefully copy the full file specification for the XSD into the address bar of Chrome or Firefox:
file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd
If the XSD does not display in the browser, delete all but the last component of the path (email.xsd) and see if you can't display the parent directory. Continue in this manner, walking up the directory structure until you discover where the path diverges from the reality of your local filesystem.
If the XSD does displayed in the browser, state what XML processor you're using, and be prepared to hear that it's broken or that you must work around some limitation. I can tell you that the above fix will work with my Xerces-J-based validator.
If your code cannot be updated on some reason, just change your switch ... continue
to switch ... break
, as in previous versions of PHP it was meant to work this way.
Note: u should login as root user
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('your password');
ints:
$query = "SELECT * FROM `$table` WHERE `$column` IN(".implode(',',$array).")";
strings:
$query = "SELECT * FROM `$table` WHERE `$column` IN('".implode("','",$array)."')";
Sometimes you don't have a local REF for pushing that branch back to the origin.
Try
git push origin master:master
This explicitly indicates which branch to push to (and from)
Alternatively, if you want to simply set the number of ticks while allowing matplotlib to position them (currently only with MaxNLocator
), there is pyplot.locator_params
,
pyplot.locator_params(nbins=4)
You can specify specific axis in this method as mentioned below, default is both:
# To specify the number of ticks on both or any single axes
pyplot.locator_params(axis='y', nbins=6)
pyplot.locator_params(axis='x', nbins=10)
In XML values in text() nodes.
If we write this
<numbers>1,2,3</numbers>
in element "numbers
" will be one text() node with value "1,2,3".
Native way to get many text() nodes in element is insert nodes of other types in text.
Other available types is element or comment() node.
Split with element node:
<numbers>3<_/>2<_/>1</numbers>
Split with comment() node:
<numbers>3<!---->2<!---->1</numbers>
We can select this values by this XPath
//numbers/text()
Select value by index
//numbers/text()[3]
Will return text() node with value "1"
No it doesnt really matter. The MySQL speed is about 7 Million rows per second. So you can scale it quite a bit
Running .NET core
(3.1.4) on IIS
behind a Load balancer did not work with other suggested solutions.
Manually reading the X-Forwarded-For
header does.
IPAddress ip;
var headers = Request.Headers.ToList();
if (headers.Exists((kvp) => kvp.Key == "X-Forwarded-For"))
{
// when running behind a load balancer you can expect this header
var header = headers.First((kvp) => kvp.Key == "X-Forwarded-For").Value.ToString();
ip = IPAddress.Parse(header);
}
else
{
// this will always have a value (running locally in development won't have the header)
ip = Request.HttpContext.Connection.RemoteIpAddress;
}
Example
0000 0001 Yes
0001 0001 No
Algorithm
Using a bit mask, divide NUM
the variable in binary
IF R > 0 AND L > 0: Return FALSE
Otherwise, NUM
becomes the one that is non-zero
IF NUM = 1: Return TRUE
Otherwise, go to Step 1
Complexity
Time ~ O(log(d))
where d
is number of binary digits
It seems to me that simply: ls -lt mydirectory
does the job...
assertNotNull
asserts that the object is not null. If it is null the test fails, so you want that.
There are already many good answers, but if your entire file is on a single line and you still want to process "rows" (as opposed to fixed-size blocks), these answers will not help you.
99% of the time, it is possible to process files line by line. Then, as suggested in this answer, you can to use the file object itself as lazy generator:
with open('big.csv') as f:
for line in f:
process(line)
However, I once ran into a very very big (almost) single line file, where the row separator was in fact not '\n'
but '|'
.
'|'
to '\n'
before processing was also out of the question, because some of the fields of this csv contained '\n'
(free text user input).For these kind of situations, I created the following snippet:
def rows(f, chunksize=1024, sep='|'):
"""
Read a file where the row separator is '|' lazily.
Usage:
>>> with open('big.csv') as f:
>>> for r in rows(f):
>>> process(row)
"""
curr_row = ''
while True:
chunk = f.read(chunksize)
if chunk == '': # End of file
yield curr_row
break
while True:
i = chunk.find(sep)
if i == -1:
break
yield curr_row + chunk[:i]
curr_row = ''
chunk = chunk[i+1:]
curr_row += chunk
I was able to use it successfully to solve my problem. It has been extensively tested, with various chunk sizes.
Test suite, for those who want to convince themselves.
test_file = 'test_file'
def cleanup(func):
def wrapper(*args, **kwargs):
func(*args, **kwargs)
os.unlink(test_file)
return wrapper
@cleanup
def test_empty(chunksize=1024):
with open(test_file, 'w') as f:
f.write('')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 1
@cleanup
def test_1_char_2_rows(chunksize=1024):
with open(test_file, 'w') as f:
f.write('|')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 2
@cleanup
def test_1_char(chunksize=1024):
with open(test_file, 'w') as f:
f.write('a')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 1
@cleanup
def test_1025_chars_1_row(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1025):
f.write('a')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 1
@cleanup
def test_1024_chars_2_rows(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1023):
f.write('a')
f.write('|')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 2
@cleanup
def test_1025_chars_1026_rows(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1025):
f.write('|')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 1026
@cleanup
def test_2048_chars_2_rows(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1022):
f.write('a')
f.write('|')
f.write('a')
# -- end of 1st chunk --
for i in range(1024):
f.write('a')
# -- end of 2nd chunk
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 2
@cleanup
def test_2049_chars_2_rows(chunksize=1024):
with open(test_file, 'w') as f:
for i in range(1022):
f.write('a')
f.write('|')
f.write('a')
# -- end of 1st chunk --
for i in range(1024):
f.write('a')
# -- end of 2nd chunk
f.write('a')
with open(test_file) as f:
assert len(list(rows(f, chunksize=chunksize))) == 2
if __name__ == '__main__':
for chunksize in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]:
test_empty(chunksize)
test_1_char_2_rows(chunksize)
test_1_char(chunksize)
test_1025_chars_1_row(chunksize)
test_1024_chars_2_rows(chunksize)
test_1025_chars_1026_rows(chunksize)
test_2048_chars_2_rows(chunksize)
test_2049_chars_2_rows(chunksize)
The answer in my view is related to whether you have a tangible problem to solve or if you just want to learn for example to be prepared for a possible new job. If you have a problem then you are in better shape. You can start by looking around and seeing how other people went about solving that problem. Languages in general you should be able to pick up fairly quickly (after all you hold an MS in EE, no small feat IMO).
What you need to be on the lookout for is good programming practices. You'll probably see yourself asking "why is this method so small", "why is this method empty and what the heck is this abstract word doing here". That will give you perspective beyond syntax towards good writing.
On Fedora, Docker uses LVM for storage if available. On my system docker info
shows:
Storage Driver: devicemapper
Pool Name: vg01-docker--pool
Pool Blocksize: 524.3 kB
Base Device Size: 10.74 GB
Backing Filesystem: xfs
Data file:
Metadata file:
Data Space Used: 9.622 GB
...
In that case, to increase storage, you will have to use LVM command line tools or compatible partition managers like blivet.
It is important to note the following difference between the two techniques:
$Str="This is the<BR />source string<BR />ALL RIGHT"
$Str.Split("<BR />")
This
is
the
(multiple blank lines)
source
string
(multiple blank lines)
ALL
IGHT
$Str -Split("<BR />")
This is the
source string
ALL RIGHT
From this you can see that the string.split()
method:
While the -split
operator:
Calling stopPropagation
on the event prevents propagation:
(event)="doSomething($event); $event.stopPropagation()"
For preventDefault
just return false
(event)="doSomething($event); false"
Event binding allows to execute multiple statements and expressions to be executed sequentially (separated by ;
like in *.ts
files.
The result of last expression will cause preventDefault
to be called if falsy. So be cautious what the expression returns (even when there is only one)
Download the Linux SDK from the Android website. Copy the folder to whereever you want to extract the contents. Open a terminal there, and then run:
sudo apt-get install unzip
sudo tar xvzf android-studio-ide-135.1641136-linux.zip
cd android-studio-ide-135.1641136-linux
./studio.sh
JDK 1.7 is required for Studio 1.0 onwards:
Download the jdk 1.7 by executing the following commands in terminal as mentioned webupd8:
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer
Open Android Studio and install the SDK tools.
Caveats:
Note: If you are running a 64-bit version of Ubuntu, you need to install some 32-bit libraries with the following command:
$ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1
Source: - linux-32-bit-libraries
You need this instead:
if(s.contains("+"))
contains()
method of String
class does not take regular expression as a parameter, it takes normal text.
EDIT:
String s = "ddjdjdj+kfkfkf";
if(s.contains("+"))
{
String parts[] = s.split("\\+");
System.out.print(parts[0]);
}
OUTPUT:
ddjdjdj
Here's how you'd roll your own function http://play.golang.org/p/Qgw7XuLNhb
func compare(a, b T) bool {
if &a == &b {
return true
}
if a.X != b.X || a.Y != b.Y {
return false
}
if len(a.Z) != len(b.Z) || len(a.M) != len(b.M) {
return false
}
for i, v := range a.Z {
if b.Z[i] != v {
return false
}
}
for k, v := range a.M {
if b.M[k] != v {
return false
}
}
return true
}
I started getting this error after converting my project into a typescript project. From what I understand, the problem stems from async/await not being recognized.
For me the error was fixed by adding two things to my setup:
As mentioned above many times, I needed to add babel-polyfill into my webpack entry array:
... entry: ['babel-polyfill', './index.js'], ...
I needed to update my .babelrc to allow the complilation of async/await into generators:
{ "presets": ["es2015"], "plugins": ["transform-async-to-generator"] }
I had to install a few things into my devDependencies in my package.json file as well. Namely, I was missing the babel-plugin-transform-async-to-generator, babel-polyfill and the babel-preset-es2015:
"devDependencies": {
"babel-loader": "^6.2.2",
"babel-plugin-transform-async-to-generator": "^6.5.0",
"babel-polyfill": "^6.5.0",
"babel-preset-es2015": "^6.5.0",
"webpack": "^1.12.13"
}
I got the code from a really helpful and concise GitHub gist you can find here.
Yes, should try reinstall mysql, but use the --reinstall
flag to force a package reconfiguration. So the operating system service configuration is not skipped:
sudo apt --reinstall install mysql-server
To link to a YouTube video so it plays in HD by default, use the following URL:
https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080
Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).
Use this function:
public string GetSubstringByString(string a, string b, string c)
{
return c.Substring((c.IndexOf(a) + a.Length), (c.IndexOf(b) - c.IndexOf(a) - a.Length));
}
and here is the usage:
GetSubstringByString("(", ")", "User name (sales)")
and the output would be:
sales
Because of ridiculous historical practice that nobody is willing to fix. Consolidating all of the functions required by C and POSIX into a single library file would not only avoid this question getting asked over and over, but would also save a significant amount of time and memory when dynamic linking, since each .so
file linked requires the filesystem operations to locate and find it, and a few pages for its static variables, relocations, etc.
An implementation where all functions are in one library and the -lm
, -lpthread
, -lrt
, etc. options are all no-ops (or link to empty .a
files) is perfectly POSIX conformant and certainly preferable.
Note: I'm talking about POSIX because C itself does not specify anything about how the compiler is invoked. Thus you can just treat gcc -std=c99 -lm
as the implementation-specific way the compiler must be invoked for conformant behavior.
If strictly one space character is the delimiter,
probably std::getline
will be valid.
For example:
int main() {
using namespace std;
istringstream iss("This is a string");
string s;
while ( getline( iss, s, ' ' ) ) {
printf( "`%s'\n", s.c_str() );
}
}
EmailData clsEmailData = new EmailData();
List<EmailData> lstemail = new List<EmailData>();
clsEmailData.FirstName="JOhn";
clsEmailData.LastName ="Smith";
clsEmailData.Location ="Los Angeles"
lstemail.add(clsEmailData);
(Using Python's terminology.)
To say Ruby uses "pass by value" or "pass by reference" isn't really descriptive enough to be helpful. I think as most people know it these days, that terminology ("value" vs "reference") comes from C++.
In C++, "pass by value" means the function gets a copy of the variable and any changes to the copy don't change the original. That's true for objects too. If you pass an object variable by value then the whole object (including all of its members) get copied and any changes to the members don't change those members on the original object. (It's different if you pass a pointer by value but Ruby doesn't have pointers anyway, AFAIK.)
class A {
public:
int x;
};
void inc(A arg) {
arg.x++;
printf("in inc: %d\n", arg.x); // => 6
}
void inc(A* arg) {
arg->x++;
printf("in inc: %d\n", arg->x); // => 1
}
int main() {
A a;
a.x = 5;
inc(a);
printf("in main: %d\n", a.x); // => 5
A* b = new A;
b->x = 0;
inc(b);
printf("in main: %d\n", b->x); // => 1
return 0;
}
Output:
in inc: 6
in main: 5
in inc: 1
in main: 1
In C++, "pass by reference" means the function gets access to the original variable. It can assign a whole new literal integer and the original variable will then have that value too.
void replace(A &arg) {
A newA;
newA.x = 10;
arg = newA;
printf("in replace: %d\n", arg.x);
}
int main() {
A a;
a.x = 5;
replace(a);
printf("in main: %d\n", a.x);
return 0;
}
Output:
in replace: 10
in main: 10
Ruby uses pass by value (in the C++ sense) if the argument is not an object. But in Ruby everything is an object, so there really is no pass by value in the C++ sense in Ruby.
In Ruby, "pass by object reference" (to use Python's terminology) is used:
Therefore Ruby does not use "pass by reference" in the C++ sense. If it did, then assigning a new object to a variable inside a function would cause the old object to be forgotten after the function returned.
class A
attr_accessor :x
end
def inc(arg)
arg.x += 1
puts arg.x
end
def replace(arg)
arg = A.new
arg.x = 3
puts arg.x
end
a = A.new
a.x = 1
puts a.x # 1
inc a # 2
puts a.x # 2
replace a # 3
puts a.x # 2
puts ''
def inc_var(arg)
arg += 1
puts arg
end
b = 1 # Even integers are objects in Ruby
puts b # 1
inc_var b # 2
puts b # 1
Output:
1
2
2
3
2
1
2
1
* This is why, in Ruby, if you want to modify an object inside a function but forget those changes when the function returns, then you must explicitly make a copy of the object before making your temporary changes to the copy.
There's no need to set a fact.
- shell: cat "hello"
register: cat_contents
- shell: echo "I cat hello"
when: cat_contents.stdout == "hello"
Use @temp tables whenever possible--that is, you only need one primary key and you do not need to access the data from a subordinate stored proc.
Use #temp tables if you need to access the data from a subordinate stored proc (it is an evil global variable to the stored proc call chain) and you have no other clean way to pass the data between stored procs. Also use it if you need a secondary index (although, really ask yourself if it is a #temp table if you need more than one index)
If you do this, always declare your #temp table at the top of the function. SQL will force a recompile of your stored proc when it sees the create table statement....so if you have the #temp table declaration in the middle of the stored proc, you stored proc must stop processing and recompile.
I had the same issue on OSX Mavericks, it turned out that Sophos anti-virus was blocking certain requests, once I uninstalled it the issue went away.
If you think that it might be caused by an extension one easy way to try and test this is to open chrome with the '--disable-extensions
flag to see if it fixes the problem. If that doesn't fix it consider looking beyond the browser to see if any other application might be causing the problem, specifically security apps which can affect requests.
Yes, it is possible to use @Transactional on private methods, but as others have mentioned this won't work out of the box. You need to use AspectJ. It took me some time to figure out how to get it working. I will share my results.
I chose to use compile-time weaving instead of load-time weaving because I think it's an overall better option. Also, I'm using Java 8 so you may need to adjust some parameters.
First, add the dependency for aspectjrt.
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.8</version>
</dependency>
Then add the AspectJ plugin to do the actual bytecode weaving in Maven (this may not be a minimal example).
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>aspectj-maven-plugin</artifactId>
<version>1.8</version>
<configuration>
<complianceLevel>1.8</complianceLevel>
<source>1.8</source>
<target>1.8</target>
<aspectLibraries>
<aspectLibrary>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</aspectLibrary>
</aspectLibraries>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
Finally add this to your config class
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
Now you should be able to use @Transactional on private methods.
One caveat to this approach: You will need to configure your IDE to be aware of AspectJ otherwise if you run the app via Eclipse for example it may not work. Make sure you test against a direct Maven build as a sanity check.
I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.
The URL has the form:
export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD@DBHOST:DBPORT/DBNAME
Code to connect this way:
var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;
mongo_connect(DATABASE_URL, mongodb_server_options,
function(err, db) {
if(db && !err) {
console.log("connected to mongodb" + " " + lobby_db);
}
else if(err) {
console.log("NOT connected to mongodb " + err + " " + lobby_db);
}
});
Like this:
if (number < 0) {
number *= -1;
}
use the
innerHTML
property and access the td
using getElementById()
as always.
If you are using python 3+ then try adding below lines
import os, sys
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))
sys.path.insert(0, parent_dir_path)
Neo4j cannot delete nodes that have a relation. You have to delete the relations before you can delete the nodes.
But, it is simple way to delete "ALL" nodes and "ALL" relationships with a simple chyper. This is the code:
MATCH (n) DETACH DELETE n
--> DETACH DELETE will remove all of the nodes and relations by Match
We can add for all devices with platform specific size
<link rel="apple-touch-icon" sizes="57x57" href="fav_icons/apple-icon-57x57.png">
<link rel="apple-touch-icon" sizes="60x60" href="fav_icons/apple-icon-60x60.png">
<link rel="apple-touch-icon" sizes="72x72" href="fav_icons/apple-icon-72x72.png">
<link rel="apple-touch-icon" sizes="76x76" href="fav_icons/apple-icon-76x76.png">
<link rel="apple-touch-icon" sizes="114x114" href="fav_icons/apple-icon-114x114.png">
<link rel="apple-touch-icon" sizes="120x120" href="fav_icons/apple-icon-120x120.png">
<link rel="apple-touch-icon" sizes="144x144" href="fav_icons/apple-icon-144x144.png">
<link rel="apple-touch-icon" sizes="152x152" href="fav_icons/apple-icon-152x152.png">
<link rel="apple-touch-icon" sizes="180x180" href="fav_icons/apple-icon-180x180.png">
<link rel="icon" type="image/png" sizes="192x192" href="fav_icons/android-icon-192x192.pn">
<link rel="icon" type="image/png" sizes="32x32" href="fav_icons/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="96x96" href="fav_icons/favicon-96x96.png">
<link rel="icon" type="image/png" sizes="16x16" href="fav_icons/favicon-16x16.png">
any large single block of data stored in a database, such as a picture or sound file, which does not include record fields, and cannot be directly searched by the database's search engine.
Try this:
Sub GetColumns()
Dim lnRow As Long, lnCol As Long
lnRow = 3 'For testing
lnCol = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:="sds", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
End Sub
Probably best not to use colIndex and rowIndex as variable names as they are already mentioned in the Excel Object Library.
There is a better solution now: Vertical align anything with just 3 lines of CSS
JButton close = new JButton("Close");
close.addActionListener(this);
public void actionPerformed(ActionEvent closing) {
// getSource() checks for the source of clicked Button , compares with the name of button in which here is close .
if(closing.getSource()==close)
System.exit(0);
// This exit Your GUI
}
/*Some Answers were asking for @override which is overriding the method the super class or the parent class and creating different objects and etc which makes the answer too long . Note : we just need to import java.awt.*; and java.swing.*; and Adding this command : class className implements actionListener{} */
If you ARE very very lazy, you can put the values inside an array. Such as
list = []
list.append(x)
list.append(y)
list.append(z)
nums = [add numbers here]
letters = [add corresponding letters here]
for index in range(len(nums)):
for obj in list:
if obj == num[index]:
MyList.append(letters[index])
break
You can also put the numbers and letters in a dictionary and do it, but this is probably a LOT more complicated than simply if statements. That's what you get for trying to be extra lazy :)
One more thing, your
if x or y or z == 0:
will compile, but not in the way you want it to. When you simply put a variable in an if statement (example)
if b
the program will check if the variable is not null. Another way to write the above statement (which makes more sense) is
if bool(b)
Bool is an inbuilt function in python which basically does the command of verifying a boolean statement (If you don't know what that is, it is what you are trying to make in your if statement right now :))
Another lazy way I found is :
if any([x==0, y==0, z==0])
I think you could do it using a specs file.
Under MinGW you could run
gcc -dumpspecs > specs
Where it says
*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT}
You change it to
*cpp:
%{posix:-D_POSIX_SOURCE} %{mthreads:-D_MT} -std=c++11
And then place it in
/mingw/lib/gcc/mingw32/<version>/specs
I'm sure you could do the same without a MinGW build. Not sure where to place the specs file though.
The folder is probably either /gcc/lib/ or /gcc/.
This worked for me for on Windows10
curl -d "{"""owner""":"""sasdasdasdasd"""}" -H "Content-Type: application/json" -X PUT http://localhost:8080/api/changeowner/CAR4
Since you don't explicitly invoke a parent constructor as part of your child class constructor, there is an implicit call to a parameterless parent constructor inserted. That constructor does not exist, and so you get that error.
To correct the situation, you need to add an explicit call:
public Child(int i) : base(i)
{
Console.WriteLine("child");
}
Or, you can just add a parameterless parent constructor:
protected Parent() { }
Neither <iostream>
nor <iostream.h>
are standard C header files. Your code is meant to be C++, where <iostream>
is a valid header. Use g++
(and a .cpp
file extension) for C++ code.
Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream>
and using namespace std;
, and replace cout << endl;
with putchar('\n');
... I advise compiling using C99 (eg. gcc -std=c99
)
Yes there is. The preferred syntax is to favor str.format
over the deprecated %
operator.
print "First number is {} and second number is {}".format(first, second)
Apparently, the question never says to run on local mode not on yarn. Somehow I couldnt get spark-default.conf change to work. Instead I tried this and it worked for me
bin/spark-shell --master yarn --num-executors 6 --driver-memory 5g --executor-memory 7g
( couldnt bump executor-memory to 8g there is some restriction from yarn configuration.)
this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)
DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
*/
DECLARE NAME_FOUND VARCHAR DEFAULT "";
SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
RETURN NAME_FOUND;
END;//
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size
like this:
#include <vector>
int main () {
std::vector<int> v;
auto size = v.size();
}
Your third call
int size = v.size();
triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_type
to int
was intended.
Note that if the size of the vector
is greater than the biggest number an int
can represent, size
will contain an implementation defined (de facto garbage) value.
#!/usr/bin/env python
import re
def is_int(x):
if(isinstance(x,(int,long))):
return True
matchObj = re.match(r'^-?\d+\.(\d+)',str(x))
if matchObj:
x = matchObj.group(1)
if int(x)-0==0:
return True
return False
print is_int(6)
print is_int(1.0)
print is_int(1.1)
print is_int(0.1)
print is_int(-956.0)
git rebase -i @~9 # Show the last 9 commits in a text editor
Find the commit you want, change pick
to e
(edit
), and save and close the file. Git will rewind to that commit, allowing you to either:
git commit --amend
to make changes, orgit reset @~
to discard the last commit, but not the changes to the files (i.e. take you to the point you were at when you'd edited the files, but hadn't committed yet).The latter is useful for doing more complex stuff like splitting into multiple commits.
Then, run git rebase --continue
, and Git will replay the subsequent changes on top of your modified commit. You may be asked to fix some merge conflicts.
Note: @
is shorthand for HEAD
, and ~
is the commit before the specified commit.
Read more about rewriting history in the Git docs.
ProTip™: Don't be afraid to experiment with "dangerous" commands that rewrite history* — Git doesn't delete your commits for 90 days by default; you can find them in the reflog:
$ git reset @~3 # go back 3 commits
$ git reflog
c4f708b HEAD@{0}: reset: moving to @~3
2c52489 HEAD@{1}: commit: more changes
4a5246d HEAD@{2}: commit: make important changes
e8571e4 HEAD@{3}: commit: make some changes
... earlier commits ...
$ git reset 2c52489
... and you're back where you started
* Watch out for options like --hard
and --force
though — they can discard data.
* Also, don't rewrite history on any branches you're collaborating on.
On many systems, git rebase -i
will open up Vim by default. Vim doesn't work like most modern text editors, so take a look at how to rebase using Vim. If you'd rather use a different editor, change it with git config --global core.editor your-favorite-text-editor
.
In my case the error occurred inside a Fragment
on this line:
Intent intent = new Intent(getActivity(), SecondaryActivity.class);
It happened when I double clicked on an item which triggered the code above so two SecondaryActivity.class
activities were launched at the same time, one on top of the other. I closed the top SecondaryActivity.class
activity by pressing back button which triggered a call to getActivity()
in the SecondaryActivity.class
which came to foreground. The call to getActivity()
returned null
.
It's some kind of weird Android bug so it usually should not happen.
You can block the clicks after the user clicked once.
Change string[] lines = File.ReadLines("c:\\file.txt");
to IEnumerable<string> lines = File.ReadLines("c:\\file.txt");
The rest of your code should work fine.
I have a .Net Core 3.1 MSTest project with similar issue. This post provided clues to fix it.
Breaking this down to a simple answer for .Net core 3.1:
If it is a MSTest project:
rename file in project to testhost.dll.config
OR
Use post-build command provided by DeepSpace101
Ran into the same problem on Laravel 4 trying to send e-mail using SSL encryption.
Having WAMPServer 2.2 on Windows 7 64bit I only enabled php_openssl in the php.ini, restarted WAMPServer and worked flawlessly.
Did following:
What you're trying to do sounds dangerous, as that's not the intended use of AUTO_INCREMENT
.
If you really want to find the lowest unused key value, don't use AUTO_INCREMENT
at all, and manage your keys manually. However, this is NOT a recommended practice.
Take a step back and ask "why you need to recycle key values?" Do unsigned INT
(or BIGINT
) not provide a large enough key space?
Are you really going to have more than 18,446,744,073,709,551,615
unique records over the course of your application's lifetime?
I had a similar problem; after running the AdMob example, I tried to insert Ads in my app, causing this error:
01-02 16:48:51.269 8199-8199/it.dndc.BreathPlot E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.IllegalStateException: Could not execute method of the activity
Caused by: android.view.InflateException: Binary XML file line #57: Error inflating class fragment
The solution is: you cannot insert the fragment for an Ad into a ListActivity. Instead, I could add it to a FragmentActivity and to an ActionBarActivity without any problem.
My suggestion is: start from the AdMob example and add into it your existing app: I would have saved a lot of time !!!
Another option I like, which can be generalized once I start seeing the code not conform to DRY, is to use one controller that redirects to another controller.
public ActionResult ClientIdSearch(int cid)
{
var action = String.Format("Details/{0}", cid);
return RedirectToAction(action, "Accounts");
}
I find this allows me to apply my logic in one location and re-use it without have to sprinkle JavaScript in the views to handle this. And, as I mentioned I can then refactor for re-use as I see this getting abused.
you can iterate through it to do it
my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
my_string = my_string + ' ' + a
print(my_string)
output is
how are you
you can strip it to get
how are you
like this
my_list = ['how', 'are', 'you']
my_string = " "
for a in my_list:
my_string = my_string + ' ' + a
print(my_string.strip())
Update: since the answer from @r2evans, it is much easier to insert images into R Markdown and control the size of the image.
The bookdown book does a great job of explaining that the best way to include images is by using include_graphics()
. For example, a full width image can be printed with a caption below:
```{r pressure, echo=FALSE, fig.cap="A caption", out.width = '100%'}
knitr::include_graphics("temp.png")
```
The reason this method is better than the pandoc approach ![your image](path/to/image)
:
fig.width
), the output width in the report (out.width
), add captions (fig.cap
) etc.knitr::kable()
is the best way to include tables in an R Markdown report as explained fully here. Again, this function is intelligent in automatically selecting the correct formatting for the output selected.
```{r table}
knitr::kable(mtcars[1:5,, 1:5], caption = "A table caption")
```
If you want to make your own simple tables in R Markdown and are using R Studio, you can check out the insert_table
package. It provides a tidy graphical interface for making tables.
Achieving custom styling of the table column width is beyond the scope of knitr
, but the kableExtra
package has been written to help achieve this: https://cran.r-project.org/web/packages/kableExtra/index.html
The R Markdown cheat sheet is still the best place to learn about most the basic syntax you can use.
If you are looking for potential extensions to the formatting, the bookdown
package is also worth exploring. It provides the ability to cross-reference, create special headers and more: https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html
To me the key thing about this is: an InterruptedException is not anything going wrong, it is the thread doing what you told it to do. Therefore rethrowing it wrapped in a RuntimeException makes zero sense.
In many cases it makes sense to rethrow an exception wrapped in a RuntimeException when you say, I don't know what went wrong here and I can't do anything to fix it, I just want it to get out of the current processing flow and hit whatever application-wide exception handler I have so it can log it. That's not the case with an InterruptedException, it's just the thread responding to having interrupt() called on it, it's throwing the InterruptedException in order to help cancel the thread's processing in a timely way.
So propagate the InterruptedException, or eat it intelligently (meaning at a place where it will have accomplished what it was meant to do) and reset the interrupt flag. Note that the interrupt flag gets cleared when the InterruptedException gets thrown; the assumption the Jdk library developers make is that catching the exception amounts to handling it, so by default the flag is cleared.
So definitely the first way is better, the second posted example in the question is not useful unless you don't expect the thread to actually get interrupted, and interrupting it amounts to an error.
Here's an answer I wrote describing how interrupts work, with an example. You can see in the example code where it is using the InterruptedException to bail out of a while loop in the Runnable's run method.
If you want to to know how to return a value from stored procedure to Visual Basic.NET. Please read this tutorial: How to return a value from stored procedure
I used the following stored procedure to return the value.
CREATE PROCEDURE usp_get_count
AS
BEGIN
DECLARE @VALUE int;
SET @VALUE=(SELECT COUNT(*) FROM tblCar);
RETURN @VALUE;
END
GO
From here Routing in Asp.net Mvc 4 and Web Api
Darin Dimitrov has posted a very good answer which is working for me.
It says...
You could have a couple of routes:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { name = @"^[a-z]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
}
}
Just for the fun of it:
CURDATE() = DATE(NOW())
Or
NOW() = CONCAT(CURDATE(), ' ', CURTIME())
This will allow file names to have spaces (reproducible example).
# Select files of interest, here, only text files for ex.
find -type f -exec file {} \; > findresult.txt
grep ": ASCII text$" findresult.txt > textfiles.txt
# leave only the path to the file removing suffix and prefix
sed -i -e 's/:.*$//' textfiles.txt
sed -i -e 's/\.\///' textfiles.txt
#write a script that deletes the files in textfiles.txt
IFS_backup=$IFS
IFS=$(echo "\n\b")
for f in $(cat textfiles.txt);
do
rm "$f";
done
IFS=$IFS_backup
# save script as "some.sh" and run: sh some.sh
This could be done simpler:
<base href="${pageContext.request.contextPath}/"/>
All URL will be formed without unnecessary domain:port
but with application context.
If there is a one to one mapping between entity and entity_property you can use entity_id as the identifier.
in my test.
close
will send fin packet and destroy fd immediately when socket is not shared with other processes
shutdown
SHUT_RD, process can still recv data from the socket, but recv
will return 0 if TCP buffer is empty.After peer send more data, recv
will return data again.
shutdown
SHUT_WR will send fin packet to indicate the Further sends are disallowed. the peer can recv data but it will recv 0 if its TCP buffer is empty
shutdown
SHUT_RDWR (equal to use both SHUT_RD and SHUT_WR) will send rst packet if peer send more data.
Swift 4
func topMostController() -> UIViewController {
var topController: UIViewController = UIApplication.shared.keyWindow!.rootViewController!
while (topController.presentedViewController != nil) {
topController = topController.presentedViewController!
}
return topController
}
In their simplest form, reset
resets the index without touching the working tree, while checkout
changes the working tree without touching the index.
Resets the index to match HEAD
, working tree left alone:
git reset
Conceptually, this checks out the index into the working tree. To get it to actually do anything you would have to use -f
to force it to overwrite any local changes. This is a safety feature to make sure that the "no argument" form isn't destructive:
git checkout
Once you start adding parameters it is true that there is some overlap.
checkout
is usually used with a branch, tag or commit. In this case it will reset HEAD
and the index to the given commit as well as performing the checkout of the index into the working tree.
Also, if you supply --hard
to reset
you can ask reset
to overwrite the working tree as well as resetting the index.
If you current have a branch checked out out there is a crucial different between reset
and checkout
when you supply an alternative branch or commit. reset
will change the current branch to point at the selected commit whereas checkout
will leave the current branch alone but will checkout the supplied branch or commit instead.
Other forms of reset
and commit
involve supplying paths.
If you supply paths to reset
you cannot supply --hard
and reset
will only change the index version of the supplied paths to the version in the supplied commit (or HEAD
if you don't specify a commit).
If you supply paths to checkout
, like reset
it will update the index version of the supplied paths to match the supplied commit (or HEAD
) but it will always checkout the index version of the supplied paths into the working tree.
This works:
df['date'].dt.year
Now:
df['year'] = df['date'].dt.year
df['month'] = df['date'].dt.month
gives this data frame:
date Count year month
0 2010-06-30 525 2010 6
1 2010-07-30 136 2010 7
2 2010-08-31 125 2010 8
3 2010-09-30 84 2010 9
4 2010-10-29 4469 2010 10
If you have some estimation about the distance between the 2 strings 'abc' and 'efg' you are looking for, you might use:
grep -r . -e 'abc' -A num1 -B num2 | grep 'efg'
That way, the first grep will return the line with the 'abc' plus #num1 lines after it, and #num2 lines after it, and the second grep will sift through all of those to get the 'efg'. Then you'll know at which files they appear together.
I think you've missed the point of access control.
A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.
Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee
) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.
In your specific case, it seems that paste.ee
doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).
Calendar c = new GregorianCalendar();
c.set(Calendar.HOUR_OF_DAY, 0); //anything 0 - 23
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
Date d1 = c.getTime(); //the midnight, that's the first second of the day.
should be Fri Mar 09 00:00:00 IST 2012
Assuming you use LinearLayoutManager
in your RecyclerView, then you can pass true
as third argument in the LinearLayoutManager constructor.
For example:
mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true));
If you are using the StaggeredGridLayoutManager
, then you can use the setReverseLayout
method it provides.
I had the same confusion. After some tinkering based on many of the answers above, I can finally see the differences. In my humble opinion, the distinction is best demonstrated with a flex container that satisfies the following two conditions:
min-height: 60rem
) and thus can become too tall for its contentCondition 1 helps me understand what content
means relative to its parent container. When the content is flush with the container, we will not be able to see any positioning effects coming from align-content
. It is only when we have extra space along the cross axis, we start to see its effect: It aligns the content relative to the boundaries of the parent container.
Condition 2 helps me visualize the effects of align-items
: it aligns items relative to each other.
Here is a code example. Raw materials come from Wes Bos' CSS Grid tutorial (21. Flexbox vs. CSS Grid)
<div class="flex-container">
<div class="item">Short</div>
<div class="item">Longerrrrrrrrrrrrrr</div>
<div class="item"></div>
<div class="item" id="tall">This is Many Words</div>
<div class="item">Lorem, ipsum.</div>
<div class="item">10</div>
<div class="item">Snickers</div>
<div class="item">Wes Is Cool</div>
<div class="item">Short</div>
</div>
.flex-container {
display: flex;
/*dictates a min-height*/
min-height: 60rem;
flex-flow: row wrap;
border: 5px solid white;
justify-content: center;
align-items: center;
align-content: flex-start;
}
#tall {
/*intentionally made tall*/
min-height: 30rem;
}
.item {
margin: 10px;
max-height: 10rem;
}
Example 1: Let's narrow the viewport so that the content is flush with the container. This is when align-content: flex-start;
has no effects since the entire content block is tightly fit inside the container (no extra room for repositioning!)
Also, note the 2nd row--see how the items are center aligned among themselves.
Example 2: As we widen the viewport, we no longer have enough content to fill the entire container. Now we start to see the effects of align-content: flex-start;
--it aligns the content relative to the top edge of the container.
These examples are based on flexbox, but the same principles are applicable to CSS grid. Hope this helps :)
I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.
Here's Sun's docs on the subject matter.
The ANSI escape sequences you're looking for are the Select Graphic Rendition subset. All of these have the form
\033[XXXm
where XXX
is a series of semicolon-separated parameters.
To say, make text red, bold, and underlined (we'll discuss many other options below) in C you might write:
printf("\033[31;1;4mHello\033[0m");
In C++ you'd use
std::cout<<"\033[31;1;4mHello\033[0m";
In Python3 you'd use
print("\033[31;1;4mHello\033[0m")
and in Bash you'd use
echo -e "\033[31;1;4mHello\033[0m"
where the first part makes the text red (31
), bold (1
), underlined (4
) and the last part clears all this (0
).
As described in the table below, there are a large number of text properties you can set, such as boldness, font, underlining, &c. (Isn't it silly that StackOverflow doesn't allow you to put proper tables in answers?)
Code | Effect | Note |
---|---|---|
0 | Reset / Normal | all attributes off |
1 | Bold or increased intensity | |
2 | Faint (decreased intensity) | Not widely supported. |
3 | Italic | Not widely supported. Sometimes treated as inverse. |
4 | Underline | |
5 | Slow Blink | less than 150 per minute |
6 | Rapid Blink | MS-DOS ANSI.SYS; 150+ per minute; not widely supported |
7 | [[reverse video]] | swap foreground and background colors |
8 | Conceal | Not widely supported. |
9 | Crossed-out | Characters legible, but marked for deletion. Not widely supported. |
10 | Primary(default) font | |
11–19 | Alternate font | Select alternate font n-10 |
20 | Fraktur | hardly ever supported |
21 | Bold off or Double Underline | Bold off not widely supported; double underline hardly ever supported. |
22 | Normal color or intensity | Neither bold nor faint |
23 | Not italic, not Fraktur | |
24 | Underline off | Not singly or doubly underlined |
25 | Blink off | |
27 | Inverse off | |
28 | Reveal | conceal off |
29 | Not crossed out | |
30–37 | Set foreground color | See color table below |
38 | Set foreground color | Next arguments are 5;<n> or 2;<r>;<g>;<b> , see below |
39 | Default foreground color | implementation defined (according to standard) |
40–47 | Set background color | See color table below |
48 | Set background color | Next arguments are 5;<n> or 2;<r>;<g>;<b> , see below |
49 | Default background color | implementation defined (according to standard) |
51 | Framed | |
52 | Encircled | |
53 | Overlined | |
54 | Not framed or encircled | |
55 | Not overlined | |
60 | ideogram underline | hardly ever supported |
61 | ideogram double underline | hardly ever supported |
62 | ideogram overline | hardly ever supported |
63 | ideogram double overline | hardly ever supported |
64 | ideogram stress marking | hardly ever supported |
65 | ideogram attributes off | reset the effects of all of 60-64 |
90–97 | Set bright foreground color | aixterm (not in standard) |
100–107 | Set bright background color | aixterm (not in standard) |
You've got this already!
The standards implementing terminal colours began with limited (4-bit) options. The table below lists the RGB values of the background and foreground colours used for these by a variety of terminal emulators:
Using the above, you can make red text on a green background (but why?) using:
\033[31;42m
In their book "Basic Color Terms: Their Universality and Evolution", Brent Berlin and Paul Kay used data collected from twenty different languages from a range of language families to identify eleven possible basic color categories: white, black, red, green, yellow, blue, brown, purple, pink, orange, and gray.
Berlin and Kay found that, in languages with fewer than the maximum eleven color categories, the colors followed a specific evolutionary pattern. This pattern is as follows:
This may be why story Beowulf only contains the colours black, white, and red. It may also be why the Bible does not contain the colour blue. Homer's Odyssey contains black almost 200 times and white about 100 times. Red appears 15 times, while yellow and green appear only 10 times. (More information here)
Differences between languages are also interesting: note the profusion of distinct colour words used by English vs. Chinese. However, digging deeper into these languages shows that each uses colour in distinct ways. (More information)
Generally speaking, the naming, use, and grouping of colours in human languages is fascinating. Now, back to the show.
Technology advanced, and tables of 256 pre-selected colours became available, as shown below.
Using these above, you can make pink text like so:
\033[38;5;206m #That is, \033[38;5;<FG COLOR>m
And make an early-morning blue background using
\033[48;5;57m #That is, \033[48;5;<BG COLOR>m
And, of course, you can combine these:
\033[38;5;206;48;5;57m
The 8-bit colours are arranged like so:
0x00-0x07: standard colors (same as the 4-bit colours)
0x08-0x0F: high intensity colors
0x10-0xE7: 6 × 6 × 6 cube (216 colors): 16 + 36 × r + 6 × g + b (0 = r, g, b = 5)
0xE8-0xFF: grayscale from black to white in 24 steps
Now we are living in the future, and the full RGB spectrum is available using:
\033[38;2;<r>;<g>;<b>m #Select RGB foreground color
\033[48;2;<r>;<g>;<b>m #Select RGB background color
So you can put pinkish text on a brownish background using
\033[38;2;255;82;197;48;2;155;106;0mHello
Support for "true color" terminals is listed here.
Much of the above is drawn from the Wikipedia page "ANSI escape code".
Since I'm often in the position of trying to remember what colours are what, I have a handy script called: ~/bin/ansi_colours
:
#!/usr/bin/python
print "\\033[XXm"
for i in range(30,37+1):
print "\033[%dm%d\t\t\033[%dm%d" % (i,i,i+60,i+60);
print "\033[39m\\033[39m - Reset colour"
print "\\033[2K - Clear Line"
print "\\033[<L>;<C>H OR \\033[<L>;<C>f puts the cursor at line L and column C."
print "\\033[<N>A Move the cursor up N lines"
print "\\033[<N>B Move the cursor down N lines"
print "\\033[<N>C Move the cursor forward N columns"
print "\\033[<N>D Move the cursor backward N columns"
print "\\033[2J Clear the screen, move to (0,0)"
print "\\033[K Erase to end of line"
print "\\033[s Save cursor position"
print "\\033[u Restore cursor position"
print " "
print "\\033[4m Underline on"
print "\\033[24m Underline off"
print "\\033[1m Bold on"
print "\\033[21m Bold off"
This prints
-w
is the GCC-wide option to disable warning messages.
Math
has static method where you can call directly like Math.abs()
while Date
has static method like Date.now()
and also instance method where you need to create new instance first var time = new Date()
to call time.getHours()
.
// The instance method of Date can be found on `Date.prototype` so you can just call:
var keys = Object.getOwnPropertyNames(Date.prototype);
// And for the static method
var keys = Object.getOwnPropertyNames(Date);
// But if the instance already created you need to
// pass its constructor
var time = new Date();
var staticKeys = Object.getOwnPropertyNames(time.constructor);
var instanceKeys = Object.getOwnPropertyNames(time.constructor.prototype);
Of course you will need to filter the obtained keys for the static method to get actual method names, because you can also get length, name
that aren't a function on the list.
But how if we want to obtain all available method from class that extend another class?
Of course you will need to scan through the root of prototype like using __proto__
. For saving your time you can use script below to get static method and deep method instance.
// var keys = new Set();_x000D_
function getStaticMethods(keys, clas){_x000D_
var keys2 = Object.getOwnPropertyNames(clas);_x000D_
_x000D_
for(var i = 0; i < keys2.length; i++){_x000D_
if(clas[keys2[i]].constructor === Function)_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
}_x000D_
_x000D_
function getPrototypeMethods(keys, clas){_x000D_
if(clas.prototype === void 0)_x000D_
return;_x000D_
_x000D_
var keys2 = Object.getOwnPropertyNames(clas.prototype);_x000D_
for (var i = keys2.length - 1; i >= 0; i--) {_x000D_
if(keys2[i] !== 'constructor')_x000D_
keys.add(keys2[i]);_x000D_
}_x000D_
_x000D_
var deep = Object.getPrototypeOf(clas);_x000D_
if(deep.prototype !== void 0)_x000D_
getPrototypeMethods(keys, deep);_x000D_
}_x000D_
_x000D_
// ====== Usage example ======_x000D_
// To avoid duplicate on deeper prototype we use `Set`_x000D_
var keys = new Set();_x000D_
getStaticMethods(keys, Date);_x000D_
getPrototypeMethods(keys, Date);_x000D_
_x000D_
console.log(Array.from(keys));
_x000D_
If you want to obtain methods from created instance, don't forget to pass the constructor
of it.
Direct link to awk version : http://www.shelldorado.com/scripts/cmds/urlencode
I used it for years and it works like a charm
:
##########################################################################
# Title : urlencode - encode URL data
# Author : Heiner Steven ([email protected])
# Date : 2000-03-15
# Requires : awk
# Categories : File Conversion, WWW, CGI
# SCCS-Id. : @(#) urlencode 1.4 06/10/29
##########################################################################
# Description
# Encode data according to
# RFC 1738: "Uniform Resource Locators (URL)" and
# RFC 1866: "Hypertext Markup Language - 2.0" (HTML)
#
# This encoding is used i.e. for the MIME type
# "application/x-www-form-urlencoded"
#
# Notes
# o The default behaviour is not to encode the line endings. This
# may not be what was intended, because the result will be
# multiple lines of output (which cannot be used in an URL or a
# HTTP "POST" request). If the desired output should be one
# line, use the "-l" option.
#
# o The "-l" option assumes, that the end-of-line is denoted by
# the character LF (ASCII 10). This is not true for Windows or
# Mac systems, where the end of a line is denoted by the two
# characters CR LF (ASCII 13 10).
# We use this for symmetry; data processed in the following way:
# cat | urlencode -l | urldecode -l
# should (and will) result in the original data
#
# o Large lines (or binary files) will break many AWK
# implementations. If you get the message
# awk: record `...' too long
# record number xxx
# consider using GNU AWK (gawk).
#
# o urlencode will always terminate it's output with an EOL
# character
#
# Thanks to Stefan Brozinski for pointing out a bug related to non-standard
# locales.
#
# See also
# urldecode
##########################################################################
PN=`basename "$0"` # Program name
VER='1.4'
: ${AWK=awk}
Usage () {
echo >&2 "$PN - encode URL data, $VER
usage: $PN [-l] [file ...]
-l: encode line endings (result will be one line of output)
The default is to encode each input line on its own."
exit 1
}
Msg () {
for MsgLine
do echo "$PN: $MsgLine" >&2
done
}
Fatal () { Msg "$@"; exit 1; }
set -- `getopt hl "$@" 2>/dev/null` || Usage
[ $# -lt 1 ] && Usage # "getopt" detected an error
EncodeEOL=no
while [ $# -gt 0 ]
do
case "$1" in
-l) EncodeEOL=yes;;
--) shift; break;;
-h) Usage;;
-*) Usage;;
*) break;; # First file name
esac
shift
done
LANG=C export LANG
$AWK '
BEGIN {
# We assume an awk implementation that is just plain dumb.
# We will convert an character to its ASCII value with the
# table ord[], and produce two-digit hexadecimal output
# without the printf("%02X") feature.
EOL = "%0A" # "end of line" string (encoded)
split ("1 2 3 4 5 6 7 8 9 A B C D E F", hextab, " ")
hextab [0] = 0
for ( i=1; i<=255; ++i ) ord [ sprintf ("%c", i) "" ] = i + 0
if ("'"$EncodeEOL"'" == "yes") EncodeEOL = 1; else EncodeEOL = 0
}
{
encoded = ""
for ( i=1; i<=length ($0); ++i ) {
c = substr ($0, i, 1)
if ( c ~ /[a-zA-Z0-9.-]/ ) {
encoded = encoded c # safe character
} else if ( c == " " ) {
encoded = encoded "+" # special handling
} else {
# unsafe character, encode it as a two-digit hex-number
lo = ord [c] % 16
hi = int (ord [c] / 16);
encoded = encoded "%" hextab [hi] hextab [lo]
}
}
if ( EncodeEOL ) {
printf ("%s", encoded EOL)
} else {
print encoded
}
}
END {
#if ( EncodeEOL ) print ""
}
' "$@"
You can do this through straight javascript and DOM, but I really recommend learning JQuery. Here is a function you can use to actually toggle that object.
EDIT: Adding the actual code:
Solution:
HTML snippet:
<a href="#" id="showAll" title="Show Tags">Show All Tags</a>
<ul id="tags" class="subforums" style="display:none;overflow-x: visible; overflow-y: visible; ">
<li>Tag 1</li>
<li>Tag 2</li>
<li>Tag 3</li>
<li>Tag 4</li>
<li>Tag 5</li>
</ul>
Javascript code using JQuery from Google's Content Distribution Network: https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
$(function() {
$('#showAll').click(function(){ //Adds click event listener
$('#tags').toggle('slow'); // Toggles visibility. Use the 'slow' parameter to add a nice effect.
});
});
You can test directly from this link: http://jsfiddle.net/vssJr/5/
Additional Comments on JQuery:
Someone has suggested that using JQuery for something like this is wrong because it is a 50k Library. I have a strong opinion against that.
JQuery is widely used because of the huge advantages it offers (like many other javascript frameworks). Additionally, JQuery is hosted by Content Distribution Networks (CDNs) like Google's CDN that will guarantee that the library is cached in the client's browser. It will have minimal impact on the client.
Additionally, with JQuery you can use powerful selectors, adding event listener, and use functions that are for the most part guaranteed to be cross-browser.
If you are a beginner and want to learn Javascript, please don't discount frameworks like JQuery. It will make your life so much easier.
Yes, Java SE is where to start. All the tasks you mention can be handled with it.
Java ME is the Mobile Edition, and EE is Enterprise Edition; these are specialized / extended versions of Standard Edition.
Go to the package.json
file, check the "@angular/core"
version. It is an actual project version.
... takes no arguments and has a void return type?
If you are writing for System.Windows.Forms
, You can also use:
public delegate void MethodInvoker()
I had the same problem and finally it appeared that they weren't attached to the same targets. The ObjC class is attached to Target1 and Target2, the Swift class is only attached to the Target1 and is not visible inside the ObjC class.
Hope this helps someone.
However, neither can find public static methods that are unused in a workspace. If anyone knows of such a tool then please let me know.
The best way I found:
Replace the TextView with an EditText with these extra attributes:
android:background="@null"
android:editable="false"
android:cursorVisible="false"
There is no need for wrapping in a ScrollView.
Give this a try:
PS> $nl = [Environment]::NewLine
PS> gci hklm:\software\microsoft\windows\currentversion\uninstall |
ForEach { $_.GetValue("DisplayName") } | Where {$_} | Sort |
Foreach {"$_$nl"} | Out-File addrem.txt -Enc ascii
It yields the following text in my addrem.txt file:
Adobe AIR
Adobe Flash Player 10 ActiveX
...
Note: on my system, GetValue("DisplayName") returns null for some entries, so I filter those out. BTW, you were close with this:
ForEach-Object -Process { "$_.GetValue("DisplayName") `n" }
Except that within a string, if you need to access a property of a variable, that is, "evaluate an expression", then you need to use subexpression syntax like so:
Foreach-Object -Process { "$($_.GetValue('DisplayName'))`r`n" }
Essentially within a double quoted string PowerShell will expand variables like $_
, but it won't evaluate expressions unless you put the expression within a subexpression using this syntax:
$(`<Multiple statements can go in here`>).
You need to enable that extension in your php.ini file. See Oracle Installation:
extension=oci8.so
Try this:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+elemA+"&lon="+elemB+"&setLatLon=Set";
To put a variable in a string enclose the variable in quotes and addition signs like this:
var myname = "BOB";
var mystring = "Hi there "+myname+"!";
Just remember that one rule!
In fact, if there is no definition of background-color
under some element, Chrome will output its background-color
as rgba(0, 0, 0, 0)
, while Firefox outputs is transparent
.
Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get
>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160
There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.
If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).
Here are the basic instructions:-
%CATALINA_HOME%/conf/server.xml
).<Connector
.protocol="HTTP/1.1"
.connectionTimeout
value is set on the connector, it may need to be increased - e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout
property value is set on the connector, the default is 60 seconds - if this is insufficient, the property may need to be added.In new version, you can try something like this
function (req,res) {
model.destroy({
where: {
id: req.params.id
}
})
.then(function (deletedRecord) {
if(deletedRecord === 1){
res.status(200).json({message:"Deleted successfully"});
}
else
{
res.status(404).json({message:"record not found"})
}
})
.catch(function (error){
res.status(500).json(error);
});
simply add + "<br />" +
is enough for a line break
Shamelessly adopted from Quickredfox.
jQuersy.fn.cssNum = function(){
return parseInt(jQuery.fn.css.apply(this, arguments), 10);
};
update
Changed to parseInt(val, 10)
since it is faster than parseFloat
.
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
If you need to convert the instance of System.Xml.Linq.XDocument into the instance of the System.Xml.XmlDocument this extension method will help you to do not lose the XML declaration in the resulting XmlDocument instance:
using System.Xml;
using System.Xml.Linq;
namespace www.dimaka.com
{
internal static class LinqHelper
{
public static XmlDocument ToXmlDocument(this XDocument xDocument)
{
var xmlDocument = new XmlDocument();
using (var reader = xDocument.CreateReader())
{
xmlDocument.Load(reader);
}
var xDeclaration = xDocument.Declaration;
if (xDeclaration != null)
{
var xmlDeclaration = xmlDocument.CreateXmlDeclaration(
xDeclaration.Version,
xDeclaration.Encoding,
xDeclaration.Standalone);
xmlDocument.InsertBefore(xmlDeclaration, xmlDocument.FirstChild);
}
return xmlDocument;
}
}
}
Hope that helps!
I coded a function (used in Django project for DecimalField) but it can be used in Python project :
This code :
Code with tests :
def convert_decimal_to_right(value, max_digits, decimal_places, signed=True):
integer_digits = max_digits - decimal_places
max_value = float((10**integer_digits)-float(float(1)/float((10**decimal_places))))
if signed:
min_value = max_value*-1
else:
min_value = 0
if value > max_value:
value = max_value
if value < min_value:
value = min_value
return round(value, decimal_places)
value = 12.12345
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.12
value = 12.126
nb = convert_decimal_to_right(value, 4, 2)
# nb : 12.13
value = 1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : 99.99
value = -1234.123
nb = convert_decimal_to_right(value, 4, 2)
# nb : -99.99
value = -1234.123
nb = convert_decimal_to_right(value, 4, 2, signed = False)
# nb : 0
value = 12.123
nb = convert_decimal_to_right(value, 8, 4)
# nb : 12.123
I don't know of any explicit fork
call in bash. What you probably want to do is append &
to a command that you want to run in the background. You can also use &
on functions that you define within a bash script:
do_something_with_line()
{
line=$1
foo
foo2
foo3
}
for line in file
do
do_something_with_line $line &
done
EDIT: to put a limit on the number of simultaneous background processes, you could try something like this:
for line in file
do
while [`jobs | wc -l` -ge 50 ]
do
sleep 5
done
do_something_with_line $line &
done
[myButton setTitle: @"myTitle" forState: UIControlStateNormal];
Use UIControlStateNormal
to set your title.
There are couple of states that UIbuttons provide, you can have a look:
[myButton setTitle: @"myTitle" forState: UIControlStateApplication];
[myButton setTitle: @"myTitle" forState: UIControlStateHighlighted];
[myButton setTitle: @"myTitle" forState: UIControlStateReserved];
[myButton setTitle: @"myTitle" forState: UIControlStateSelected];
[myButton setTitle: @"myTitle" forState: UIControlStateDisabled];
Make sure that the node server to provide the bundle is running in the background. To run start the server use npm start
or react-native start
and keep the tab open during development
Will "length" ever deviate from the real length of "s". If the answer is no, then you don't need to store length, because strings store their length already, and you can just call s.Length.
To get the syntax you asked for, you can implement an "implicit" operator like so:
static implicit operator MyStruct(string s) {
return new MyStruct(...);
}
The implicit operator will work, regardless of whether you make your struct mutable or not.
In addition to @Elltz answer, we can use both fill and image for background:
someNode.setBackground(
new Background(
Collections.singletonList(new BackgroundFill(
Color.WHITE,
new CornerRadii(500),
new Insets(10))),
Collections.singletonList(new BackgroundImage(
new Image("image/logo.png", 100, 100, false, true),
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.CENTER,
BackgroundSize.DEFAULT))));
Use
setBackground(
new Background(
Collections.singletonList(new BackgroundFill(
Color.WHITE,
new CornerRadii(0),
new Insets(0))),
Collections.singletonList(new BackgroundImage(
new Image("file:clouds.jpg", 100, 100, false, true),
BackgroundRepeat.NO_REPEAT,
BackgroundRepeat.NO_REPEAT,
BackgroundPosition.DEFAULT,
new BackgroundSize(1.0, 1.0, true, true, false, false)
))));
(different last argument) to make the image full-window size.
For those who like boost:
boost::filesystem::path mySourcePath("foo.bar");
boost::filesystem::path myTargetPath("bar.foo");
// Variant 1: Overwrite existing
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::overwrite_if_exists);
// Variant 2: Fail if exists
boost::filesystem::copy_file(mySourcePath, myTargetPath, boost::filesystem::copy_option::fail_if_exists);
Note that boost::filesystem::path is also available as wpath for Unicode. And that you could also use
using namespace boost::filesystem
if you do not like those long type names
I prefer the FOR loop in terms of performance. FOREACH is a little slow when you go with more number of items.
If you perform more business logic with the instance then FOREACH performs faster.
Demonstration: I created a list of 10000000 instances and looping with FOR and FOREACH.
Time took to loop:
Below is the sample code.
class Program
{
static void Main(string[] args)
{
List<TestClass> lst = new List<TestClass>();
for (int i = 1; i <= 10000000; i++)
{
TestClass obj = new TestClass() {
ID = i,
Name = "Name" + i.ToString()
};
lst.Add(obj);
}
DateTime start = DateTime.Now;
foreach (var obj in lst)
{
//obj.ID = obj.ID + 1;
//obj.Name = obj.Name + "1";
}
DateTime end = DateTime.Now;
var first = end.Subtract(start).TotalMilliseconds;
start = DateTime.Now;
for (int j = 0; j<lst.Count;j++)
{
//lst[j].ID = lst[j].ID + 1;
//lst[j].Name = lst[j].Name + "1";
}
end = DateTime.Now;
var second = end.Subtract(start).TotalMilliseconds;
}
}
public class TestClass
{
public long ID { get; set; }
public string Name { get; set; }
}
If I uncomment the code inside the loop: Then, time took to loop:
Conclusion
If you do more business logic with the instance, then FOREACH is recommended.
If you are not doing much logic with the instance, then FOR is recommended.
Compared to the methods listed here, I prefer the method that comes with the system. Here, I provide a better method without third-party libraries.
class colors: # You may need to change color settings
RED = '\033[31m'
ENDC = '\033[m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
print(colors.RED + "something you want to print in red color" + colors.ENDC)
print(colors.GREEN + "something you want to print in green color" + colors.ENDC)
print("something you want to print in system default color")
More color code , ref to : Printing Colored Text in Python
Enjoy yourself!