Internally, the rm command must test for file existence anyway,
so why add another test? Just issue
rm filename
and it will be gone after that, whether it was there or not.
Use rm -f is you don't want any messages about non-existent files.
If you need to take some action if the file does NOT exist, then you must test for that yourself. Based on your example code, this is not the case in this instance.
Java 8
return Collections.list(httpServletRequest.getParameterNames())
.stream()
.collect(Collectors.toMap(parameterName -> parameterName, httpServletRequest::getParameterValues));
called_from
must be null
. Add a test against that condition like
if (called_from != null && called_from.equalsIgnoreCase("add")) {
or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null
behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)
if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null
Based on the example here: http://drupal.org/node/550488
The following will probably work in .htaccess
<IfModule mod_expires.c>
# Enable expirations.
ExpiresActive On
# Cache all files for 2 weeks after access (A).
ExpiresDefault A1209600
<FilesMatch (\.js|\.html)$>
ExpiresActive Off
</FilesMatch>
</IfModule>
I am using React-Native 0.40 and below code works for me both on IOS and Android.
(Android-only) Sets the elevation of a view, using Android's underlying elevation API. This adds a drop shadow to the item and affects z-order for overlapping views. Only supported on Android 5.0+, has no effect on earlier versions.
class MainApp extends Component {
render() {
return (
<View style={styles.container}>
<View elevation={5} style={styles.buttonContainer}>
<Text style={styles.textStyle}>Shadow Applied</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF'
},
textStyle: {
color: '#FFFFFF'
},
buttonContainer: {
backgroundColor: '#2E9298',
borderRadius: 10,
padding: 10,
shadowColor: '#000000',
shadowOffset: {
width: 0,
height: 3
},
shadowRadius: 5,
shadowOpacity: 1.0
}
})
Tested on iPhone.
Edit
Comment from @ James. Thanks.
Note: For those on android, the backgroundColor is critical. I was using View as a container for another element and couldn't get a shadow until I specified a background color.
You could remove the folder and update the parent directory before committing:
rm -r some_dir
svn update some_dir_parent
This:
https://github.com/jbtule/cdto#cd-to
It's a small app that you drag into the Finder toolbar, the icon fits in very nicely. It works with Terminal, xterm (under X11), iterm.
Like for me -> working is:
string strUri2 = Directory.GetCurrentDirectory()+@"/Images/ok_progress.png";
image1.Source = new BitmapImage(new Uri(strUri2));
Using the first mechanism given there will do it.
<?php
...
?>
<div>
<h3><a href="#">First</a></h3>
<div>Lorem ipsum dolor sit amet.</div>
</div>
<div>
<?php
...
?>
For me
Adding this line
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
Before this line.
<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>
worked
Given the specific title of this post, here's my suggestion:
ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g'
The idea is to convert blanks to any unique character, like '<', and then change that into '\ ', a backslash followed by a blank. You can then pipe that into any command you like, such as:
ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g' | xargs -L1 GetFileInfo
The key here lies in the 'tr' and 'sed' commands; and you can use any character besides '<', such as '?' or even a tab-character.
I know it is an old question but there's two type of environment variables. The one owned with User and the one system wide. Depending how do you open git bash (with user privilege or with administrator privilege) the environment variable PATH used can be from you User variables or from System variables. See below:
as said in a previous answer, check with the command env|grep PATH
to see which one you are using and update your variable accordingly.
BTW, no need to reboot the system. Just close and reopen the git bash
As stated in the relevant RxJS documentation, the .subscribe()
method can take a third argument that is called on completion if there are no errors.
For reference:
[onNext]
(Function
): Function to invoke for each element in the observable sequence.[onError]
(Function
): Function to invoke upon exceptional termination of the observable sequence.[onCompleted]
(Function
): Function to invoke upon graceful termination of the observable sequence.
Therefore you can handle your routing logic in the onCompleted
callback since it will be called upon graceful termination (which implies that there won't be any errors when it is called).
this.httpService.makeRequest()
.subscribe(
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// 'onCompleted' callback.
// No errors, route to new page here
}
);
As a side note, there is also a .finally()
method which is called on completion regardless of the success/failure of the call. This may be helpful in scenarios where you always want to execute certain logic after an HTTP request regardless of the result (i.e., for logging purposes or for some UI interaction such as showing a modal).
Rx.Observable.prototype.finally(action)
Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
For instance, here is a basic example:
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/finally';
// ...
this.httpService.getRequest()
.finally(() => {
// Execute after graceful or exceptionally termination
console.log('Handle logging logic...');
})
.subscribe (
result => {
// Handle result
console.log(result)
},
error => {
this.errors = error;
},
() => {
// No errors, route to new page
}
);
If you are usgin Mysql a date column can be passed a String representation of this date
so i using the DateFormatter Class to format it and then set it as a String in the sql statement or prepared statement
here is the code illustration:
private String converUtilDateToSqlDate(java.util.Date utilDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String sqlDate = sdf.format(utilDate);
return sqlDate;
}
String date = converUtilDateToSqlDate(otherTransaction.getTransDate());
//then pass this date in you sql statement
SELECT
a.nameA, /* TableA.nameA */
d.nameD /* TableD.nameD */
FROM TableA a
INNER JOIN TableB b on b.aID = a.aID
INNER JOIN TableC c on c.cID = b.cID
INNER JOIN TableD d on d.dID = a.dID
WHERE DATE(c.`date`) = CURDATE()
I have faced the same problem with a character that I never managed to match with a where query - CHARINDEX, LIKE, REPLACE
, etc. did not work. Then I have used a brute force solution which is awful, heavy but works:
Step 1: make a copy of the complete data set - keep track of the original names with an source_id referencing the pk of the source table (and keep this source id in all the subsequent tables).
Step 2: LTRIM RTRIM
the data, and replace all double spaces, tab, etc (basically all the CHAR(1) to CHAR(32) by one space. Lowercase the whole set as well.
Step 3: replace all the special characters that you know (get the list of all the quotes, double quotes, etc.) by something from a-z (I suggest z). Basically replace everything that is not standard English characters by a z (using nested REPLACE of REPLACE in a loop).
Step 4: split by word into a second copy, where each word is in a separate row - the split is a SUBSTRING
based on the position of the space characters - at this point, we should miss the ones where there's a hidden space that we did not catche earlier.
Step 5: split each word into a third copy, where each letter is in a separate row (I know it makes a very large table) - keep track of the charindex of each letter in a separate column.
Step 6: Select everything in the above table which is not LIKE [a-z]. This is the list of the unidentified characters we want to exclude.
From the output of step 6 we have enough data to make a series of substring of the source to select everything but the unknown character we want to exclude.
Note 1: there are smart ways to optimize this, depending on the size of the original expression (steps 4, 5 and 6 can be made in one go).
Note 2: this is not very fast, but the fastest way to get this done for a large data set, because the split of lines into words and words into letters is made by substring, which slices all the table into one character slices. However, this is quite heavy to build. With a smaller set, it may be enough to parse each record one by one and search for character which is not in a list of all English characters plus all special characters.
<button class="btn btn-primary btn-lg" data-backdrop="static" data-keyboard="false" data-target="#myModal" data-toggle="modal">
Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.
Anyway, I'd just do this:
public Integer tryParse(Object obj) {
Integer retVal;
try {
retVal = Integer.parseInt((String) obj);
} catch (NumberFormatException nfe) {
retVal = 0; // or null if that is your preference
}
return retVal;
}
Additional comments to mti2935 good answer.
It seems the higher iteration the better protection against brute force, and you should use a high iteration as you can afford performance/resource wise.
On my my old Intel i3-7100 encrypting a rather big file 1.5GB:
time openssl enc -aes256 -e -pbkdf2 -iter 10000 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
Seconds: 2,564s
time openssl enc -aes256 -e -pbkdf2 -iter 262144 -pass pass:"mypassword" -in "InputFile" -out "OutputFile"
Seconds: 2,775s
Not really any difference, didn't check memory usage though(?)
With today's GPUs, and even faster tomorrows, I guess billion brute-force iteration seems possible every seconds.
12 years ago a NVIDIA GeForce 8800 Ultra
could iterate over 200.000 millions/sec iterations (MD5 hashing though)
==
takes precedence over in
, so you're actually testing word == True
.
>>> w = 'ab c'
>>> ' ' in w == True
1: False
>>> (' ' in w) == True
2: True
But you don't need == True
at all. if
requires [something that evalutes to True or False] and ' ' in word
will evalute to true or false. So, if ' ' in word: ...
is just fine:
>>> ' ' in w
3: True
Here's an alternate
req.hostname
Read about it in the Express Docs.
I tried neaumusic solution, but later found out that the only problem with destroy is the scope.
var chart;
function renderGraph() {
// Destroy old graph
if (chart) {
chart.destroy();
}
// Render chart
chart = new Chart(
document.getElementById(idChartMainWrapperCanvas),
chartOptions
);
}
Moving my chart variable outside the function scope, got it working for me.
Just setup UIBarButtonItem
with customView
For example:
var leftNavBarButton = UIBarButtonItem(customView:yourButton)
self.navigationItem.leftBarButtonItem = leftNavBarButton
or use setFunction
:
self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(customView: yourButton), animated: true);
I was also facing this issue even I was not using push notifications at all in my app.Making new provisioning profile also did not work for me.What I did was:-
1.Create fresh new certificate for Ad hoc & App Store only.
2.Then make distribution profile with this certificate and integrate profile with Xcode.
Then newly submitted build with this profile approved without any warning.
Set objShell = WScript.CreateObject("WScript.Shell")
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{9A25302D-30C0-39D9-BD6F-21E6EC160475}\"
with CreateObject("WScript.Shell")
on error resume next ' turn off error trapping
sValue = .regread(sKey) ' read attempt
bFound = (err.number = 0) ' test for success
end with
if bFound then
msgbox "exists"
else
msgbox "not exists"
End If
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
If you are using docker-compose, and in docker-compose.yml have:
volumes:
- .:/myapp
That means you local workspace is mapped to the container's /myapp folder.
Anything in /myapp will not be deleted for the volumes define.
You can delete ./tmp/pids/server.pid
in you local machine. Then the container's /myapp will not have this file.
I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.
Simple Key Pair JSON structure
var data = {
'XXXXXX' : '100.0',
'YYYYYYY' : '200.0',
'ZZZZZZZ' : '500.0',
}
Usage JavaScript code to access the key pairs
for (var key in data)
{ if (!data.hasOwnProperty(key))
{ continue; }
console.log(key + ' -> ' + data[key]);
};
Console output should look like this
XXXXXX -> 100.0
YYYYYYY -> 200.0
ZZZZZZZ -> 500.0
Here is a JSFiddle to show how it works.
I had similar issue before and in my case the file was in another machine so i have mapped network drive z to the folder location where my file is then i created a context in tomcat so in my web project i could access the HTML file via context
Following Traveling Tech Guy's answer, which already awesome, we can create a plugin and attach it to mongoose once we initialise it so that .upsert()
will be available on all models.
plugins.js
export default (schema, options) => {
schema.statics.upsert = async function(query, data) {
let record = await this.findOne(query)
if (!record) {
record = new this(data)
} else {
Object.keys(data).forEach(k => {
record[k] = data[k]
})
}
return await record.save()
}
}
db.js
import mongoose from 'mongoose'
import Plugins from './plugins'
mongoose.connect({ ... })
mongoose.plugin(Plugins)
export default mongoose
Then you can do something like User.upsert({ _id: 1 }, { foo: 'bar' })
or YouModel.upsert({ bar: 'foo' }, { value: 1 })
whenever you want.
Documentation here, and I'll use the Frankfurt region as an example.
But this url does not work:
The message is explicit: The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint.
I may be talking about another problem because I'm not getting NoSuchKey
error but I suspect the error message has been made clearer over time.
In 2015, if you still getting this confusing error, blame python default setuptools that PIP uses.
pip install -U setuptools
pip install blahblah
It will work fine.
UPDATE: It won't work fine for all libraries. I still get some error with few modules, that require lib-headers. They only thing that work flawlessly is Linux platform
If you want to run a script to a database:
mysql -u user -p data_base_name_here < db.sql
I would try putting a
Log.e("SOMETAG", "dialog button was clicked");
before the dialog.dismiss() line in your code to see if it actually reaches that section.
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
Just use the -H
parameter several times:
curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com
As of Spark 2.0, CSV can be read directly into a DataFrame
.
If the data file does not have a header row, then it would be:
val df = spark.read.csv("file://path/to/data.csv")
That will load the data, but give each column generic names like _c0
, _c1
, etc.
If there are headers then adding .option("header", "true")
will use the first row to define the columns in the DataFrame
:
val df = spark.read
.option("header", "true")
.csv("file://path/to/data.csv")
For a concrete example, let's say you have a file with the contents:
user,topic,hits
om,scala,120
daniel,spark,80
3754978,spark,1
Then the following will get the total hits grouped by topic:
import org.apache.spark.sql.functions._
import spark.implicits._
val rawData = spark.read
.option("header", "true")
.csv("file://path/to/data.csv")
// specifies the query, but does not execute it
val grouped = rawData.groupBy($"topic").agg(sum($"hits))
// runs the query, pulling the data to the master node
// can fail if the amount of data is too much to fit
// into the master node's memory!
val collected = grouped.collect
// runs the query, writing the result back out
// in this case, changing format to Parquet since that can
// be nicer to work with in Spark
grouped.write.parquet("hdfs://some/output/directory/")
// runs the query, writing the result back out
// in this case, in CSV format with a header and
// coalesced to a single file. This is easier for human
// consumption but usually much slower.
grouped.coalesce(1)
.write
.option("header", "true")
.csv("hdfs://some/output/directory/")
It is simple, $obj->{$obj->Name} the curly brackets will wrap the property much like a variable variable.
This was a top search. But did not resolve my question, which was using $this. In the case of my circumstance using the curly bracket also helped...
example with Code Igniter get instance
in an sourced library class called something with a parent class instance
$this->someClass='something';
$this->someID=34;
the library class needing to source from another class also with the parents instance
echo $this->CI->{$this->someClass}->{$this->someID};
MozWebSocket
MozWebSocket
Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.
See caniuse for the current status of WebSockets support in desktop and mobile browsers.
See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.
It depends on which language you use.
In Java/Java EE:
V 7.5 supports RFC6455
- Jetty 9.1 supports javax.websocket / JSR 356)V 3.1.2 supports RFC6455
V 4.0.25 supports RFC6455
V 7.0.28 supports RFC6455
Some other Java implementations:
V 5.6 supports RFC6455
V 2.10 supports RFC6455
In C#:
In PHP:
In Python:
In C:
In Node.js:
Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :
Pusher.com is a Websocket cloud service accessible through a REST API.
DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.
Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.
For other language implementations, see the Wikipedia article for more information.
The RFC for Websockets : RFC6455
I think max value of int(11) is 4294967295
Implicit Wait
An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
Explicit Wait + Expected Conditions
An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("someid")));
import os
import shutil
os.chdir('C:\\') #Make sure you add your source and destination path below
dir_src = ("C:\\foooo\\")
dir_dst = ("C:\\toooo\\")
for filename in os.listdir(dir_src):
if filename.endswith('.txt'):
shutil.copy( dir_src + filename, dir_dst)
print(filename)
For posterity, your question was how to send an http request to https://stackoverflow.com/questions
. The real answer is: you cannot with telnet, cause this is an https-only reachable url.
So, you might want to use openssl
instead of telnet
, like this for instance
$ openssl s_client -connect stackoverflow.com:443
...
---
GET /questions HTTP/1.1
Host: stackoverflow.com
This will give you the https response.
I had to include -lmysqlcppconn to my build in order to get it to work.
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
OR
you can write this down in your program
Private Sub ComboBoxExp_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles MyBase.Load
AlarmHourSelect.Text = "YOUR DEFAULT VALUE"
AlarmMinuteSelect.Text = "YOUR DEFAULT VALUE"
End Sub
so when you start your program, the first thing it would do is set it on your assigned default value and later you can easily select your required option from the drop down list. also keeping the DropDownStyle to DropDownList would make it look more cooler.
-Starkternate
The quickest and easiest way I've found to Json-ify POJOs is to use the Gson library. This blog post gives a quick overview of using the library.
It seems System.gc()
do not work on Art Android 6.0.1 Nexus 5x, So I use Runtime.getRuntime().gc();
instead.
Put your query (e.g. db.someCollection.find().pretty()
) to a javascript file, let's say query.js
. Then run it in your operating system's shell using command:
mongo yourDb < query.js > outputFile
Query result will be in the file named 'outputFile'.
By default Mongo prints out first 20 documents IIRC. If you want more you can define new value to batch size in Mongo shell, e.g.
DBQuery.shellBatchSize = 100
.
I wanted to do this the angular (2/4)
way, here is what I did:
<div [class.show]="visible" [class.in]="visible" class="modal fade" id="confirm-dialog-modal" role="dialog">
..
</div>`
Important things to note:
visible
is a variable (boolean) in the component which governs modal's visibility.show
and in
are bootstrap classes.Component
@ViewChild('rsvpModal', { static: false }) rsvpModal: ElementRef;
..
@HostListener('document:keydown.escape', ['$event'])
onEscapeKey(event: KeyboardEvent) {
this.hideRsvpModal();
}
..
hideRsvpModal(event?: Event) {
if (!event || (event.target as Element).classList.contains('modal')) {
this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'none');
this.renderer.removeClass(this.rsvpModal.nativeElement, 'show');
this.renderer.addClass(document.body, 'modal-open');
}
}
showRsvpModal() {
this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'block');
this.renderer.addClass(this.rsvpModal.nativeElement, 'show');
this.renderer.removeClass(document.body, 'modal-open');
}
Html
<!--S:RSVP-->
<div class="modal fade" #rsvpModal role="dialog" aria-labelledby="niviteRsvpModalTitle" (click)="hideRsvpModal($event)">
<div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="niviteRsvpModalTitle">
</h5>
<button type="button" class="close" (click)="hideRsvpModal()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary bg-white text-dark"
(click)="hideRsvpModal()">Close</button>
</div>
</div>
</div>
</div>
<!--E:RSVP-->
Yes, you can do this by creating a DoubleStream
from the array, filtering out the negatives, and converting the stream back to an array. Here is an example:
double[] d = {8, 7, -6, 5, -4};
d = Arrays.stream(d).filter(x -> x > 0).toArray();
//d => [8, 7, 5]
If you want to filter a reference array that is not an Object[]
you will need to use the toArray
method which takes an IntFunction
to get an array of the original type as the result:
String[] a = { "s", "", "1", "", "" };
a = Arrays.stream(a).filter(s -> !s.isEmpty()).toArray(String[]::new);
SongsTableSeeder.php should be in database/seeds directory
Console command steps:
composer dump-autoload
and then:
php artisan cache:clear
and then:
php artisan optimize
and then:
php artisan db:seed
or:
php artisan db:seed --class=SongsTableSeeder
cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:
http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html
It takes multiple comma separated matrices and data.frames as input :) You just need to
install.packages("gdata", dependencies=TRUE)
and then
library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)
Note that git checkout --ours|--theirs
will overwrite the files entirely, by choosing either theirs
or ours
version, which might be or might not be what you want to do (if you have any non-conflicted changes coming from the other side, they will be lost).
If instead you want to perform a three-way merge on the file, and only resolve the conflicted hunks using --ours|--theirs
, while keeping non-conflicted hunks from both sides in place, you may want to resort to git merge-file
; see details in this answer.
If your integer is timestamp in milliseconds use:
SELECT strftime("%Y-%d-%m", col_name, 'unixepoch') AS col_name
It will format milliseconds to yyyy-mm-dd string.
In Ubuntu, you can install libtool
which resolves the libraries automatically.
$ sudo apt-get install libtool
This resolved a problem with ltdl
for me, which had been installed as libltdl.so.7
and wasn't found as simply -lltdl
in the make.
A method quite frequently used in Oracle is something like this:
select trunc(sysdate)-rn
from
( select rownum rn
from dual
connect by level <= 365)
/
Personally, if an application has a need for a list of dates then I'd just create a table with them, or create a table with a series of integers up to something ridiculous like one million that can be used for this sort of thing.
If You Need to Replace Strings in Multiple Files:
It should be noted that the different methods posted here can be wildly different with regard to the time it takes to complete. For me, I regularly have large numbers of small files. To test what is most performant, I extracted 5.52 GB (5,933,604,999 bytes) of XML in 40,693 separate files and ran through three of the answers I found here:
## 5.52 GB (5,933,604,999 bytes) of XML files (40,693 files)
#### Test 1 - Plain Replace
$start = get-date
$xmls = (Get-ChildItem -Path "I:\TestseT\All_XML" -Recurse -Filter *.xml).FullName
foreach ($xml in $xmls)
{
(Get-Content $xml).replace("'", " ") | Set-Content $xml
}
$end = get-date
NEW-TIMESPAN –Start $Start –End $End
<#
TotalMinutes: 103.725113128333
#>
#### Test 2 - Replace with -Raw
$start = get-date
$xmls = (Get-ChildItem -Path "I:\TestseT\All_XML" -Recurse -Filter *.xml).FullName
foreach ($xml in $xmls)
{
(Get-Content $xml -Raw).replace("'", " ") | Set-Content $xml
}
$end = get-date
NEW-TIMESPAN –Start $Start –End $End
<#
TotalMinutes: 10.1600227983333
#>
#### Test 3 - .NET, System.IO
$start = get-date
$xmls = (Get-ChildItem -Path "I:\TestseT\All_XML" -Recurse -Filter *.xml).FullName
foreach ($xml in $xmls)
{
$txt = [System.IO.File]::ReadAllText("$xml").Replace("'"," ")
[System.IO.File]::WriteAllText("$xml", $txt)
}
$end = get-date
NEW-TIMESPAN –Start $Start –End $End
<#
TotalMinutes: 5.83619516833333
#>
You can save excel
as unicode
text, it is tab-delimited.
Steps to install Spark in local mode:
Install Java 7 or later.
To test java installation is complete, open command prompt type java
and hit enter.
If you receive a message 'Java' is not recognized as an internal or external command.
You need to configure your environment variables, JAVA_HOME
and PATH
to point to the path of jdk.
Set SCALA_HOME
in Control Panel\System and Security\System
goto "Adv System settings" and add %SCALA_HOME%\bin
in PATH variable in environment variables.
Install Python 2.6 or later from Python Download link.
Download SBT. Install it and set SBT_HOME
as an environment variable with value as <<SBT PATH>>
.
Download winutils.exe
from HortonWorks repo or git repo. Since we don't have a local Hadoop installation on Windows we have to download winutils.exe
and place it in a bin
directory under a created Hadoop
home directory.
Set HADOOP_HOME = <<Hadoop home directory>>
in environment variable.
We will be using a pre-built Spark package, so choose a Spark pre-built package for Hadoop Spark download. Download and extract it.
Set SPARK_HOME
and add %SPARK_HOME%\bin
in PATH variable in environment variables.
Run command: spark-shell
Open http://localhost:4040/
in a browser to see the SparkContext web UI.
Before proceeding:
Install a proper mergetool. On Linux, I strongly suggest you to use meld:
sudo apt-get install meld
Configure your mergetool:
git config --global merge.tool meld
Then, iterate in the following way:
git cherry-pick ....
git mergetool
git cherry-pick --continue
What exactly is OAuth (Open Authorization)?
OAuth allows notifying a resource provider (e.g. Facebook) that the resource owner (e.g. you) grants permission to a third-party (e.g. a Facebook Application) access to their information (e.g. the list of your friends).
If you read it stated as plainly, I would understand your confusion. So let's go with a concrete example: joining yet another social network!
Say you have an existing GMail account. You decide to join LinkedIn. Adding all of your many, many friends manually is tiresome and error-prone. You might get fed up half-way or insert typos in their e-mail address for invitation. So you might be tempted not to create an account after all.
Facing this situation, LinkedIn has the Good Idea(TM) to write a program that adds your list of friends automatically because computers are far more efficient and effective at tiresome and error prone tasks. Since joining the network is now so easy, there is no way you would refuse such an offer, now would you?
Without an API for exchanging this list of contacts, you would have to give LinkedIn the username and password to your GMail account, thereby giving them too much power.
This is where OAuth comes in. If your GMail supports the OAuth protocol, then LinkedIn can ask you to authorize them to access your GMail list of contacts.
OAuth allows for:
Will it become a de facto (standard?) in near future?
Well, although OAuth is a significant step forward, it doesn't solve problems if people don't use it correctly. For instance, if a resource provider gives only a single read-write access level to all your resources at once and doesn't provide mechanism for managing access, then there is no point to it. In other words, OAuth is a framework to provide authorization functionality and not just authentication.
In practice, it fits the social network model very well. It is especially popular for those social networks that want to allow third-party "plugins". This is an area where access to the resources is inherently necessary and is also inherently unreliable (i.e. you have little or no quality control over those applications).
I haven't seen so many other uses out in the wild. I mean, I don't know of an online financial advice firm that will access your bank records automatically, although it could technically be used that way.
You can use the DataGridViewCell.Value Property to retrieve the value stored in a particular cell.
So to retrieve the value of the 'first' selected Cell and display in a MessageBox, you can:
MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());
The above probably isn't exactly what you need to do. If you provide more details we can provide better help.
Piggybacking on what the other answers say, since you don't know how to do them at all, here's an example of how you might do it in JavaScript:
var charactersOnly = "This contains only characters";
var nonCharacters = "This has _@#*($()*@#$(*@%^_(#@!$ non-characters";
if (charactersOnly.search(/[^a-zA-Z]+/) === -1) {
alert("Only characters");
}
if (nonCharacters.search(/[^a-zA-Z]+/)) {
alert("There are non characters.");
}
The /
starting and ending the regular expression signify that it's a regular expression. The search
function takes both strings and regexes, so the /
are necessary to specify a regex.
From the MDN Docs, the function returns -1
if there is no match.
Also note: that this works for only a-z, A-Z. If there are spaces, it will fail.
You can use this below.
rename --no-act 's/\.html$/\.php/' *.html */*.html
Switch is not same as if-else-if.
Switch is used when there is one expression that gets evaluated to a value and that value can be one of predefined set of values. If you need to perform multiple boolean / comparions operations run-time then if-else-if needs to be used.
Vertical align, dynamic height combined with absolute position is except some special conditions not possible without a few lines of JS (eg. jQuery). (can possibly be solved with backend code in some cases, or min-height combined with sensible top or margin styles, but not perfect)
I mostly only use absolute position when something is supposed to "popup" in relation to something else which is in the float, I think that's the best way to use it so you don't have to fiddle with things like this.
No offense, but most answers in here are way off.
Not sure if your teacher allows you to use filters but...
filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h")
returns-
'aaasdffgh'
Much more efficient than looping...
Example:
for i in range(10):
a.replace(str(i),'')
The accepted answer here does not work for my use case. I needed to be able to dynamically create parameters in one job and pass them into another. As Mark McKenna mentions there is seemingly no way to export a variable from a shell build step to the post build actions.
I achieved a workaround using the Parameterized Trigger Plugin by writing the values to a file and using that file as the parameters to import via 'Add post-build action' -> 'Trigger parameterized build...' then selecting 'Add Parameters' -> 'Parameters from properties file'.
EDIT: Updated for jQuery 1.8
Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: Added code to make it a jQuery function.
For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.
var rotation = 0;
jQuery.fn.rotate = function(degrees) {
$(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
'-moz-transform' : 'rotate('+ degrees +'deg)',
'-ms-transform' : 'rotate('+ degrees +'deg)',
'transform' : 'rotate('+ degrees +'deg)'});
return $(this);
};
$('.rotate').click(function() {
rotation += 5;
$(this).rotate(rotation);
});
EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.
Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.
Here is a jsFiddle.
If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.
HTML
<div class="rotate">
<h1>Rotatey text</h1>
</div>
CSS
/* Totally for style */
.rotate {
background: #F02311;
color: #FFF;
width: 200px;
height: 200px;
text-align: center;
font: normal 1em Arial;
position: relative;
top: 50px;
left: 50px;
}
/* The real code */
.rotated {
-webkit-transform: rotate(45deg); /* Chrome, Safari 3.1+ */
-moz-transform: rotate(45deg); /* Firefox 3.5-15 */
-ms-transform: rotate(45deg); /* IE 9 */
-o-transform: rotate(45deg); /* Opera 10.50-12.00 */
transform: rotate(45deg); /* Firefox 16+, IE 10+, Opera 12.10+ */
}
jQuery
Make sure these are wrapped in $(document).ready
$('.rotate').click(function() {
$(this).toggleClass('rotated');
});
Custom intervals
var rotation = 0;
$('.rotate').click(function() {
rotation += 5;
$(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
'-moz-transform' : 'rotate('+ rotation +'deg)',
'-ms-transform' : 'rotate('+ rotation +'deg)',
'transform' : 'rotate('+ rotation +'deg)'});
});
If you are using 1.0, try making a custom templatetag that looks like this:
def adminpageurl(object, link=None):
if link is None:
link = object
return "<a href=\"/admin/%s/%s/%d\">%s</a>" % (
instance._meta.app_label,
instance._meta.module_name,
instance.id,
link,
)
then just use {% adminpageurl my_object %} in your template (don't forget to load the templatetag first)
To find out if it's visible with plain JavaScript, check whether the display property is 'none' (don't check for 'block', it could also be blank or 'inline' and still be visible):
var isVisible = (elt.style.display != "none");
If you are using jQuery, you can use this instead:
var isVisible = $elt.is(":visible");
Nowadays - using C++11 - you can use enum class for this:
enum class Color { RED, BLUE, WHITE };
AFAII this does exactly what you want.
To quote a quote:
The data- attributes are pulled in the first time the data property is accessed and then are no longer accessed or mutated (all data values are then stored internally in jQuery).
.data()
- jQuery Documentiation
Note that this (Frankly odd) limitation is only withheld to the use of .data()
.
The solution? Use .attr
instead.
Of course, several of you may feel uncomfortable with not using it's dedicated method. Consider the following scenario:
Common sense - Why would they change an already established attribute like that? Just imagine class
begin renamed to group and id
to identifier. The Internet would break.
And even then, Javascript itself has the ability to fix this - And of course, despite it's infamous incompatibility with HTML, REGEX (And a variety of similar methods) could rapidly rename your attributes to this new-mythical 'standard'.
TL;DR
alert($(targetField).attr("data-helptext"));
a lot of people say to use int(x)
, and this works ok for most cases, but there is a little problem. If OP's result is:
x = 1.9999999999999999
it will round to
x = 2
after the 16th 9 it will round. This is not a big deal if you are sure you will never come across such thing. But it's something to keep in mind.
Read the file line by line and then add it on a list in reverse order.
Here is an example of code :
reverse = []
with open("file.txt", "r") as file:
for line in file:
line = line.strip()
reverse[0:0] = line
I haven't managed to get WMDC working on Windows 10 (it hanged on splash screen upon start), so I've finally uninstalled it. But now I have a Portable Devices / Compact device in the Device Manager and I can browse my Windows Compact 7 device within Windows Explorer. All my apps using RAPI also work. Maybe this is the result of installing/uninstalling WMDC, or probably this functionality was already presented on Windows 10 and I've just overlooked it initially.
You need to double the backslashes used to escape the regular expression special characters. However, as @Bohemian points out, most of those backslashes aren't needed. Unfortunately, his answer suffers from the same problem as yours. What you actually want is:
The backslash is being interpreted by the code that reads the string, rather than passed to the regular expression parser. You want:
"[\\[\\]?*+|{}\\\\()@.\n\r]"
Note the quadrupled backslash. That is definitely needed. The string passed to the regular expression compiler is then identical to @Bohemian's string, and works correctly.
void input_from_key_board(int &ri, int &ci)
{
char ch = 'x';
if (_kbhit())
{
ch = _getch();
if (ch == -32)
{
ch = _getch();
switch (ch)
{
case 72: { ri--; break; }
case 80: { ri++; break; }
case 77: { ci++; break; }
case 75: { ci--; break; }
}
}
else if (ch == '\r'){ gotoRowCol(ri++, ci -= ci); }
else if (ch == '\t'){ gotoRowCol(ri, ci += 5); }
else if (ch == 27) { system("ipconfig"); }
else if (ch == 8){ cout << " "; gotoRowCol(ri, --ci); if (ci <= 0)gotoRowCol(ri--, ci); }
else { cout << ch; gotoRowCol(ri, ci++); }
gotoRowCol(ri, ci);
}
}
Use value instanceof YourClass
Firstly, the Instagram API endpoint "tags" required OAuth authentication.
You can query results for a particular hashtag (snowy in this case) using the following url
It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour
https://api.instagram.com/v1/tags/snowy/media/recent
Sample response
{
"pagination": {
"next_max_tag_id": "1370433362010",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "1370433362010",
"next_min_id": "1370443976800",
"min_tag_id": "1370443976800",
"next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"snowy"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": null,
"created_time": "1370418343",
"link": "http://instagram.com/p/aK1yrGRi3l/",
"likes": {
"count": 1,
"data": [
{
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
}
]
},
"images": {
"low_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
"width": 306,
"height": 306
},
"thumbnail": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
"width": 612,
"height": 612
}
},
"users_in_photo": [],
"caption": {
"created_time": "1370418353",
"text": "#snowy",
"from": {
"username": "iri92lol",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"id": "404174490",
"full_name": "Iri"
},
"id": "471425773832908504"
},
"user_has_liked": false,
"id": "471425689728724453_404174490",
"user": {
"username": "iri92lol",
"website": "",
"profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
"full_name": "Iri",
"bio": "",
"id": "404174490"
}
}
}
You can play around here :
You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.
All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.
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.
To quickly resolve this, use this very helpful shortcut in Android Studio:
Right-click widget-in-question > Constraint Layout > Infer Constraints:
Thereafter, you can tweak the constraints as described here: https://stackoverflow.com/a/37960888/5556250
Update
This is not correct for the Android Studio v3 and up. As per @purpleladydragons's comment:
"Constraint Layout" is not in the dropdown menu. Use the magic wand icon in the toolbar menu above the design preview; there is the "Infer Constraints" button.
In Swift 4.2 and Xcode 10.1
//Create image view simply like this.
let imgView = UIImageView()
imgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
imgView.image = UIImage(named: "yourimagename")//Assign image to ImageView
imgView.imgViewCorners()
view.addSubview(imgView)//Add image to our view
//Add image view properties like this(This is one of the way to add properties).
extension UIImageView {
//If you want only round corners
func imgViewCorners() {
layer.cornerRadius = 10
layer.borderWidth = 1.0
layer.masksToBounds = true
}
}
You can't. At the time of writing, the only HTML form element that's designed to be multi-line is <textarea>
.
<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For more info - https://angular.io/guide/router#query-parameters-and-fragments
Hey use this utility class if you are on spring.
ReflectionTestUtils.invokeMethod(new ClassName(), "privateMethodName");
Horrible Answers Galore
Ozgur Ozcitak
When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.
This is completely wrong.
Mats Fredriksson
When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.
This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.
smh
Your addition operation causes the int to be converted to an unsigned int.
Wrong. Maybe it does and maybe it doesn't.
Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)
Wrong. It is either undefined behavior if it causes overflow or the value is preserved.
Anonymous
The value of i is converted to unsigned int ...
Wrong. Depends on the precision of an int relative to an unsigned int.
Taylor Price
As was previously answered, you can cast back and forth between signed and unsigned without a problem.
Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.
Now I can finally answer the question.
Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 [1]. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.
Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.
What is precision?
Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.
[Gotchas]
The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.
[1] The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.
#!/bin/bash
START_TIME=$(date +%s)
sleep 4
echo "Total time elapsed: $(date -ud "@$(($(date +%s) - $START_TIME))" +%T) (HH:MM:SS)"
$ ./total_time_elapsed.sh
Total time elapsed: 00:00:04 (HH:MM:SS)
Open the procedure in SQL Developer and run it from there. SQL Developer displays the SQL that it runs.
BEGIN
PROCEEDURE_NAME_HERE();
END;
It appears that your HTML syntax is incorrect for the table cell. Before you try the other idea below, confirm if this works or not... You can also try adding this to your table itself: table-layout:fixed.. .
<td style="overflow: hidden; width: 280px; text-align: left; valign: top; whitespace: nowrap;">
[content]
</td>
New HTML
<td>
<div class="MyClass"">
[content]
</div>
</td>
CSS Class:
.MyClass{
height: 280px;
width: 456px;
overflow: hidden;
white-space: nowrap;
}
Python Unittest, Bat process Error Codes:
if __name__ == "__main__":
test_suite = unittest.TestSuite()
test_suite.addTest(RunTestCases("test_aggregationCount_001"))
runner = unittest.TextTestRunner()
result = runner.run(test_suite)
# result = unittest.TextTestRunner().run(test_suite)
if result.wasSuccessful():
print("############### Test Successful! ###############")
sys.exit(1)
else:
print("############### Test Failed! ###############")
sys.exit()
Bat codes:
@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
echo Error found. Waiting here...
pause
) || (
echo This time of test is ok.
)
)
You can add references to your model through command line in the following manner:
rails g migration add_column_to_tester user_id:integer
This will generate a migration file like :
class AddColumnToTesters < ActiveRecord::Migration
def change
add_column :testers, :user_id, :integer
end
end
This works fine every time i use it..
Starting with PHP 8 (2020-11-24), you can use str_contains:
if (str_contains('www.domain.com/car/', 'car')) {
echo 'car is exist';
} else {
echo 'no cars';
}
This should work if current file is located in same directory where initcontrols is:
<?php
$ds = DIRECTORY_SEPARATOR;
$base_dir = realpath(dirname(__FILE__) . $ds . '..') . $ds;
require_once("{$base_dir}initcontrols{$ds}config.php");
?>
<div>
<?php
$file = "{$base_dir}initcontrols{$ds}header_myworks.php";
include_once($file);
echo $plHeader;?>
</div>
You can use Ruby's Net::HTTP
class:
require 'net/http'
url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts res.body
There's a function called dropNamed()
in Bernd Bischl's BBmisc
package that does exactly this.
BBmisc::dropNamed(df, "x")
The advantage is that it avoids repeating the data frame argument and thus is suitable for piping in magrittr
(just like the dplyr
approaches):
df %>% BBmisc::dropNamed("x")
You're storing the .Text
properties of the textboxes directly into the database, this doesn't work. The .Text
properties are String
s (i.e. simple text) and not typed as DateTime
instances. Do the conversion first, then it will work.
Do this for each date parameter:
Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) )
Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse
or DateTime.TryParseExact
, but implementing that is an exercise for the reader.
As other guys commented before you can write your own procedure with anonymous function to solve this issue.
I used two ways to solve it:
func Find(slice interface{}, f func(value interface{}) bool) int {
s := reflect.ValueOf(slice)
if s.Kind() == reflect.Slice {
for index := 0; index < s.Len(); index++ {
if f(s.Index(index).Interface()) {
return index
}
}
}
return -1
}
Uses example:
type UserInfo struct {
UserId int
}
func main() {
var (
destinationList []UserInfo
userId int = 123
)
destinationList = append(destinationList, UserInfo {
UserId : 23,
})
destinationList = append(destinationList, UserInfo {
UserId : 12,
})
idx := Find(destinationList, func(value interface{}) bool {
return value.(UserInfo).UserId == userId
})
if idx < 0 {
fmt.Println("not found")
} else {
fmt.Println(idx)
}
}
Second method with less computational cost:
func Search(length int, f func(index int) bool) int {
for index := 0; index < length; index++ {
if f(index) {
return index
}
}
return -1
}
Uses example:
type UserInfo struct {
UserId int
}
func main() {
var (
destinationList []UserInfo
userId int = 123
)
destinationList = append(destinationList, UserInfo {
UserId : 23,
})
destinationList = append(destinationList, UserInfo {
UserId : 123,
})
idx := Search(len(destinationList), func(index int) bool {
return destinationList[index].UserId == userId
})
if idx < 0 {
fmt.Println("not found")
} else {
fmt.Println(idx)
}
}
Like we have date "07/May/2018" and we need date "2018-05-07" as mysql compatible
if (!empty($date)) {
$timestamp = strtotime($date);
if ($timestamp === FALSE) {
$timestamp = strtotime(str_replace('/', '-', $date));
}
$date = date('Y-m-d', $timestamp);
}
It works for me. enjoy :)
Here is the easiest way I use, hope works for you,
var1 = var1 or 4
This assigns 4
to var1
only if var1
is None
, False
or 0
Use a subselect:
SELECT row FROM table WHERE id=(
SELECT max(id) FROM table
)
Note: ID must be unique, else multiple rows are returned
Just delete key:
HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration
Or run in command line:
reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f
You cant directly access anything under the WEB-INF
foldere. When browsers request your CSS file, they can not see inside the WEB-INF folder.
Try putting your files css/css
folder under WebContent
.
And add the following in dispatcher servlet to grant access ,
<mvc:resources mapping="/css/**" location="/css/" />
similarly for your js files . A Nice example here on this
You can declare a new type:
declare type MyHandler = (myArgument: string) => void;
var handler: MyHandler;
The declare
keyword is not necessary. It should be used in the .d.ts files or in similar cases.
You should create a variable of the type SelectionneNonSelectionne.
struct SelectionneNonSelectionne var;
After that pass that variable to the function like
characterSelection(screen, var);
The error is caused since you are passing the type name SelectionneNonSelectionne
I've colour coded this figure to ease the process.
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
You can have full control over the figure using these commands, to complete the answer I've add also the control over the splines:
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
# X AXIS -BORDER
ax.spines['bottom'].set_visible(False)
# BLUE
ax.set_xticklabels([])
# RED
ax.set_xticks([])
# RED AND BLUE TOGETHER
ax.axes.get_xaxis().set_visible(False)
# Y AXIS -BORDER
ax.spines['left'].set_visible(False)
# YELLOW
ax.set_yticklabels([])
# GREEN
ax.set_yticks([])
# YELLOW AND GREEN TOGHETHER
ax.axes.get_yaxis().set_visible(False)
I was able to fix similar errors by changeing
http://ip-address/html/ci3-fire-starter/htdocs/index.php/
on the application/config/config.php line 26.
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
The easiest way to do it is using Storyboard and a Segue.
Just create a Segue from the FirstViewController (not the Navigation Controller) of your TabBarController to a LoginViewController with the login UI and name it "showLogin".
Create a method that returns a BOOL to validate if the user logged in and/or his/her session is valid... preferably on the AppDelegate. Call it isSessionValid.
On your FirstViewController.m override the method viewDidAppear as follows:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if([self isSessionValid]==NO){
[self performSegueWithIdentifier:@"showLogin" sender:self];
}
}
Then if the user logged in successfully, just dismiss or pop-out the LoginViewController to show your tabs.
Works 100%!
Hope it helps!
Try this code:
<input type="text" name="Phone Number" pattern="[7-9]{1}[0-9]{9}"
title="Phone number with 7-9 and remaing 9 digit with 0-9">
This code will inputs only in the following format:
9238726384 (starting with 9 or 8 or 7 and other 9 digit using any number)
8237373746
7383673874
Incorrect format:
2937389471(starting not with 9 or 8 or 7)
32796432796(more than 10 digit)
921543(less than 10 digit)
dict.keys.sorted()
that gives [String] https://developer.apple.com/documentation/swift/array/2945003-sorted
Put this in your window constructor
WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
.NET FrameworkSupported in: 4, 3.5, 3.0
.NET Framework Client ProfileSupported in: 4, 3.5 SP1
Use CSS: overflow:
.thumb {
width:230px;
height:230px;
overflow:hidden
}
Checkout points the head at a specific commit.
Reset points a branch at a specific commit. (A branch is a pointer to a commit.)
Incidentally, if your head doesn’t point to a commit that’s also pointed to by a branch then you have a detached head. (turned out to be wrong. See comments...)
I think it's worth pointing out that jQuery sorts this out nicely with $.each()
.
See: .each()
Example:
$('.foo').each(function() {
console.log($(this));
});
$(this)
being the single item inside the object. Swap $('.foo')
to a variable if you don't want to use jQuery's selector engine.
Simple example for how to set JAVA_HOME with setx.exe
in command line:
setx JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"
This will set environment variable "JAVA_HOME" for current user. If you want to set a variable for all users, you have to use option "-m". Here is an example:
setx -m JAVA_HOME "C:\Program Files (x86)\Java\jdk1.7.0_04"
Note: you have to execute this command as Administrator.
Note: Make sure to run the command setx from an command-line Admin window
def normalize_seconds(seconds: int) -> tuple:
(days, remainder) = divmod(seconds, 86400)
(hours, remainder) = divmod(remainder, 3600)
(minutes, seconds) = divmod(remainder, 60)
return namedtuple("_", ("days", "hours", "minutes", "seconds"))(days, hours, minutes, seconds)
So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.
protected void onCreate(Bundle savedInstanceState) { setContentView(R.layout.my_layout); Bitmap bitmap = getIntent().getParcelableExtra("image"); ImageView imageView = (ImageView) findViewById(R.id.imageview); imageView.setImageBitmap(bitmap); }
For future googlers, FYI, the method in the answer by @meder , can be used with any element that has a name attribute, so lets say theres an <iframe>
with the name xyz
then you can use the rule as belows.
iframe[name=xyz] {
display: none;
}
The name
attribute can be used on the following elements:
<button>
<fieldset>
<form>
<iframe>
<input>
<keygen>
<map>
<meta>
<object>
<output>
<param>
<select>
<textarea>
If you don't want something complicated, then:
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
Using this Log-Entry
framework:
Script:
Function Main {
Log -File "D:\Apps\Logs\$Env:computername.log"
$tcp = (get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductVersionRaw
$dfs = (get-childitem C:\Windows\Microsoft.NET\Framework\v2.0.50727\dfsvc.exe).Versioninfo.ProductVersionRaw
Log "TCPIP.sys Version on $computer is:" $tcp
Log "DFSVC.exe Version on $computer is:" $dfs
If (get-wmiobject win32_share | where-object {$_.Name -eq "REMINST"}) {Log "The REMINST share exists on $computer"}
Else {Log "The REMINST share DOES NOT exist on $computer - Please create as per standards"}
"KB2450944", "KB3150513", "KB3176935" | ForEach {
$hotfix = Get-HotFix -Id $_ -ErrorAction SilentlyContinue
If ($hotfix) {Log -Color Green Hotfix $_ is installed}
Else {Log -Color Red Hotfix $_ " is NOT installed - Please ensure you install this hotfix"}
}
}
Log File (at D:\Apps\Logs\<computername>.log
):
2017-05-31 Write-Log (version: 01.00.02, PowerShell version: 5.1.14393.1198)
19:19:29.00 C:\Users\User\PowerShell\Write-Log\Check.ps1
19:19:29.47 TCPIP.sys Version on is: {Major: 10, Minor: 0, Build: 14393, Revision: 1066, MajorRevision: 0, MinorRevision: 1066}
19:19:29.50 DFSVC.exe Version on is: {Major: 2, Minor: 0, Build: 50727, Revision: 8745, MajorRevision: 0, MinorRevision: 8745}
19:19:29.60 The REMINST share DOES NOT exist on - Please create as per standards
Error at 25,13: Cannot find the requested hotfix on the 'localhost' computer. Verify the input and run the command again.
19:19:33.41 Hotfix KB2450944 is NOT installed - Please ensure you install this hotfix
19:19:37.03 Hotfix KB3150513 is installed
19:19:40.77 Hotfix KB3176935 is installed
19:19:40.77 End
If you need support for all standardized named character references, unicode and ambiguous ampersands, the he library is the only 100% reliable solution I'm aware of!
he.encode('foo © bar ? baz qux');
// Output : 'foo © bar ≠ baz 𝌆 qux'
he.decode('foo © bar ≠ baz 𝌆 qux');
// Output : 'foo © bar ? baz qux'
We also encountered similar problems. However, setting the charset as noted in the previous comment did not help. Our application was making an AJAX request every 60 seconds and our webserver, nginx, was sending Keep-Alive timeout at 60 seconds.
We fixed the problem by setting the keep-alive timeout value to 75 seconds.
This is what we believe was happening:
A Wireshark TCP dump would provide more clarity, our problem is fixed and we do not wish to spend more time on it.
You can't call methods outside a method. Code like this cannot float around in the class.
You need something like:
public class MyClass {
UserInput input = new UserInput();
public void foo() {
input.name();
}
}
or inside a constructor:
public class MyClass {
UserInput input = new UserInput();
public MyClass() {
input.name();
}
}
Please use regex to remove anything before |
example
dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds
Use find and replace in notepad++
find: .+(\|)
replace: \1
output
| fdfsfsf
|gfghhghg
|dfdsfsds
I can do it using below two methods, using function
def lensort(x):
list1 = []
for i in x:
list1.append([len(i),i])
return sorted(list1)
lista = ['a', 'bb', 'ccc', 'dddd']
a=lensort(lista)
print([l[1] for l in a])
In one Liner using Lambda, as below, a already answered above.
lista = ['a', 'bb', 'ccc', 'dddd']
lista.sort(key = lambda x:len(x))
print(lista)
i'd recommend using tables for this problem. i'm having a similar issue and as long as the table is just used to display some data and not for the main page layout it is fine.
For images, open an image in google viewer. i.e.
https://docs.google.com/file/d/0Bz7qe_olclTwWDNJRDRmb1pJamM/edit
then view source> find word "texmex-thumb" and aside it there will be link.
Sometimes it doesnt fire when the script has some syntax error, make sure the script and javascript syntax is correct.
Migrator cannot identify all the functions that need @objc
Inferred Objective-C thunks marked as deprecated to help you find them
• Build warnings about deprecated methods
• Console messages when running deprecated thunks
Good way to do this is to use mkdirp module.
$ npm install mkdirp
Use it to run function that requires the directory. Callback is called after path is created or if path did already exists. Error err
is set if mkdirp failed to create directory path.
var mkdirp = require('mkdirp');
mkdirp('/tmp/some/path/foo', function(err) {
// path exists unless there was an error
});
Ok, instead of identifying players by name track with sockets through which they have connected. You can have a implementation like
var allClients = [];
io.sockets.on('connection', function(socket) {
allClients.push(socket);
socket.on('disconnect', function() {
console.log('Got disconnect!');
var i = allClients.indexOf(socket);
allClients.splice(i, 1);
});
});
Hope this will help you to think in another way
**Radio button aria-checked: true or false one at a time**_x000D_
_x000D_
$('input:radio[name=anynameofinput]').change(function() {_x000D_
if (this.value === 'value1') {_x000D_
$("#id1").attr("aria-checked","true");_x000D_
$("#id2").attr("aria-checked","false");_x000D_
}_x000D_
else if (this.value === 'value2') {;_x000D_
$("#id2").attr("aria-checked","true");_x000D_
$("#id1").attr("aria-checked","false");_x000D_
}_x000D_
});
_x000D_
My remote sql server was expecting connection at a different port and not on the default 1443.
The solution was to add a "," after your sql server IP and then add your port like so 129.0.0.1,2995 (Check the " , " after server IP)
Please find the image for reference below.
As per MSDN, In a case of spreadsheets inside of Excel it might not work because Excel files are not real databases. So you will be not able to get the sheets name in order of their visualization in workbook.
Code to get sheets name as per their visual appearance using interop:
Add reference to Microsoft Excel 12.0 Object Library.
Following code will give the sheets name in the actual order stored in workbook, not the sorted name.
Sample Code:
using Microsoft.Office.Interop.Excel;
string filename = "C:\\romil.xlsx";
object missing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb =excel.Workbooks.Open(filename, missing, missing, missing, missing,missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
ArrayList sheetname = new ArrayList();
foreach (Microsoft.Office.Interop.Excel.Worksheet sheet in wb.Sheets)
{
sheetname.Add(sheet.Name);
}
Here is the code, and you can decide which
(synchronized)StringBuffer or
faster StringBuilder to use.
Benchmark shows StringBuilder is Faster.
public class Main {
int times = 777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
sb.append("");
getJSONFromStringBuffer(String stringJSON);
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
getJSONFromStringBUilder(String stringJSON);
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
}
Not 100% what you were looking for, but kind of an inside-out way of doing it:
SQL> CREATE TABLE mytable (id NUMBER, status VARCHAR2(50));
Table created.
SQL> INSERT INTO mytable VALUES (1,'Finished except pouring water on witch');
1 row created.
SQL> INSERT INTO mytable VALUES (2,'Finished except clicking ruby-slipper heels');
1 row created.
SQL> INSERT INTO mytable VALUES (3,'You shall (not?) pass');
1 row created.
SQL> INSERT INTO mytable VALUES (4,'Done');
1 row created.
SQL> INSERT INTO mytable VALUES (5,'Done with it.');
1 row created.
SQL> INSERT INTO mytable VALUES (6,'In Progress');
1 row created.
SQL> INSERT INTO mytable VALUES (7,'In progress, OK?');
1 row created.
SQL> INSERT INTO mytable VALUES (8,'In Progress Check Back In Three Days'' Time');
1 row created.
SQL> SELECT *
2 FROM mytable m
3 WHERE +1 NOT IN (INSTR(m.status,'Done')
4 , INSTR(m.status,'Finished except')
5 , INSTR(m.status,'In Progress'));
ID STATUS
---------- --------------------------------------------------
3 You shall (not?) pass
7 In progress, OK?
SQL>
hashCode()
is a function that takes an object and outputs a numeric value. The hashcode for an object is always the same if the object doesn't change.
Functions like HashMap
, HashTable
, HashSet
, etc. that need to store objects will use a hashCode
modulo the size of their internal array to choose in what "memory position" (i.e. array position) to store the object.
There are some cases where collisions may occur (two objects end up with the same hashcode), and that, of course, needs to be solved carefully.
To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?
Like biegleux already said:
If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml
file in your values
folder and define the text size there with the following 3 lines:
<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>
Here is an example for a TextView with large text from the dimens.xml
file:
<TextView
android:id="@+id/hello_world"
android:text="hello world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="@dimen/text_size_large"/>
I caused my sqlite db to become locked by crashing an app during a write. Here is how i fixed it:
echo ".dump" | sqlite old.db | sqlite new.db
Taken from: http://random.kakaopor.hu/how-to-repair-an-sqlite-database
Integer.parseInt
will take a string and return a int.
The evaluation of condition
resulted in an NA
. The if
conditional must have either a TRUE
or FALSE
result.
if (NA) {}
## Error in if (NA) { : missing value where TRUE/FALSE needed
This can happen accidentally as the results of calculations:
if(TRUE && sqrt(-1)) {}
## Error in if (TRUE && sqrt(-1)) { : missing value where TRUE/FALSE needed
To test whether an object is missing use is.na(x)
rather than x == NA
.
See also the related errors:
Error in if/while (condition) { : argument is of length zero
Error in if/while (condition) : argument is not interpretable as logical
if (NULL) {}
## Error in if (NULL) { : argument is of length zero
if ("not logical") {}
## Error: argument is not interpretable as logical
if (c(TRUE, FALSE)) {}
## Warning message:
## the condition has length > 1 and only the first element will be used
My issue was not sending the response back, so it was hanging. If you are using express make sure that res.send(data), res.json(data) or whatever the api method you wanna use is executed for the route you are testing.
window.format = function(b, a) {
if (!b || isNaN(+a)) return a;
var a = b.charAt(0) == "-" ? -a : +a,
j = a < 0 ? a = -a : 0,
e = b.match(/[^\d\-\+#]/g),
h = e && e[e.length - 1] || ".",
e = e && e[1] && e[0] || ",",
b = b.split(h),
a = a.toFixed(b[1] && b[1].length),
a = +a + "",
d = b[1] && b[1].lastIndexOf("0"),
c = a.split(".");
if (!c[1] || c[1] && c[1].length <= d) a = (+a).toFixed(d + 1);
d = b[0].split(e);
b[0] = d.join("");
var f = b[0] && b[0].indexOf("0");
if (f > -1)
for (; c[0].length < b[0].length - f;) c[0] = "0" + c[0];
else +c[0] == 0 && (c[0] = "");
a = a.split(".");
a[0] = c[0];
if (c = d[1] && d[d.length -
1].length) {
for (var d = a[0], f = "", k = d.length % c, g = 0, i = d.length; g < i; g++) f += d.charAt(g), !((g - k + 1) % c) && g < i - c && (f += e);
a[0] = f
}
a[1] = b[1] && a[1] ? h + a[1] : "";
return (j ? "-" : "") + a[0] + a[1]
};
var str="1234567890";
var formatstr=format( "##,###.", str);
alert(formatstr);
This will split the string in reverse order with comma separated after 3 char's. If you want you can change the position.
Yes, I also found it here: http://developer.android.com/tools/testing/activity_testing.html It's seems a key-input protection mechanism which includes the screen-lock, but not only includes it. According to this webpage, it also defines some key-input restriction for auto-test framework in Android.
You may already have this working, but the I created a test project with the classes below allowing you to retrieve the data into an entity, projection or dto.
Projection - this will return the code column twice, once named code and also named text (for example only). As you say above, you don't need the @Projection annotation
import org.springframework.beans.factory.annotation.Value;
public interface DeadlineTypeProjection {
String getId();
// can get code and or change name of getter below
String getCode();
// Points to the code attribute of entity class
@Value(value = "#{target.code}")
String getText();
}
DTO class - not sure why this was inheriting from your base class and then redefining the attributes. JsonProperty just an example of how you'd change the name of the field passed back to a REST end point
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class DeadlineType {
String id;
// Use this annotation if you need to change the name of the property that is passed back from controller
// Needs to be called code to be used in Repository
@JsonProperty(value = "text")
String code;
}
Entity class
import lombok.Data;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Data
@Entity
@Table(name = "deadline_type")
public class ABDeadlineType {
@Id
private String id;
private String code;
}
Repository - your repository extends JpaRepository<ABDeadlineType, Long> but the Id is a String, so updated below to JpaRepository<ABDeadlineType, String>
import com.example.demo.entity.ABDeadlineType;
import com.example.demo.projection.DeadlineTypeProjection;
import com.example.demo.transfer.DeadlineType;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, String> {
List<ABDeadlineType> findAll();
List<DeadlineType> findAllDtoBy();
List<DeadlineTypeProjection> findAllProjectionBy();
}
Example Controller - accesses the repository directly to simplify code
@RequestMapping(value = "deadlinetype")
@RestController
public class DeadlineTypeController {
private final ABDeadlineTypeRepository abDeadlineTypeRepository;
@Autowired
public DeadlineTypeController(ABDeadlineTypeRepository abDeadlineTypeRepository) {
this.abDeadlineTypeRepository = abDeadlineTypeRepository;
}
@GetMapping(value = "/list")
public ResponseEntity<List<ABDeadlineType>> list() {
List<ABDeadlineType> types = abDeadlineTypeRepository.findAll();
return ResponseEntity.ok(types);
}
@GetMapping(value = "/listdto")
public ResponseEntity<List<DeadlineType>> listDto() {
List<DeadlineType> types = abDeadlineTypeRepository.findAllDtoBy();
return ResponseEntity.ok(types);
}
@GetMapping(value = "/listprojection")
public ResponseEntity<List<DeadlineTypeProjection>> listProjection() {
List<DeadlineTypeProjection> types = abDeadlineTypeRepository.findAllProjectionBy();
return ResponseEntity.ok(types);
}
}
Hope that helps
Les
Below is a fully functional example of what I believe you're trying to do (with a functional snippet).
Based on your question, you seem to be modifying 1 property in state
for all of your elements. That's why when you click on one, all of them are being changed.
In particular, notice that the state tracks an index of which element is active. When MyClickable
is clicked, it tells the Container
its index, Container
updates the state
, and subsequently the isActive
property of the appropriate MyClickable
s.
class Container extends React.Component {_x000D_
state = {_x000D_
activeIndex: null_x000D_
}_x000D_
_x000D_
handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
render() {_x000D_
return <div>_x000D_
<MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
<MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
<MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
</div>_x000D_
}_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
handleClick = () => this.props.onClick(this.props.index)_x000D_
_x000D_
render() {_x000D_
return <button_x000D_
type='button'_x000D_
className={_x000D_
this.props.isActive ? 'active' : 'album'_x000D_
}_x000D_
onClick={ this.handleClick }_x000D_
>_x000D_
<span>{ this.props.name }</span>_x000D_
</button>_x000D_
}_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
display: block;_x000D_
margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable
elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.
// New render method for `Container`
render() {
const clickables = [
{ name: "a" },
{ name: "b" },
{ name: "c" },
]
return <div>
{ clickables.map(function(clickable, i) {
return <MyClickable key={ clickable.name }
name={ clickable.name }
index={ i }
isActive={ this.state.activeIndex === i }
onClick={ this.handleClick }
/>
} )
}
</div>
}
//simple json object in asp.net mvc
var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({ url: 'test/[ControllerName]',
type: "POST",
data: model,
success: function (res) {
if (res != null) {
alert("done.");
}
},
error: function (res) {
}
});
//model in c#
public class MyModel
{
public string Id {get; set;}
public string Name {get; set;}
}
//controller in asp.net mvc
public ActionResult test(MyModel model)
{
//now data in your model
}
You can think of a static member function as one that exists without the need for an object to exist. For example, the Integer.parseInt() method from the Integer class is static. When you need to use it, you don't need to create a new Integer object, you simply call it. The same thing for main(). If you need to call a non-static member from it, simply put your main code in a class and then from main create a new object of your newly created class.
I also faced that problem and there are two ways to solve this in laravel.
first one is you can set the default value as null. I will show you an example:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('gender');
$table->string('slug');
$table->string('pic')->nullable();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
as the above example, you can set nullable()
for that feature. then when you are inserting data MySQL set the default value as null.
second one is in your model set your input field in protected $fillable
field. as example:
protected $fillable = [
'name', 'email', 'password', 'slug', 'gender','pic'
];
I think the second one is fine than the first one and also you can set nullable feature as well as fillable in the same time without a problem.
It turns out setting these configuration properties is pretty straight forward, but the official documentation is more general so it might be hard to find when searching specifically for connection pool configuration information.
To set the maximum pool size for tomcat-jdbc, set this property in your .properties or .yml file:
spring.datasource.maxActive=5
You can also use the following if you prefer:
spring.datasource.max-active=5
You can set any connection pool property you want this way. Here is a complete list of properties supported by tomcat-jdbc
.
To understand how this works more generally you need to dig into the Spring-Boot code a bit.
Spring-Boot constructs the DataSource like this (see here, line 102):
@ConfigurationProperties(prefix = DataSourceAutoConfiguration.CONFIGURATION_PREFIX)
@Bean
public DataSource dataSource() {
DataSourceBuilder factory = DataSourceBuilder
.create(this.properties.getClassLoader())
.driverClassName(this.properties.getDriverClassName())
.url(this.properties.getUrl())
.username(this.properties.getUsername())
.password(this.properties.getPassword());
return factory.build();
}
The DataSourceBuilder is responsible for figuring out which pooling library to use, by checking for each of a series of know classes on the classpath. It then constructs the DataSource and returns it to the dataSource()
function.
At this point, magic kicks in using @ConfigurationProperties
. This annotation tells Spring to look for properties with prefix CONFIGURATION_PREFIX
(which is spring.datasource
). For each property that starts with that prefix, Spring will try to call the setter on the DataSource with that property.
The Tomcat DataSource is an extension of DataSourceProxy, which has the method setMaxActive()
.
And that's how your spring.datasource.maxActive=5
gets applied correctly!
I haven't tried, but if you are using one of the other Spring-Boot supported connection pools (currently HikariCP or Commons DBCP) you should be able to set the properties the same way, but you'll need to look at the project documentation to know what is available.
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
Use the id
of the element to do the same.
document.getElementById(id).style.visibility = 'hidden';
Currently (Laravel 5.4) the way to achieve this is:
$model = new Model();
$model->created_at = Carbon::now();
$model->save(['timestamps' => false]);
Are you going to want to do a setInterval()
?
setInterval(function(){get_fb();}, 10000);
Or:
setInterval(get_fb, 10000);
Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success()
callback:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Or use .ajax().complete()
if you want it to run regardless of result:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).complete(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.
I would recommend using lastIndexOf() as opposed to indexOf()
var myString = "this.is.my.file.txt"
alert(myString.substring(myString.lastIndexOf(".")+1))
There was almost the same question on GitHub a year ago.
The idea was to rename the master branch:
git branch -m master development
git branch -m published master
git push -f origin master
Making master have what you want people to use, and do all other work in branches.
(a "git-symbolic-ref HEAD refs/head/published
" would not be propagated to the remote repo)
This is similar to "How do I delete origin/master in Git".
As said in this thread: (emphasis mine)
"
git clone
" creates only a single local branch.
To do that, it looks at theHEAD ref
of the remote repo, and creates a local branch with the same name as the remote branch referenced by it.So to wrap that up, you have repo
A
and clone it:
HEAD
referencesrefs/heads/master
and that exists
-> you get a local branch calledmaster
, starting fromorigin/master
HEAD references
refs/heads/anotherBranch
and that exists
-> you get a local branch calledanotherBranch
, starting fromorigin/anotherBranch
HEAD references
refs/heads/master
and that doesn't exist
-> "git clone
" complainsNot sure if there's any way to directly modify the
HEAD
ref in a repo.
(which is the all point of your question, I know ;) )
Maybe the only way would be a "publication for the poor", where you:
$ git-symbolic-ref HEAD refs/head/published
$ git-update-server-info
$ rsync -az .git/* server:/local_path_to/git/myRepo.git/
But that would involve write access to the server, which is not always possible.
As I explain in "Git: Correct way to change Active Branch in a bare repository?", git remote set-head
wouldn't change anything on the remote repo.
It would only change the remote tracking branch stored locally in your local repo, in remotes/<name>/HEAD
.
With Git 2.29 (Q4 2020), "git remote set-head
(man)" that failed still said something that hints the operation went through, which was misleading.
See commit 5a07c6c (17 Sep 2020) by Christian Schlack (cschlack
).
(Merged by Junio C Hamano -- gitster
-- in commit 39149df, 22 Sep 2020)
remote
: don't show success message whenset-head
failsSigned-off-by: Christian Schlack
Suppress the message 'origin/HEAD set to master' in case of an error.
$ git remote set-head origin -a error: Not a valid ref: refs/remotes/origin/master origin/HEAD set to master
After many conclusions I ended up with this combination:
@media only screen and (max-width: 730px) {
h2 {
font-size: 4.3vw;
}
}
Using ApplicationContextAware
is tying you to Spring (which may or may not be an issue). I would recommend passing in a LoginActionFactory
, which you can ask for a new instance of a LoginAction
each time you need one.
Use this:
$parameter = $_SERVER['QUERY_STRING'];
echo $parameter;
Or just use:
$parameter = $_GET['link'];
echo $parameter ;
It is bad practice to catch Exception -- it's just too broad, and you may miss something like a NullPointerException in your own code.
For most file operations, IOException is the root exception. Better to catch that, instead.
npm rebuild
will work for sure
You can use the .indexOf()
and .substring()
, like this:
var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);
You can give it a try here, if it may not have a #
in it, do an if(url.indexOf("#") != -1)
check like this:
var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";
If this is the current page URL, you can just use window.location.hash
to get it, and replace the #
if you wish.
When you write x = 0
, x
is an int...so you can't do x[age1]
because x
is int
In my case that was just a weird bug on the ios 12.1 emulator. Disappeared after launching on real device.
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
Sometimes help to add ?raw=true
at the end of a file path. For example:
wb = xlrd.open_workbook("Z:\\Data\\Locates\\3.8 locates.xls?raw=true")
On most POSIX systems (through it's not in the POSIX standard) there is the endian.h, which can be used to determine what encoding your system uses. From there it's something like this:
unsigned int change_endian(unsigned int x)
{
unsigned char *ptr = (unsigned char *)&x;
return (ptr[0] << 24) | (ptr[1] << 16) | (ptr[2] << 8) | ptr[3];
}
This swaps the order (from big endian to little endian):
If you have the number 0xDEADBEEF (on a little endian system stored as 0xEFBEADDE), ptr[0] will be 0xEF, ptr[1] is 0xBE, etc.
But if you want to use it for networking, then htons, htonl and htonll (and their inverses ntohs, ntohl and ntohll) will be helpful for converting from host order to network order.
$(this).parent().parent().attr('id');
Is how you would get the id of the parent's parent.
EDIT:
$(this).closest('ul').attr('id');
Is a more foolproof solution for your case.
svn info
, I believe, is what you want.
If you just wanted the revision, maybe you could do something like:
svn info | grep "Revision:"
It'll need to be something tailored to the needs, which are dependent on the structure you're presented with. For the example you've provided, this works:
$(document).ready(function(){
var $tmp = $('#listItem').children().remove();
$('#listItem').text('').append($tmp);
});
Demo: http://jquery.nodnod.net/cases/2385/run
But it's fairly dependent on the markup being similar to what you posted.
We faced similar issue recently, In case if a process refers to a deleted file, the Inode shall not be released, so you need to check lsof /, and kill/ restart the process will release the inodes.
Correct me if am wrong here.
A slight modification of the suggestion of @Krizz, so that it works properly if the constants header file is to be included in the PCH, which is rather normal. Since the original is imported into the PCH, it won't reload it into the .m
file and thus you get no symbols and the linker is unhappy.
However, the following modification allows it to work. It's a bit convoluted, but it works.
You'll need 3 files, .h
file which has the constant definitions, the .h
file and the .m
file, I'll use ConstantList.h
, Constants.h
and Constants.m
, respectively. the contents of Constants.h
are simply:
// Constants.h
#define STR_CONST(name, value) extern NSString* const name
#include "ConstantList.h"
and the Constants.m
file looks like:
// Constants.m
#ifdef STR_CONST
#undef STR_CONST
#endif
#define STR_CONST(name, value) NSString* const name = @ value
#include "ConstantList.h"
Finally, the ConstantList.h
file has the actual declarations in it and that is all:
// ConstantList.h
STR_CONST(kMyConstant, "Value");
…
A couple of things to note:
I had to redefine the macro in the .m
file after #undef
ing it for the macro to be used.
I also had to use #include
instead of #import
for this to work properly and avoid the compiler seeing the previously precompiled values.
This will require a recompile of your PCH (and probably the entire project) whenever any values are changed, which is not the case if they are separated (and duplicated) as normal.
Hope that is helpful for someone.
The best way is to use display:
inline-block;
and
overflow: hidden;
With client authentication:
openssl s_client -cert ./client-cert.pem -key ./client-key.key -CApath /etc/ssl/certs/ -connect foo.example.com:443
You can also try this way
<option id="opt7" class='select_continent' data-value='7'>Antarctica</option>
jquery
$('.select_continent').click(function () {
alert($(this).data('value'));
});
Good luck !!!!
Below is the code to do it in vtd-xml. It basically queries the XML with the XPath of "/xml/item/@name."
import com.ximpleware.*;
public class getAttrs{
public static void main(String[] s) throws VTDException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml",false)) // turn off namespace
return;
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
ap.selectXPath("/xml/item/@name");
int i=0;
while( (i=ap.evalXPath())!=-1){
System.out.println(" item name is ===>"+vn.toString(i+1));
}
}
}
The correct answer is
Options -Indexes
You must have been thinking of
AllowOverride All
https://httpd.apache.org/docs/2.2/howto/htaccess.html
.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.
That's because your dat1
and dat2
variables are just strings.
You should parse them to get a Date
object, for that format I always use the following function:
// parse a date in yyyy-mm-dd format
function parseDate(input) {
var parts = input.match(/(\d+)/g);
// new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}
I use this function because the Date.parse(string)
(or new Date(string)
) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
My understanding from my testing (and the PostgreSQL dox) is that the quotes need to be done differently from the other answers, and should also include "day" like this:
SELECT Table.date
FROM Table
WHERE date > current_date - interval '10 day';
Demonstrated here (you should be able to run this on any Postgres db):
SELECT DISTINCT current_date,
current_date - interval '10' day,
current_date - interval '10 days'
FROM pg_language;
Result:
2013-03-01 2013-03-01 00:00:00 2013-02-19 00:00:00
working like a charm here for bootstrap 4>4.1.1
var myGroup = $('your-list');
myGroup.on('show.bs.collapse','.collapse', function() {
myGroup.find('.collapse.show').collapse('hide');
});
From the function's definition (http://www.w3schools.com/jsref/jsref_replace.asp):
The replace() method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced.
This method does not change the original string.
Hence, the line: tt.replace(/,/g, '.')
does not change the value of tt
; it just returns the new value.
You need to replace this line with: tt = tt.replace(/,/g, '.')
Any time you need to separate allocation from initialization, you'll need placement new and explicit calling of the destructor manually. Today, it's rarely necessary, since we have the standard containers, but if you have to implement some new sort of container, you'll need it.
You create a file .xml in drawable with name drop_shadow.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!--<item android:state_pressed="true">
<layer-list>
<item android:left="4dp" android:top="4dp">
<shape>
<solid android:color="#35000000" />
<corners android:radius="2dp"/>
</shape>
</item>
...
</layer-list>
</item>-->
<item>
<layer-list>
<!-- SHADOW LAYER -->
<!--<item android:top="4dp" android:left="4dp">
<shape>
<solid android:color="#35000000" />
<corners android:radius="2dp" />
</shape>
</item>-->
<!-- SHADOW LAYER -->
<item>
<shape>
<solid android:color="#35000000" />
<corners android:radius="2dp" />
</shape>
</item>
<!-- CONTENT LAYER -->
<item android:bottom="3dp" android:left="1dp" android:right="3dp" android:top="1dp">
<shape>
<solid android:color="#ffffff" />
<corners android:radius="1dp" />
</shape>
</item>
</layer-list>
</item>
</selector>
Then:
<LinearLayout
...
android:background="@drawable/drop_shadow"/>
This could happen when you have several projects that include each other in JAR form. What I did was remove all libraries and project dependencies on buildpath, for all projects. Then, one at a time, I added the project dependencies on the Project Tab, but only the ones needed. This is because you can add a project which in turn has itself referenced or another project which is referencing some other project with this self-referencing issue.
This resolved my issue.
I think that moving last operator to the beginning of the next line is a good practice. That way you know right away the purpose of the second line, even it doesn't start with an operator. I also recommend 2 indentation spaces (2 tabs) for a previously broken tab, to differ it from the normal indentation. That is immediately visible as continuing previous line. Therefore I suggest this:
private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper
= new HashMap<Class<? extends Persistent>, PersistentHelper>();
This will work:
if 'A' in df:
But for clarity, I'd probably write it as:
if 'A' in df.columns:
I had this issue in an ASP web site project. Adding a "Content-Length" header caused downloads to start working again in Chrome.
Your query is probably fine. "The semaphore timeout period has expired" is a Network error, not a SQL Server timeout.
There is apparently some sort of network problem between you and the SQL Server.
edit: However, apparently the query runs for 15-20 min before giving the network error. That is a very long time, so perhaps the network error could be related to the long execution time. Optimization of the underlying View might help.
If [MyTable] in your example is a View, can you post the View Definition so that we can have a go at optimizing it?
You don't need a CTE for this
UPDATE PEDI_InvoiceDetail
SET
DocTotal = v.DocTotal
FROM
PEDI_InvoiceDetail
inner join
(
SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
FROM PEDI_InvoiceDetail
GROUP BY InvoiceNumber
) v
ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber
You can type this command in terminal: sudo apt-get install php-intl
I know I'm 4 years too late, but I stumbled upon yet another alternative answer to this problem. The issue for speed isn't just pre-filtering, but also preventing sorting. It's possible to force the join-order to execute in a manner that the Cartesian product actually counts up as a result of the join. Using slartidan's answer as a jump-off point:
WITH x AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n
FROM x ones, x tens, x hundreds, x thousands
ORDER BY 1
If we know the range we want, we can specify it via @Upper and @Lower. By combining the join hint REMOTE along with TOP, we can calculate only the subset of values we want with nothing wasted.
WITH x AS (SELECT n FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))
SELECT TOP (1+@Upper-@Lower) @Lower + ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n
FROM x thousands
INNER REMOTE JOIN x hundreds on 1=1
INNER REMOTE JOIN x tens on 1=1
INNER REMOTE JOIN x ones on 1=1
The join hint REMOTE forces the optimizer to compare on the right side of the join first. By specifying each join as REMOTE from most to least significant value, the join itself will count upwards by one correctly. No need to filter with a WHERE, or sort with an ORDER BY.
If you want to increase the range, you can continue to add additional joins with progressively higher orders of magnitude, so long as they're ordered from most to least significant in the FROM clause.
Note that this is a query specific to SQL Server 2008 or higher.
Sending an HTTP POST request using file_get_contents
is not that hard, actually : as you guessed, you have to use the $context
parameter.
There's an example given in the PHP manual, at this page : HTTP context options (quoting) :
$postdata = http_build_query(
array(
'var1' => 'some content',
'var2' => 'doh'
)
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/submit.php', false, $context);
Basically, you have to create a stream, with the right options (there is a full list on that page), and use it as the third parameter to file_get_contents
-- nothing more ;-)
As a sidenote : generally speaking, to send HTTP POST requests, we tend to use curl, which provides a lot of options an all -- but streams are one of the nice things of PHP that nobody knows about... too bad...
Others have directly answered your question, but when trying to understand the stack and the heap, I think it is helpful to consider the memory layout of a traditional UNIX process (without threads and mmap()
-based allocators). The Memory Management Glossary web page has a diagram of this memory layout.
The stack and heap are traditionally located at opposite ends of the process's virtual address space. The stack grows automatically when accessed, up to a size set by the kernel (which can be adjusted with setrlimit(RLIMIT_STACK, ...)
). The heap grows when the memory allocator invokes the brk()
or sbrk()
system call, mapping more pages of physical memory into the process's virtual address space.
In systems without virtual memory, such as some embedded systems, the same basic layout often applies, except the stack and heap are fixed in size. However, in other embedded systems (such as those based on Microchip PIC microcontrollers), the program stack is a separate block of memory that is not addressable by data movement instructions, and can only be modified or read indirectly through program flow instructions (call, return, etc.). Other architectures, such as Intel Itanium processors, have multiple stacks. In this sense, the stack is an element of the CPU architecture.
use your ip address or a service like noip.com if you need something more practical. Then eventually configure your router properly so incoming connection will be forwarded to the machine with the server running.
The webserver is returning an http 500 error code. These errors generally happen when an exception in thrown on the webserver and there's no logic to catch it so it spits out an http 500 error. You can usually resolve the problem by placing try-catch blocks in your code.
I had the same its because of version incompatibility check for version or remove version if using spring boot