Use the row number to differentiate between duplicate records. Keep the first row number for an EmpID/EmpSSN and delete the rest:
DELETE FROM Employee a
WHERE ROW_NUMBER() <> ( SELECT MIN( ROW_NUMBER() )
FROM Employee b
WHERE a.EmpID = b.EmpID
AND a.EmpSSN = b.EmpSSN )
you must do 4 following step :
create event
var event = new Event("change",{
detail: {
oldValue:yourValueVariable,
newValue:!yourValueVariable
},
bubbles: true,
cancelable: true
});
event.simulated = true;
let tracker = this.yourComponentDomRef._valueTracker;
if (tracker) {
tracker.setValue(!yourValueVariable);
}
bind value to component dom
this.yourComponentDomRef.value = !yourValueVariable;
bind element onchange to react onChange function
this.yourComponentDomRef.onchange = (e)=>this.props.onChange(e);
dispatch event
this.yourComponentDomRef.dispatchEvent(event);
in above code yourComponentDomRef
refer to master dom of your React component for example <div className="component-root-dom" ref={(dom)=>{this.yourComponentDomRef= dom}}>
Solved my own problem. This line:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
needs to be:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
or since Java 7:
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));
Try this:
if(myString != "-1")
The opperand is !=
and not =!
You can also use Equals
if(!myString.Equals("-1"))
Note the !
before myString
You can use the build job
step from Jenkins Pipeline (Minimum Jenkins requirement: 2.130).
Here's the full API for the build
step: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/
How to use build
:
job
: Name of a downstream job to build. May be another Pipeline job, but more commonly a freestyle or other project.
../sister-folder/downstream
/top-level-folder/nested-folder/downstream
At my company many of our branches include "/". You must replace any instances of "/" with "%2F" (as it appears in the URL of the job).
In this example we're using relative paths
stage('Trigger Branch Build') {
steps {
script {
echo "Triggering job for branch ${env.BRANCH_NAME}"
BRANCH_TO_TAG=env.BRANCH_NAME.replace("/","%2F")
build job: "../my-relative-job/${BRANCH_TO_TAG}", wait: false
}
}
}
build job: 'your-job-name',
parameters: [
string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
]
Source: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/
More info on Parallel here: https://jenkins.io/doc/book/pipeline/syntax/#parallel
stage ('Trigger Builds In Parallel') {
steps {
// Freestyle build trigger calls a list of jobs
// Pipeline build() step only calls one job
// To run all three jobs in parallel, we use "parallel" step
// https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel
parallel (
linux: {
build job: 'full-build-linux', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
},
mac: {
build job: 'full-build-mac', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
},
windows: {
build job: 'full-build-windows', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
},
failFast: false)
}
}
Or alternatively:
stage('Build A and B') {
failFast true
parallel {
stage('Build A') {
steps {
build job: "/project/A/${env.BRANCH}", wait: true
}
}
stage('Build B') {
steps {
build job: "/project/B/${env.BRANCH}", wait: true
}
}
}
}
Find a parent of current element that has vertical scrolling or body.
$.fn.scrollableParent = function() {
var $parents = this.parents();
var $scrollable = $parents.filter(function(idx) {
return this.scrollHeight > this.offsetHeight && this.offsetWidth !== this.clientWidth;
}).first();
if ($scrollable.length === 0) {
$scrollable = $('html, body');
}
return $scrollable;
};
It may be used to autoscroll to current element via:
var $scrollable = $elem.scrollableParent();
$scrollable.scrollTop($elem.position().top);
Your string is not valid. Double quots cannot be inside double quotes. You should escape them:
"{\"TeamList\" : [{\"teamid\" : \"1\",\"teamname\" : \"Barcelona\"}]}"
or use single quotes and double quotes
'{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}'
Change your last statement to this:
EXEC('SELECT * FROM ' + @tablename)
This is how I do mine in a stored procedure. The first block will declare the variable, and set the table name based on the current year and month name, in this case TEST_2012OCTOBER. I then check if it exists in the database already, and remove if it does. Then the next block will use a SELECT INTO statement to create the table and populate it with records from another table with parameters.
--DECLARE TABLE NAME VARIABLE DYNAMICALLY
DECLARE @table_name varchar(max)
SET @table_name =
(SELECT 'TEST_'
+ DATENAME(YEAR,GETDATE())
+ UPPER(DATENAME(MONTH,GETDATE())) )
--DROP THE TABLE IF IT ALREADY EXISTS
IF EXISTS(SELECT name
FROM sysobjects
WHERE name = @table_name AND xtype = 'U')
BEGIN
EXEC('drop table ' + @table_name)
END
--CREATES TABLE FROM DYNAMIC VARIABLE AND INSERTS ROWS FROM ANOTHER TABLE
EXEC('SELECT * INTO ' + @table_name + ' FROM dbo.MASTER WHERE STATUS_CD = ''A''')
db.collection("collection_name").deleteOne({_id:ObjectId("4d513345cc9374271b02ec6c")})
The best way its add:
<ImageView
android:id="@+id/ivBack"
style="?attr/actionButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:src="@drawable/ic_back_arrow_black"
android:tint="@color/white" />
just use <br>
at the end of your lines.
I had kind of the same problem and after going carefully against all charsets and finding that they were all right, I realized that the bugged property I had in my class was annotated as @Column instead of @JoinColumn (javax.presistence; hibernate) and it was breaking everything up.
git checkout [branchYouWantToReceiveBranch]
- checkout branch you want to receive branchgit merge [branchYouWantToMergeIntoBranch]
from bower help, save option has a capital S
-S, --save Save installed packages into the project's bower.json dependencies
Alexandru's suggestion of using class constants for enums works quite well.
I also like to add a dictionary for each set of constants to lookup a human-readable string representation.
This serves two purposes: a) it provides a simple way to pretty-print your enum and b) the dictionary logically groups the constants so that you can test for membership.
class Animal:
TYPE_DOG = 1
TYPE_CAT = 2
type2str = {
TYPE_DOG: "dog",
TYPE_CAT: "cat"
}
def __init__(self, type_):
assert type_ in self.type2str.keys()
self._type = type_
def __repr__(self):
return "<%s type=%s>" % (
self.__class__.__name__, self.type2str[self._type].upper())
In my case DockerFile contained the image name in mixed case instead of lower case.
Earlier line in my DockerFile
FROM CentOs
and when I changed above to FROM centos
, it worked smoothly.
Try this SQL statement:
update Table set Column =( Column - your val )
There are a number of alternative tools and approaches for doing this listed arround the web. For example:
There's no guarantee that SQL Server won't attempt to perform the CONVERT
to numeric(20,0)
before it runs the filter in the WHERE
clause.
And, even if it did, ISNUMERIC
isn't adequate, since it recognises £
and 1d4
as being numeric, neither of which can be converted to numeric(20,0)
.(*)
Split it into two separate queries, the first of which filters the results and places them in a temp table or table variable, the second of which performs the conversion. (Subqueries and CTEs are inadequate to prevent the optimizer from attempting the conversion before the filter)
For your filter, probably use account_code not like '%[^0-9]%'
instead of ISNUMERIC
.
(*) ISNUMERIC
answers the question that no-one (so far as I'm aware) has ever wanted to ask - "can this string be converted to any of the numeric datatypes - I don't care which?" - when obviously, what most people want to ask is "can this string be converted to x?" where x
is a specific target datatype.
You can easily test the difference between HTTP and HTTPS performance in your own browser using the HTTP vs HTTPS Test website by AnthumChris: “This page measures its load time over unsecure HTTP and encrypted HTTPS connections. Both pages load 360 unique, non-cached images (2.04 MB total).”
The results may surprise you.
It's important to have an up to date knowledge about the HTTPS performance because the Let’s Encrypt Certificate Authority will start issuing free, automated, and open SSL certificates in Summer 2015, thanks to Mozilla, Akamai, Cisco, Electronic Frontier Foundation and IdenTrust.
Updates on Let’s Encrypt - Arriving September 2015:
More info on Twitter: @letsencrypt
For more info on HTTPS and SSL/TLS performance see:
For more info on the importance of using HTTPS see:
To sum it up, let me quote Ilya Grigorik: "TLS has exactly one performance problem: it is not used widely enough. Everything else can be optimized."
Thanks to Chris - author of the HTTP vs HTTPS Test benchmark - for his comments below.
I have XAMPP 1.8.3-0 and PHP 5.5.0 installed.
1) edit php.ini:
from
;extension=php_intl.dll
to
extension=php_intl.dll
Note: After modification, need to save the file(php.ini) as well as need to restart the Apache Server.
2) Simply copy all icu* * * *.dll files:
from
C:\xampp\php
to
C:\xampp\apache\bin
Then intl extension works!!!
You should have used:
a:hover {
text-decoration: underline;
}
hover
is a pseudo class in CSS. No need to assign a class.
In Java its Webelement.getText() . Not sure about python.
I'm a little late to the party, but I think my approach has the advantage that it lacks the use of EventEmitters and Subjects.
So, here's my approach. We can't get away from subscribe(), and we don't want to. In that vein, our service will return an Observable<T>
with an observer that has our precious cargo. From the caller, we'll initialize a variable, Observable<T>
, and it will get the service's Observable<T>
. Next, we'll subscribe to this object. Finally, you get your "T"! from your service.
First, our people service, but yours doesnt pass parameters, that's more realistic:
people(hairColor: string): Observable<People> {
this.url = "api/" + hairColor + "/people.json";
return Observable.create(observer => {
http.get(this.url)
.map(res => res.json())
.subscribe((data) => {
this._people = data
observer.next(this._people);
observer.complete();
});
});
}
Ok, as you can see, we're returning an Observable
of type "people". The signature of the method, even says so! We tuck-in the _people
object into our observer. We'll access this type from our caller in the Component, next!
In the Component:
private _peopleObservable: Observable<people>;
constructor(private peopleService: PeopleService){}
getPeople(hairColor:string) {
this._peopleObservable = this.peopleService.people(hairColor);
this._peopleObservable.subscribe((data) => {
this.people = data;
});
}
We initialize our _peopleObservable
by returning that Observable<people>
from our PeopleService
. Then, we subscribe to this property. Finally, we set this.people
to our data(people
) response.
Architecting the service in this fashion has one, major advantage over the typical service: map(...) and component: "subscribe(...)" pattern. In the real world, we need to map the json to our properties in our class and, sometimes, we do some custom stuff there. So this mapping can occur in our service. And, typically, because our service call will be used not once, but, probably, in other places in our code, we don't have to perform that mapping in some component, again. Moreover, what if we add a new field to people?....
Like Apache, this is a quick edit to the source and recompile. From Calomel.org:
The Server: string is the header which is sent back to the client to tell them what type of http server you are running and possibly what version. This string is used by places like Alexia and Netcraft to collect statistics about how many and of what type of web server are live on the Internet. To support the author and statistics for Nginx we recommend keeping this string as is. But, for security you may not want people to know what you are running and you can change this in the source code. Edit the source file
src/http/ngx_http_header_filter_module.c
at look at lines 48 and 49. You can change the String to anything you want.
## vi src/http/ngx_http_header_filter_module.c (lines 48 and 49)
static char ngx_http_server_string[] = "Server: MyDomain.com" CRLF;
static char ngx_http_server_full_string[] = "Server: MyDomain.com" CRLF;
March 2011 edit: Props to Flavius below for pointing out a new option, replacing Nginx's standard HttpHeadersModule with the forked HttpHeadersMoreModule. Recompiling the standard module is still the quick fix, and makes sense if you want to use the standard module and won't be changing the server string often. But if you want more than that, the HttpHeadersMoreModule is a strong project and lets you do all sorts of runtime black magic with your HTTP headers.
Keys must be unique. Don't do that. Redesign as needed.
(if you are trying to insert, then delete, and the insert fails... just do the delete first. Rollback on error in either statement).
Simply by the following:
double d = 394.000;
long l = d * 1L;
public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";
public static DataSet LoaderDataSet(string StrSql)
{
SqlConnection cnn;
SqlDataAdapter dad;
DataSet dts = new DataSet();
cnn = new SqlConnection(textDataSource);
dad = new SqlDataAdapter(StrSql, cnn);
try
{
cnn.Open();
dad.Fill(dts);
cnn.Close();
return dts;
}
catch (Exception)
{
return dts;
}
finally
{
dad.Dispose();
dts = null;
cnn = null;
}
}
I had this problem and spent a few hours trying to fix it. I fixed the prefix error by changing the path but I still had an encoding import error. This was fixed by restarting my computer.
When i imported a project from another pc into my workspace, there was the default.properties but no R.java. Editing the default.properties didnt generate R.java. I changed the skd version from 1.1 to 1.5 and the R.java file was generated and the project worked.
One way to do it is the code below:
int gcd = 0;
while (gcdNum2 !=0 && gcdNum1 != 0 ) {
if(gcdNum1 % gcdNum2 == 0){
gcd = gcdNum2;
}
int aux = gcdNum2;
gcdNum2 = gcdNum1 % gcdNum2;
gcdNum1 = aux;
}
You do not need recursion to do this.
And be careful, it says that when a number is zero, then the GCD is the number that is not zero.
while (gcdNum1 == 0) {
gcdNum1 = 0;
}
You should modify this to fulfill the requirement.
I am not going to tell you how to modify your code entirely, only how to calculate the gcd.
Simple solution would be to use substring method.
Since string is ending with list element, we can use string.length and calculate end index for substring without using lastIndexOf
method
str = str.substring(0, str.length - list[i].length) + "finish"
There is a nice open source Git stack called Git Blit. It is available for different platform and in different packages. You can also easily deploy it to your existing Tomcat or any other servlet container. Take a look at Setup git server on windows in few clicks tutorial for more details, it will take you around 10 minutes to get basic setup.
This is an issue when migrating from gulp version 3 to 4, Simply you can add a parameter done to the call back function , see example,
const gulp = require("gulp")
gulp.task("message", function(done) {
console.log("Gulp is running...")
done()
});
I am just using the java.net
package.
Here you can do the following:
...
import java.net.URI;
...
String myUrl = "http://stackoverflow.com";
URI myURI = new URI(myUrl);
Check your routing method:
if your routing state is like this
.state('app.register', {
url: '/register',
views: {
'menuContent': {
templateUrl: 'templates/register.html',
}
}
})
then you should use
$location.path("/app/register");
function selectText(containerid) {_x000D_
if (document.selection) { // IE_x000D_
var range = document.body.createTextRange();_x000D_
range.moveToElementText(document.getElementById(containerid));_x000D_
range.select();_x000D_
} else if (window.getSelection) {_x000D_
var range = document.createRange();_x000D_
range.selectNode(document.getElementById(containerid));_x000D_
window.getSelection().removeAllRanges();_x000D_
window.getSelection().addRange(range);_x000D_
}_x000D_
}
_x000D_
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>
_x000D_
Now you have to pass the ID as an argument, which in this case is "selectable", but it's more global, allowing you to use it anywhere multiple times without using, as chiborg mentioned, jQuery.
Here is a function provides you more options to set min of special chars, min of upper chars, min of lower chars and min of number
function randomPassword(len = 8, minUpper = 0, minLower = 0, minNumber = -1, minSpecial = -1) {
let chars = String.fromCharCode(...Array(127).keys()).slice(33),//chars
A2Z = String.fromCharCode(...Array(91).keys()).slice(65),//A-Z
a2z = String.fromCharCode(...Array(123).keys()).slice(97),//a-z
zero2nine = String.fromCharCode(...Array(58).keys()).slice(48),//0-9
specials = chars.replace(/\w/g, '')
if (minSpecial < 0) chars = zero2nine + A2Z + a2z
if (minNumber < 0) chars = chars.replace(zero2nine, '')
let minRequired = minSpecial + minUpper + minLower + minNumber
let rs = [].concat(
Array.from({length: minSpecial ? minSpecial : 0}, () => specials[Math.floor(Math.random() * specials.length)]),
Array.from({length: minUpper ? minUpper : 0}, () => A2Z[Math.floor(Math.random() * A2Z.length)]),
Array.from({length: minLower ? minLower : 0}, () => a2z[Math.floor(Math.random() * a2z.length)]),
Array.from({length: minNumber ? minNumber : 0}, () => zero2nine[Math.floor(Math.random() * zero2nine.length)]),
Array.from({length: Math.max(len, minRequired) - (minRequired ? minRequired : 0)}, () => chars[Math.floor(Math.random() * chars.length)]),
)
return rs.sort(() => Math.random() > Math.random()).join('')
}
randomPassword(12, 1, 1, -1, -1)// -> DDYxdVcvIyLgeB
randomPassword(12, 1, 1, 1, -1)// -> KYXTbKf9vpMu0
randomPassword(12, 1, 1, 1, 1)// -> hj|9)V5YKb=7
$(".phoneString").text(function(i, text) {
text = text.replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
return text;
});
Output :-(123) 657-8963
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = findViewById(R.id.button);
spinner = findViewById(R.id.sp_item);
setInfo();
spinnerAdapter = new SpinnerAdapter(this, arrayList);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//first, we have to retrieve the item position as a string
// then, we can change string value into integer
String item_position = String.valueOf(position);
int positonInt = Integer.valueOf(item_position);
Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
note: the position of items is counted from 0.
You can use this jquery select change event for get selected option value
$(document).ready(function () { _x000D_
$('body').on('change','#select', function() {_x000D_
$('#show_selected').val(this.value);_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html> _x000D_
<html> _x000D_
<title>Learn Jquery value Method</title>_x000D_
<head> _x000D_
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> _x000D_
</head> _x000D_
<body> _x000D_
<select id="select">_x000D_
<option value="">Select One</option>_x000D_
<option value="PHP">PHP</option>_x000D_
<option value="jAVA">JAVA</option>_x000D_
<option value="Jquery">jQuery</option>_x000D_
<option value="Python">Python</option>_x000D_
<option value="Mysql">Mysql</option>_x000D_
</select>_x000D_
<br><br> _x000D_
<input type="text" id="show_selected">_x000D_
</body> _x000D_
</html>
_x000D_
I use XCOPY
with the following parameters for copying .NET assemblies:
/D /Y /R /H
/D:m-d-y - Copies files changed on or after the specified date. If no date is given, copies only those files whose source time is newer than the destination time.
/Y - Suppresses prompting to confirm you want to overwrite an existing destination file.
/R - Overwrites read-only files.
/H - Copies hidden and system files also.
NOTE: This here is a workaround if you want to achieve rounded corners at the bottom only and regular corners at the top. This will not work if you want to have different radius for all four corners of the cardview. You will have to use material cardview for it or use some third party library.
Here's what seemed to work for me:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="#F9F9F9">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@drawable/profile_bg"/>
</androidx.cardview.widget.CardView>
<androidx.cardview.widget.CardView
android:id="@+id/cvProfileHeader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="32dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="280dp"
android:orientation="vertical"
android:background="@drawable/profile_bg"
android:id="@+id/llProfileHeader"
android:gravity="center_horizontal">
<!--Enter your code here-->
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
There's two cardview's in all. The second cardview is the one that will have rounded corners (on all sides as usual) and will hold all other subviews under it. The first cardview above it is also at the same level (of elevation), and has the same background but is only about half the height of the second cardview and has no rounded corners (just the usual sharp corners). This way I was able to achieve partially rounded corners on the bottom and normal corners on the top. But for all four sides, you may have to use the material cardview.
You could do the reverse of this to get rounded corners at the top and regular ones at the bottom, i.e. let the first cardview have rounded corners and the second cardview have regular corners.
You can also change the position of the body/html to fixed:
body,
html {
position: fixed;
}
The solution in the accepted answer has a significant drawback - the destructor for the singleton is called after the control leaves the main()
function. There may be problems really, when some dependent objects are allocated inside main
.
I met this problem, when trying to introduce a Singleton in the Qt application. I decided, that all my setup dialogs must be Singletons, and adopted the pattern above. Unfortunately, Qt's main class QApplication
was allocated on stack in the main
function, and Qt forbids creating/destroying dialogs when no application object is available.
That is why I prefer heap-allocated singletons. I provide an explicit init()
and term()
methods for all the singletons and call them inside main
. Thus I have a full control over the order of singletons creation/destruction, and also I guarantee that singletons will be created, no matter whether someone called getInstance()
or not.
Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.
Try something like the following, either schema-mapped:
new Schema({ url: String, text: String, id: Number},
{ collection : 'question' }); // collection name
or model mapped:
mongoose.model('Question',
new Schema({ url: String, text: String, id: Number}),
'question'); // collection name
this is working for me:
<td>
<div class="avoid">
Cell content.
</div>
</td>
...
<style type="text/css">
.avoid {
page-break-inside: avoid !important;
margin: 4px 0 4px 0; /* to keep the page break from cutting too close to the text in the div */
}
</style>
From this thread: avoid page break inside row of table
You could do the opposite of what you proposed.
location (/test)/ {
set $folder $1;
}
location (/test_/something {
set $folder $1;
}
I'm using CSS Dig. It is made for chrome, but I think it is a great tool!
In a LAN (Local Area Network) we have a server computer, here named xhost running Windows 10, IIS is activated as WebServer. We must access this computer via Browser like Google Chrome not only from localhost through https://localhost/ from server itsself, but also from other hosts in the LAN with URL https://xhost/ :
https://localhost/
https://xhost/
https://xhost.local/
...
With this manner of accessing, we have not a fully-qualified domain name, but only local computer name xhost here.
Or from WAN:
https://dev.example.org/
...
You shall replace xhost by your real local computer name.
None of above solutions may satisfy us. After days of try, we have adopted the solution openssl.exe. We use 2 certificates - a CA (self certified Authority certificate) RootCA.crt and xhost.crt certified by the former. We use PowerShell.
cd C:\users\so\crt
openssl req -x509 -nodes -new -sha256 -days 10240 -newkey rsa:2048 -keyout RootCA.key -out RootCA.pem -subj "/C=ZA/CN=RootCA-CA"
openssl x509 -outform pem -in RootCA.pem -out RootCA.crt
C: Country
ST: State
L: locality (city)
O: Organization Name
Organization Unit
CN: Common Name
openssl req -new -nodes -newkey rsa:2048 -keyout xhost.key -out xhost.csr -subj "/C=ZA/ST=FREE STATE/L=Golden Gate Highlands National Park/O=WWF4ME/OU=xhost.home/CN=xhost.local"
openssl x509 -req -sha256 -days 1024 -in xhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out xhost.crt
with extfile domains.ext file defining many secured ways of accessing the server website:
authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
DNS.2 = xhost
DNS.3 = xhost.local
DNS.4 = dev.example.org
DNS.5 = 192.168.1.2
combinig both private xhost.key and certificate xhost.crt, permitting to import into iis. This step asks for password, please let it empty by pressing [RETURN] key (without password):
openssl pkcs12 -export -out xhost.pfx -inkey xhost.key -in xhost.crt
installed in xhost computer (here localhost). and Restart IIS service.
IIS10 Gestionnaire des services Internet (IIS) (%windir%\system32\inetsrv\InetMgr.exe)
Restart IIS Service.
via Google Chrome in any computer that will access the website https://xhost/.
\Google Chrome/…/Settings /[Advanced]/Privacy and Security/Security/Manage certificates
Import RootCA.crt
The browser will show this valid certificate tree:
RootCA-CA
|_____ xhost.local
No Certificate Error will appear through LAN, even through WAN by https://dev.example.org.
Here is the whole Powershell Script socrt.ps1 file to generate all required certificate files from the naught:
#
# Generate:
# RootCA.pem, RootCA.key RootCA.crt
#
# xhost.key xhost.csr xhost.crt
# xhost.pfx
#
# created 15-EEC-2020
# modified 15-DEC-2020
#
#
# change to a safe directory:
#
cd C:\users\so\crt
#
# Generate RootCA.pem, RootCA.key & RootCA.crt as Certification Authority:
#
openssl req -x509 -nodes -new -sha256 -days 10240 -newkey rsa:2048 -keyout RootCA.key -out RootCA.pem -subj "/C=ZA/CN=RootCA-CA"
openssl x509 -outform pem -in RootCA.pem -out RootCA.crt
#
# get RootCA.pfx: permitting to import into iis10: not required.
#
#openssl pkcs12 -export -out RootCA.pfx -inkey RootCA.key -in RootCA.crt
#
# get xhost.key xhost.csr:
# C: Country
# ST: State
# L: locality (city)
# O: Organization Name
# OU: Organization Unit
# CN: Common Name
#
openssl req -new -nodes -newkey rsa:2048 -keyout xhost.key -out xhost.csr -subj "/C=ZA/ST=FREE STATE/L=Golden Gate Highlands National Park/O=WWF4ME/OU=xhost.home/CN=xhost.local"
#
# get xhost.crt certified by RootCA.pem:
# to show content:
# openssl x509 -in xhost.crt -noout -text
#
openssl x509 -req -sha256 -days 1024 -in xhost.csr -CA RootCA.pem -CAkey RootCA.key -CAcreateserial -extfile domains.ext -out xhost.crt
#
# get xhost.pfx, permitting to import into iis:
#
openssl pkcs12 -export -out xhost.pfx -inkey xhost.key -in xhost.crt
#
# import xhost.pfx in iis10 installed in xhost computer (here localhost).
#
To install openSSL for Windows, please visit https://slproweb.com/products/Win32OpenSSL.html
What worked for me:
Since yesterday, I have been trying to install the Eclipse plugin - "Remote System Explorer" from the Eclipse marketplace on a freshly downloaded Eclipse 4.8 as shown below,
and everytime I was getting this error:
Unable to read repository at http://download.eclipse.org/releases/kepler/. Unable to read repository at http://download.eclipse.org/releases/kepler/201306260900/content.jar. download.eclipse.org:80 failed to respond
which brought me to this SO post.
I tried a few solutions mentioned here in the different answers like this one and this one and this one, but none of them worked. I just gave up almost, thinking that either the corporate network here is somehow blocking the specific download requests or the 4.8 version of Eclipse is buggy.
Discovery:
I could not reload all the paths under 'Window' -> 'Preferences' -> 'Install/Update' -> 'Available Software Sites'
.
Preconditions:
What did work for me from the beginning was:
Finally, this answer put me on the right track - for my specific case, at least. Just my step was to do the exact opposite of what that answer was doing.
Solution:
I had to change all the http:\\
paths to https:\\
and suddenly it started to work. I don't know who - either IE/Edge on Windows 10 or the Windows 10 firewall or the company firewall is blocking HTTP communications. But with HTTPS, I can finally install plugins from the Marketplace.
I must say, what is strange is that not all the paths required https
. Except a few, the rest seemed to have had no problem working with HTTP
. But I anyways changed all to HTTPS
, just for good measure.
Note: In case during the update, this same error pops up again, then see in the repositories that any new paths added by eclipse during the update, are also HTTPS and not HTTP.
For starters:
<p align='center'>
<table width='100%'>
<tr>
<td align='center'><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
Note, if the width of the input button is 100%, you wont need the attribute "align='center'" anymore.
This would be the optimal solution:
<p align='center'>
<table width='100%'>
<tr>
<td><form><input type=submit value="click me" style="width:100%"></form></td>
</tr>
</table>
</p>
For C++ it depends on what you are doing. OK, it is stupid code but imagine
class myTimeEatingClass { public: //constructor myTimeEatingClass() { sleep(2000); ms_usedTime+=2; } ~myTimeEatingClass() { sleep(3000); ms_usedTime+=3; } const unsigned int getTime() const { return ms_usedTime; } static unsigned int ms_usedTime; };
myTimeEatingClass::ms_CreationTime=0;
myFunc()
{
for (int counter = 0; counter <= 10; counter++) {
myTimeEatingClass timeEater();
//do something
}
cout << "Creating class took "<< timeEater.getTime() <<"seconds at all<<endl;
}
myOtherFunc()
{
myTimeEatingClass timeEater();
for (int counter = 0; counter <= 10; counter++) {
//do something
}
cout << "Creating class took "<< timeEater.getTime() <<"seconds at all<<endl;
}
You will wait 55 seconds until you get the output of myFunc. Just because each loop contructor and destructor together need 5 seconds to finish.
You will need 5 seconds until you get the output of myOtherFunc.
Of course, this is a crazy example.
But it illustrates that it might become a performance issue when each loop the same construction is done when the constructor and / or destructor needs some time.
As a noobie I was confused by this until I realized that the so called "path" is the path relative to the MyClass.class file in the file system and not the MyClass.java file. My IDE copies the resources (like xx.jpg, xx.xml) to a directory local to the MyClass.class. For example, inside a pkg directory called "target/classes/pkg. The class-file location may be different for different IDE's and depending on how the build is structured for your application. You should first explore the file system and find the location of the MyClass.class file and the copied location of the associated resource you are seeking to extract. Then determine the path relative to the MyClass.class file and write that as a string value with "dots" and "slashes".
For example, here is how I make an app1.fxml file available to my javafx application where the relevant "MyClass.class" is implicitly "Main.class". The Main.java file is where this line of resource-calling code is contained. In my specific case the resources are copied to a location at the same level as the enclosing package folder. That is: /target/classes/pkg/Main.class and /target/classes/app1.fxml. So paraphrasing...the relative reference "../app1.fxml" is "start from Main.class, go up one directory level, now you can see the resource".
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("../app1.fxml"));
Note that in this relative-path string "../app1.fxml", the first two dots reference the directory enclosing Main.class and the single "." indicates a file extension to follow. After these details become second nature, you will forget why it was confusing.
To print the last column of a line just use $(NF):
awk '{print $(NF)}'
I think you can't. The SELECT element is rendered at a point beyond the reach of CSS and HTML. Is it grayed out?
But you can try to add a "size" atribute.
Let me propose this solution for you. So in your managed bean, do this
public String convertTime(long time){
Date date = new Date(time);
Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
return format.format(date);
}
so in your JSF page, you can do this (assuming foo
is the object that contain your time
)
<h:dataTable value="#{myBean.convertTime(myBean.foo.time)}" />
If you have multiple pages that want to utilize this method, you can put this in an abstract class
and have your managed bean extend this abstract class
.
EDIT: Return time with TimeZone
unfortunately, I think SimpleDateFormat
will always format the time in local time, so we can't use SimpleDateFormat
anymore. So to display time in different TimeZone, we can do this
public String convertTimeWithTimeZome(long time){
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTimeInMillis(time);
return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " "
+ cal.get(Calendar.DAY_OF_MONTH) + " " + cal.get(Calendar.HOUR_OF_DAY) + ":"
+ cal.get(Calendar.MINUTE));
}
A better solution is to utilize JodaTime
. In my opinion, this API is much better than Calendar (lighter weight, faster and provide more functionality). Plus Calendar.Month
of January
is 0
, that force developer to add 1
to the result, and you have to format the time yourself. Using JodaTime
, you can fix all of that. Correct me if I am wrong, but I think JodaTime
is incorporated in JDK7
Here's an example of writing some lines to a file using scalaz-stream.
import scalaz._
import scalaz.stream._
def writeLinesToFile(lines: Seq[String], file: String): Task[Unit] =
Process(lines: _*) // Process that enumerates the lines
.flatMap(Process(_, "\n")) // Add a newline after each line
.pipe(text.utf8Encode) // Encode as UTF-8
.to(io.fileChunkW(fileName)) // Buffered write to the file
.runLog[Task, Unit] // Get this computation as a Task
.map(_ => ()) // Discard the result
writeLinesToFile(Seq("one", "two"), "file.txt").run
I would just use this small extension to Date
- http://blog.stevenlevithan.com/archives/date-time-format
var date = new Date(msSinceEpoch);
date.format("isoDateTime"); // 2007-06-09T17:46:21
BE CAREFUL!!!
One should try to avoid calling a function by string in JavaScript for two reasons:
Reason 1: Some code obfuscators will wreck your code as they will change the function names, making the string invalid.
Reason 2: It is much harder to maintain code that uses this methodology as it is much harder to locate usages of the methods called by a string.
Roll your own toFixed
function: for positive values Math.floor
works fine.
function toFixed(num, fixed) {
fixed = fixed || 0;
fixed = Math.pow(10, fixed);
return Math.floor(num * fixed) / fixed;
}
For negative values Math.floor
is round of the values. So you can use Math.ceil
instead.
Example,
Math.ceil(-15.778665 * 10000) / 10000 = -15.7786
Math.floor(-15.778665 * 10000) / 10000 = -15.7787 // wrong.
INSERT INTO Table
( Event_ID
, col2
...
)
SELECT "155"
, col2
...
FROM Table WHERE Event_ID = "120"
Here, the col2, ... represent the remaining columns (the ones other than Event_ID) in your table.
Install Tidy2 plugin. I have Notepad++ v6.2.2, and Tidy2 works fine so far.
According to others said, you cannot instantiate from abstract class. but it exist 2 way to use it. 1. make another non-abstact class that extends from abstract class. So you can instantiate from new class and use the attributes and methods in abstract class.
public class MyCustomClass extends YourAbstractClass {
/// attributes, methods ,...
}
System.String is a reference type and already "nullable".
Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.
This date function below achieves the desired effect without an additional script library. Basically it's just a simple date component concatenation in the right format, and augmenting of the Date object's prototype.
Date.prototype.dateToISO8601String = function() {
var padDigits = function padDigits(number, digits) {
return Array(Math.max(digits - String(number).length + 1, 0)).join(0) + number;
}
var offsetMinutes = this.getTimezoneOffset();
var offsetHours = offsetMinutes / 60;
var offset= "Z";
if (offsetHours < 0)
offset = "-" + padDigits(offsetHours.replace("-","") + "00",4);
else if (offsetHours > 0)
offset = "+" + padDigits(offsetHours + "00", 4);
return this.getFullYear()
+ "-" + padDigits((this.getUTCMonth()+1),2)
+ "-" + padDigits(this.getUTCDate(),2)
+ "T"
+ padDigits(this.getUTCHours(),2)
+ ":" + padDigits(this.getUTCMinutes(),2)
+ ":" + padDigits(this.getUTCSeconds(),2)
+ "." + padDigits(this.getUTCMilliseconds(),2)
+ offset;
}
Date.dateFromISO8601 = function(isoDateString) {
var parts = isoDateString.match(/\d+/g);
var isoTime = Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
var isoDate = new Date(isoTime);
return isoDate;
}
function test() {
var dIn = new Date();
var isoDateString = dIn.dateToISO8601String();
var dOut = Date.dateFromISO8601(isoDateString);
var dInStr = dIn.toUTCString();
var dOutStr = dOut.toUTCString();
console.log("Dates are equal: " + (dInStr == dOutStr));
}
Usage:
var d = new Date();
console.log(d.dateToISO8601String());
Hopefully this helps someone else.
EDIT
Corrected UTC issue mentioned in comments, and credit to Alex for the dateFromISO8601
function.
This is what I have been using successfully:
...
<div class="custom-file">
<input type="file" class="custom-file-input image-gallery" id="image-gallery" name="image-gallery[]" multiple accept="image/*">
<label class="custom-file-label" for="image-gallery">Upload Image(s)</label>
</div>
...
It is always a good idea to check for the actual file type on the server-side as well.
Do you have adequate permissions to your repo'?
My solution was unrelated to git
, however I was seeing the same error messages, and dirty status of submodules.
The root-cause was some files in the .git
folder were owned by root
, so git
did not have write access, therefore git
could not change the dirty state of submodules when run as my user.
Do you have the same problem?
From your repository's root folder, use find
to list files owned by root [optional]
find .git -user root
Sollution [Linux]
Change all files in the .git
folder to have you as the owner
sudo chown -R $USER:$USER .git
# alternatively, only the files listed in the above command...
sudo find .git -user root -exec chown $USER:$USER {} +
How did this happen?
In my case I built libraries in sub-modules from a docker container, the docker daemon traditionally runs as root
, so files created fall into root:root
ownership.
My user has root privileges by proxy through that service, so even though I didn't sudo
anything, my git repository still had changes owned by root
.
I hope this helps someone, git outa here.
Try this regex:
/^[\w&.-]+$/
Also you can use test
.
if ( pattern.test( qry ) ) {
// valid
}
#!/bin/bash
ping_count="4"
avg_max_limit="1500"
router="sagemcom-fast-2804-v2"
adress="192.168.1.1"
user="admin"
pass="admin"
VAR=$(
expect -c "
set timeout 3
spawn telnet "$adress"
expect \"Login:\"
send \"$user\n\"
expect \"Password:\"
send \"$pass\n\"
expect \"commands.\"
send \"ping ya.ru -c $ping_count\n\"
set timeout 9
expect \"transmitted\"
send \"exit\"
")
count_ping=$(echo "$VAR" | grep packets | cut -c 1)
avg_ms=$(echo "$VAR" | grep round-trip | cut -d '/' -f 4 | cut -d '.' -f 1)
echo "1_____ping___$count_ping|||____$avg_ms"
echo "$VAR"
You need to make your regex pattern 'non-greedy' by adding a '?' after the '.+'
By default, '*' and '+' are greedy in that they will match as long a string of chars as possible, ignoring any matches that might occur within the string.
Non-greedy makes the pattern only match the shortest possible match.
See Watch Out for The Greediness! for a better explanation.
Or alternately, change your regex to
\(([^\)]+)\)
which will match any grouping of parens that do not, themselves, contain parens.
Hmm, I would suggest that you use Flyweight to implement the states. Purpose: Avoid the memory overhead of a large number of small objects. State machines can get very, very big.
http://en.wikipedia.org/wiki/Flyweight_pattern
I'm not sure that I see the need to use design pattern State to implement the nodes. The nodes in a state machine are stateless. They just match the current input symbol to the available transitions from the current state. That is, unless I have entirely forgotten how they work (which is a definite possiblilty).
If I were coding it, I would do something like this:
interface FsmNode {
public boolean canConsume(Symbol sym);
public FsmNode consume(Symbol sym);
// Other methods here to identify the state we are in
}
List<Symbol> input = getSymbols();
FsmNode current = getStartState();
for (final Symbol sym : input) {
if (!current.canConsume(sym)) {
throw new RuntimeException("FSM node " + current + " can't consume symbol " + sym);
}
current = current.consume(sym);
}
System.out.println("FSM consumed all input, end state is " + current);
What would Flyweight do in this case? Well, underneath the FsmNode there would probably be something like this:
Map<Integer, Map<Symbol, Integer>> fsm; // A state is an Integer, the transitions are from symbol to state number
FsmState makeState(int stateNum) {
return new FsmState() {
public FsmState consume(final Symbol sym) {
final Map<Symbol, Integer> transitions = fsm.get(stateNum);
if (transisions == null) {
throw new RuntimeException("Illegal state number " + stateNum);
}
final Integer nextState = transitions.get(sym); // May be null if no transition
return nextState;
}
public boolean canConsume(final Symbol sym) {
return consume(sym) != null;
}
}
}
This creates the State objects on a need-to-use basis, It allows you to use a much more efficient underlying mechanism to store the actual state machine. The one I use here (Map(Integer, Map(Symbol, Integer))) is not particulary efficient.
Note that the Wikipedia page focuses on the cases where many somewhat similar objects share the similar data, as is the case in the String implementation in Java. In my opinion, Flyweight is a tad more general, and covers any on-demand creation of objects with a short life span (use more CPU to save on a more efficient underlying data structure).
Here's the code to do a nice smooth fade between two Activities..
Create a file called fadein.xml
in res/anim
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="2000" />
Create a file called fadeout.xml
in res/anim
<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_interpolator"
android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="2000" />
If you want to fade from Activity A to Activity B, put the following in the onCreate()
method for Activity B. Before setContentView()
works for me.
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
If the fades are too slow for you, change android:duration
in the xml files above to something smaller.
Pretty much everybody is using getopt
Here is the example code for the doc :
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-o", "--output"):
output = a
So in a word, here is how it works.
You've got two types of options. Those who are receiving arguments, and those who are just like switches.
sys.argv
is pretty much your char** argv
in C. Like in C you skip the first element which is the name of your program and parse only the arguments : sys.argv[1:]
Getopt.getopt
will parse it according to the rule you give in argument.
"ho:v"
here describes the short arguments : -ONELETTER
. The :
means that -o
accepts one argument.
Finally ["help", "output="]
describes long arguments ( --MORETHANONELETTER
).
The =
after output once again means that output accepts one arguments.
The result is a list of couple (option,argument)
If an option doesn't accept any argument (like --help
here) the arg
part is an empty string.
You then usually want to loop on this list and test the option name as in the example.
I hope this helped you.
There is a mistake in your insert statement chage it to below and try :
String sql = "insert into table_name values ('" + Col1 +"','" + Col2 + "','" + Col3 + "')";
try :
mvn install:install-file -DgroupId=jdk.tools -DartifactId=jdk.tools -Dversion=1.6 -Dpackaging=jar -Dfile="C:\Program Files\Java\jdk\lib\tools.jar"
also check : http://maven.apache.org/guides/mini/guide-3rd-party-jars-local.html
Use @ViewChildren
from @angular/core
to get a reference to the components
template
<div *ngFor="let v of views">
<customcomponent #cmp></customcomponent>
</div>
component
import { ViewChildren, QueryList } from '@angular/core';
/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;
ngAfterViewInit(){
// print array of CustomComponent objects
console.log(this.components.toArray());
}
If you're using SQL Server 2008, there's a new featured called a User Defined Table Type. Here is an example of how to use it:
Create your User Defined Table Type:
CREATE TYPE [dbo].[StringList] AS TABLE(
[Item] [NVARCHAR](MAX) NULL
);
Next you need to use it properly in your stored procedure:
CREATE PROCEDURE [dbo].[sp_UseStringList]
@list StringList READONLY
AS
BEGIN
-- Just return the items we passed in
SELECT l.Item FROM @list l;
END
Finally here's some sql to use it in c#:
using (var con = new SqlConnection(connstring))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("exec sp_UseStringList @list", con))
{
using (var table = new DataTable()) {
table.Columns.Add("Item", typeof(string));
for (int i = 0; i < 10; i++)
table.Rows.Add("Item " + i.ToString());
var pList = new SqlParameter("@list", SqlDbType.Structured);
pList.TypeName = "dbo.StringList";
pList.Value = table;
cmd.Parameters.Add(pList);
using (var dr = cmd.ExecuteReader())
{
while (dr.Read())
Console.WriteLine(dr["Item"].ToString());
}
}
}
}
To execute this from SSMS
DECLARE @list AS StringList
INSERT INTO @list VALUES ('Apple')
INSERT INTO @list VALUES ('Banana')
INSERT INTO @list VALUES ('Orange')
-- Alternatively, you can populate @list with an INSERT-SELECT
INSERT INTO @list
SELECT Name FROM Fruits
EXEC sp_UseStringList @list
MySQL documentation covers this topic.
Here is a synopsis. When using join
or inner join
, the on
condition is optional. This is different from the ANSI standard and different from almost any other database. The effect is a cross join
. Similarly, you can use an on
clause with cross join
, which also differs from standard SQL.
A cross join creates a Cartesian product -- that is, every possible combination of 1 row from the first table and 1 row from the second. The cross join for a table with three rows ('a', 'b', and 'c') and a table with four rows (say 1, 2, 3, 4) would have 12 rows.
In practice, if you want to do a cross join, then use cross join
:
from A cross join B
is much better than:
from A, B
and:
from A join B -- with no on clause
The on
clause is required for a right or left outer join, so the discussion is not relevant for them.
If you need to understand the different types of joins, then you need to do some studying on relational databases. Stackoverflow is not an appropriate place for that level of discussion.
int a[] = { 2, 6, 8, 5, 4, 3 };
int b[] = { 2, 3, 4, 7 };
if you take float number then you take float and it's your choice
this is very good way to show array elements.
To read more than one json tip (array, attribute) I did the following.
var jVariable = JsonConvert.DeserializeObject<YourCommentaryClass>(jsonVariableContent);
change to
var jVariable = JsonConvert.DeserializeObject <List<YourCommentaryClass>>(jsonVariableContent);
Because you cannot see all the bits in the method used in the foreach loop. Example foreach loop
foreach (jsonDonanimSimple Variable in jVariable)
{
debugOutput(jVariable.Id.ToString());
debugOutput(jVariable.Header.ToString());
debugOutput(jVariable.Content.ToString());
}
I also received an error in this loop and changed it as follows.
foreach (jsonDonanimSimple Variable in jVariable)
{
debugOutput(Variable.Id.ToString());
debugOutput(Variable.Header.ToString());
debugOutput(Variable.Content.ToString());
}
Have you tried what is on the sample. I am new to this but here is the command: puppet --test --trace --debug. I hope this helps.
You just want to call an external URL and use the results? PHP does this out of the box, if we're talking about a simple GET request to something serving JSON:
$json = json_decode(file_get_contents('http://host.com/api/stuff/1'), true);
If you want to do a post request, it's a little harder but there's loads of examples how to do this with curl.
So I guess the question is; what exactly do you want?
buildup on nawfal 's answer.
when using his answer there was a missing variable aggrEx, I added it.
file ExceptionExtenstions.class:
// example usage:
// try{ ... } catch(Exception e) { MessageBox.Show(e.ToFormattedString()); }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YourNamespace
{
public static class ExceptionExtensions
{
public static IEnumerable<Exception> GetAllExceptions(this Exception exception)
{
yield return exception;
if (exception is AggregateException )
{
var aggrEx = exception as AggregateException;
foreach (Exception innerEx in aggrEx.InnerExceptions.SelectMany(e => e.GetAllExceptions()))
{
yield return innerEx;
}
}
else if (exception.InnerException != null)
{
foreach (Exception innerEx in exception.InnerException.GetAllExceptions())
{
yield return innerEx;
}
}
}
public static string ToFormattedString(this Exception exception)
{
IEnumerable<string> messages = exception
.GetAllExceptions()
.Where(e => !String.IsNullOrWhiteSpace(e.Message))
.Select(exceptionPart => exceptionPart.Message.Trim() + "\r\n" + (exceptionPart.StackTrace!=null? exceptionPart.StackTrace.Trim():"") );
string flattened = String.Join("\r\n\r\n", messages); // <-- the separator here
return flattened;
}
}
}
If you only want to add Datapoints above the bars, you could easily do it with:
for i in range(len(frequencies)): # your number of bars
plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument
y = y_values[i]+1, #takes your y values as vertical positioning argument
s = data_labels[i], # the labels you want to add to the data
size = 9) # font size of datalabels
I have also read that for some servers one for example needs only annotate persistence contexts, but in some servers, the injection should be done manually.
If all you want to do is to remove a merge commit (2) so that it is like it never happened, the command is simply as follows
git rebase --onto <sha of 1> <sha of 2> <blue branch>
And now the purple branch isn't in the commit log of blue at all and you have two separate branches again. You can then squash the purple independently and do whatever other manipulations you want without the merge commit in the way.
Try this way:
<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>
select
helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options
.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select
The position :fixed
is differ from the other layout.
Once you fixed
the position
for your header
, keep in mind that you have to set the margin-top
for the content
div.
I think that the most elegant way to do it is to implement custom Flash Scope in Spring MVC.
the main idea for the flash scope is to store data from one controller till next redirect in second controller
Please refer to my answer on the custom scope question:
The only thing that is missing in this code is the following xml configuration:
<bean id="flashScopeInterceptor" class="com.vanilla.springMVC.scope.FlashScopeInterceptor" />
<bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="interceptors">
<list><ref bean="flashScopeInterceptor"/></list>
</property>
</bean>
You can access columns by index, by name and some other ways:
dtResult.Rows(i)("columnName") = strVerse
You should probably make sure your DataTable
has some columns first...
I find answer. Thanks all but right answer next:
$("#myModal").on("hidden", function () {
$('#result').html('yes,result');
});
Events here http://bootstrap-ru.com/javascript.php#modals
UPD
For Bootstrap 3.x need use hidden.bs.modal:
$("#myModal").on("hidden.bs.modal", function () {
$('#result').html('yes,result');
});
It's the '+' operator at the beginning of the line that trips things up (not just that you are using two '+' operators consecutively). The '+' operator can be used at the end of lines, but not at the beginning.
This works:
ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
geom_boxplot()
The does not:
ggplot(combined.data, aes(x = region, y = expression, fill = species))
+ geom_boxplot()
*Error in + geom_boxplot():
invalid argument to unary operator*
You also can't use two '+' operators, which in this case you've done. But to fix this, you'll have to selectively remove those at the beginning of lines.
surely you can do this with worksheet formulas, avoiding VBA entirely:
so for this value in say, column AV S:1 P:0 K:1 Q:1
you put this formula in column BC:
=MID(AV:AV,FIND("S",AV:AV)+2,1)
then these formulas in columns BD, BE...
=MID(AV:AV,FIND("P",AV:AV)+2,1)
=MID(AV:AV,FIND("K",AV:AV)+2,1)
=MID(AV:AV,FIND("Q",AV:AV)+2,1)
so these formulas look for the values S:1, P:1 etc in column AV. If the FIND
function returns an error, then 0 is returned by the formula, else 1 (like an IF, THEN, ELSE
Then you would just copy down the formulas for all the rows in column AV.
HTH Philip
I have a small script interruptableloop.py that runs the code at an interval (default 1sec), it pumps out a message to the screen while it's running, and traps an interrupt signal that you can send with CTL-C:
#!/usr/bin/python3
from interruptableLoop import InterruptableLoop
loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
# some python code that I want
# to keep on running
pass
When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):
[py36]$ ./interruptexample.py
CTL-C to stop (or $kill -s SIGINT pid)
......^C
Exiting at 2018-07-28 14:58:40.359331
interruptableLoop.py:
"""
Use to create a permanent loop that can be stopped ...
... from same terminal where process was started and is running in foreground:
CTL-C
... from same user account but through a different terminal
$ kill -2 <pid>
or $ kill -s SIGINT <pid>
"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
def __init__(self,intervalSecs=1,printStatus=True):
self.intervalSecs=intervalSecs
self.shouldContinue=True
self.printStatus=printStatus
self.interrupted=False
if self.printStatus:
print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
signal.signal(signal.SIGINT, self._StopRunning)
signal.signal(signal.SIGQUIT, self._Abort)
signal.signal(signal.SIGTERM, self._Abort)
def _StopRunning(self, signal, frame):
self.shouldContinue = False
def _Abort(self, signal, frame):
raise
def ShouldContinue(self):
time.sleep(self.intervalSecs)
if self.shouldContinue and self.printStatus:
print( ".",end="",flush=True)
elif not self.shouldContinue and self.printStatus:
print ("Exiting at ",dtt.now())
return self.shouldContinue
For me it was that I was passing a function result as 2-way binding input '=' to a directive that was creating a new object every time.
so I had something like that:
<my-dir>
<div ng-repeat="entity in entities">
<some-other-dir entity="myDirCtrl.convertToSomeOtherObject(entity)"></some-other-dir>
</div>
</my-dir>
and the controller method on my-dir was
this.convertToSomeOtherObject(entity) {
var obj = new Object();
obj.id = entity.Id;
obj.value = entity.Value;
[..]
return obj;
}
which when I made to
this.convertToSomeOtherObject(entity) {
var converted = entity;
converted.id = entity.Id;
converted.value = entity.Value;
[...]
return converted;
}
solved the problem!
Hopefully this will help someone :)
Here more flexible variant: it uses external shell, but allows to check for arbitrary conditions:
ifeq ($(shell test ".$(GCC_MINOR)" = .4 -o \
".$(GCC_MINOR)" = .5 -o \
".$(TODAY)" = .Friday && printf "true"), true)
CFLAGS += -fno-strict-overflow
endif
I found the answer to the second part of my questions. Yes, a class can implement an interface that is in a different class as long that the interface is declared as public.
theme(plot.title = element_text(size = 12, face = "bold"),
legend.title=element_text(size=10),
legend.text=element_text(size=9))
I came accross very intuitive explanation at this webpage http://doandroids.com/blogs/tag/codeexample/. Taken from there:
- boolean onTouchEvent(MotionEvent ev) - called whenever a touch event with this View as target is detected
- boolean onInterceptTouchEvent(MotionEvent ev) - called whenever a touch event is detected with this ViewGroup or a child of it as target. If this function returns true, the MotionEvent will be intercepted, meaning it will be not be passed on to the child, but rather to the onTouchEvent of this View.
Use case match for early return purpose. It will force you to declare all return branches explicitly, preventing the careless mistake of forgetting to write return somewhere.
CREATE TABLE table_temp_list_objects AS
SELECT o.owner, o.object_name FROM sys.all_objects o WHERE o.object_type ='TABLE';
Do Shift+F5 in Windows. The cache really frustrates in this kind of stuff
I use PyCharm which has great capabilities to compare between folders and files.
Just open the parent folder for both repos and wait until it indexes. Then you can use right click on a folder or file and Compare to...
and pick the corresponding folder / file on the other side.
It shows not only what files are different but also their content. Much easier than command line.
Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const
correctness in a compact way.
Something like this:
const int n = (x != 0) ? 10 : 20;
so basically n
is a const
whose initial value is dependent on a condition statement. The easiest alternative is to make n
not a const
, this would allow an ordinary if
to initialize it. But if you want it to be const
, it cannot be done with an ordinary if
. The best substitute you could make would be to use a helper function like this:
int f(int x) {
if(x != 0) { return 10; } else { return 20; }
}
const int n = f(x);
but the ternary if version is far more compact and arguably more readable.
Do
find / -type f -name "php.ini"
This will output all files named php.ini
.
Find out which one you're using, usually apache2/php.ini
In order to center text in md files you can use the center tag like html tag:
<center>Centered text</center>
Ok got minus, cause didn't describe my example, so more examples:):
I use regular expression and test method:
var isInteger = /^[0-9]\d*$/;
isInteger.test(123); //true
isInteger.test('123'); // true
isInteger.test('sdf'); //false
isInteger.test('123sdf'); //false
// If u want to avoid string value:
typeof testVal !== 'string' && isInteger.test(testValue);
I see three issues:
value
attribute.First, I recommend that you use the setTimeout
function to ensure that code is executed after the form reset is complete.
You could execute code when the button is clicked:
$('#searchclear').click(function() {
setTimeout(function() {
// Code goes here.
}, 0);
});
Or when the form is reset:
$('form').on('reset', function() {
setTimeout(function() {
// Code goes here.
}, 0);
});
As for what code to use:
Since the "All" option is disabled, the form reset does not make it the selected value. Therefore, you must explicitly set it to be the selected value. The way to do that is with the Select2 "val" function. And since the "All" option does not have a value
attribute, its value is the same as its text, which is "All". Therefore, you should use the code given by thtsigma in the selected answer:
$("#d").select2('val', 'All');
If the attribute value=""
were to be added to the "All" option, then you could use the code given by Daniel Dener:
$("#d").select2('val', '');
If the "All" option was not disabled, then you would just have to force the Select2 to refresh, in which case you could use:
$('#d').change();
Note: The following code by Lenart is a way to clear the selection, but it does not cause the "All" option to be selected:
$('#d').select2('data', null)
You can use the date
function. I'm using strtotime
to get the timestamp to that day ; there are other solutions, like mktime
, for instance.
For instance, with the 'D' modifier, for the textual representation in three letters :
$timestamp = strtotime('2009-10-22');
$day = date('D', $timestamp);
var_dump($day);
You will get :
string 'Thu' (length=3)
And with the 'l' modifier, for the full textual representation :
$day = date('l', $timestamp);
var_dump($day);
You get :
string 'Thursday' (length=8)
Or the 'w' modifier, to get to number of the day (0 to 6, 0 being sunday, and 6 being saturday) :
$day = date('w', $timestamp);
var_dump($day);
You'll obtain :
string '4' (length=1)
You can display a live preview of a link using javascript using the code below.
<embed src="https://www.w3schools.com/html/default.asp" width="60" height="40" />_x000D_
<p id="p1"><a href="http://cnet.com">Cnet</a></p>_x000D_
<p id="p2"><a href="http://codegena.com">Codegena</a></p>_x000D_
<p id="p3"><a href="http://apple.com">Apple</a></p>_x000D_
_x000D_
_x000D_
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>_x000D_
<link href="http://codegena.com/assets/css/image-preview-for-link.css" rel="stylesheet"> _x000D_
<script type="text/javascript">_x000D_
$(function() {_x000D_
$('#p1 a').miniPreview({ prefetch: 'pageload' });_x000D_
$('#p2 a').miniPreview({ prefetch: 'parenthover' });_x000D_
$('#p3 a').miniPreview({ prefetch: 'none' });_x000D_
});_x000D_
</script> <script src="http://codegena.com/assets/js/image-preview-for-link.js"></script>
_x000D_
Learn more about it at Codegena
id="p1" - Fetch image preview on page load.
id="p2" - Fetch preview on hover.
id="p3" - Fetch preview image each time you hover.
brew switch openssl 1.0.2s
worked for me on "macOS Mojave", "version 10.14.6".
This issue was with me also. Simple trick for it.
@NgModule({
imports: [
.....
],
declarations: [
......
],
providers: [...],
bootstrap: [...]
})
use it as in above order.first imports then declarations.It worked for me.
On Linux/OS X/Unix to display the groups to which you (or the optionally specified user) belong, use:
id -Gn [user]
which is equivalent to groups [user]
utility which has been obsoleted on Unix.
On OS X/Unix, the command id -p [user]
is suggested for normal interactive.
Explanation on the parameters:
-G
,--groups
- print all group IDs
-n
,--name
- print a name instead of a number, for-ugG
-p
- Make the output human-readable.
Take the contents of the file, split it by newline into a tuple. Then, access your tuple's line number, join your result tuple, and overwrite to the file.
A very convenient way is readr::read_delim
-family. Taking the example from here:
Importing csv with multiple separators into R you can do it as follows:
txt <- 'OBJECTID,District_N,ZONE_CODE,COUNT,AREA,SUM
1,Bagamoyo,1,"136,227","8,514,187,500.000000000000000","352,678.813105723350000"
2,Bariadi,2,"88,350","5,521,875,000.000000000000000","526,307.288878142830000"
3,Chunya,3,"483,059","30,191,187,500.000000000000000","352,444.699742995200000"'
require(readr)
read_csv(txt) # = read_delim(txt, delim = ",")
Which results in the expected result:
# A tibble: 3 × 6
OBJECTID District_N ZONE_CODE COUNT AREA SUM
<int> <chr> <int> <dbl> <dbl> <dbl>
1 1 Bagamoyo 1 136227 8514187500 352678.8
2 2 Bariadi 2 88350 5521875000 526307.3
3 3 Chunya 3 483059 30191187500 352444.7
The CSS3 specification allowing different origins for background-position is now supported in Firefox 14 but still not in Chrome 21 (apparently IE9 partly supports them, but I've not tested it myself)
In addition to the Chrome issue that @MattyF referenced there's a more succinct summary here: http://code.google.com/p/chromium/issues/detail?id=95085
So, this is an awfully old question which already has an accepted answer, but I believe that this answer would have been chosen had it been posted four years ago.
I solved this purely with CSS, and with NO EXTRA DOM ELEMENTS! This means that the two colors are purely that, just background colors of ONE ELEMENT, not the background color of two.
I used a gradient and, because I set the color stops so closely together, it looks as if the colors are distinct and that they do not blend.
Here is the gradient in native syntax:
background: repeating-linear-gradient(#74ABDD, #74ABDD 49.9%, #498DCB 50.1%, #498DCB 100%);
Color #74ABDD
starts at 0%
and is still #74ABDD
at 49.9%
.
Then, I force the gradient to shift to my next color within 0.2%
of the elements height, creating what appears to be a very solid line between the two colors.
Here is the outcome:
Have fun!
Although many answers are given, I couldn't find one I am happy with. I figured out my own solution which makes property
work for the dynamic case. The source to answer the original question:
#!/usr/local/bin/python3
INITS = { 'ab': 100, 'cd': 200 }
class DP(dict):
def __init__(self):
super().__init__()
for k,v in INITS.items():
self[k] = v
def _dict_set(dp, key, value):
dp[key] = value
for item in INITS.keys():
setattr(
DP,
item,
lambda key: property(
lambda self: self[key], lambda self, value: _dict_set(self, key, value)
)(item)
)
a = DP()
print(a) # {'ab': 100, 'cd': 200}
a.ab = 'ab100'
a.cd = False
print(a.ab, a.cd) # ab100 False
In case you're using Gradle Kotlin syntax, you also can do:
tasks.taskName {
environment(mapOf("A" to 1, "B" to "C"))
}
So for test
task this would be:
tasks.test {
environment(mapOf("SOME_TEST_VAR" to "aaa"))
}
Using np.percentile
.
q75, q25 = np.percentile(DataFrame, [75,25])
iqr = q75 - q25
Answer from How do you find the IQR in Numpy?
So let's say after getMasterData servlet will response.sendRedirect to to test.jsp.
In test.jsp
Create a javascript
<script type="text/javascript">
function alertName(){
alert("Form has been submitted");
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
Note:im not sure how to type the code in stackoverflow!. Edit: I just learned how to
Edit 2: TO the question:This works perfectly. Another question. How would I get rid of the initial alert when I first start up the JSP? "Form has been submitted" is present the second I execute. It shows up after the load is done to which is perfect.
To do that i would highly recommendation to use session!
So what you want to do is in your servlet:
session.setAttribute("getAlert", "Yes");//Just initialize a random variable.
response.sendRedirect(test.jsp);
than in the test.jsp
<%
session.setMaxInactiveInterval(2);
%>
<script type="text/javascript">
var Msg ='<%=session.getAttribute("getAlert")%>';
if (Msg != "null") {
function alertName(){
alert("Form has been submitted");
}
}
</script>
and than at the bottom
<script type="text/javascript"> window.onload = alertName; </script>
So everytime you submit that form a session will be pass on! If session is not null the function will run!
A simple INSERT INTO SELECT statement:
INSERT INTO persons_table SELECT * FROM customer_table WHERE person_name = 'tom';
DELETE FROM customer_table WHERE person_name = 'tom';
v = alli.max()
index = alli.argmax()
x, y = index/8, index%8
You can use "group by" + "orderby". See LINQ 101 for details
var list = new List<string> {"a", "b", "a", "c", "a", "b"};
var q = from x in list
group x by x into g
let count = g.Count()
orderby count descending
select new {Value = g.Key, Count = count};
foreach (var x in q)
{
Console.WriteLine("Value: " + x.Value + " Count: " + x.Count);
}
In response to this post (now deleted):
If you have a list of some custom objects then you need to use custom comparer or group by specific property.
Also query can't display result. Show us complete code to get a better help.
Based on your latest update:
You have this line of code:
group xx by xx into g
Since xx is a custom object system doesn't know how to compare one item against another. As I already wrote, you need to guide compiler and provide some property that will be used in objects comparison or provide custom comparer. Here is an example:
Note that I use Foo.Name as a key - i.e. objects will be grouped based on value of Name property.
There is one catch - you treat 2 objects to be duplicate based on their names, but what about Id ? In my example I just take Id of the first object in a group. If your objects have different Ids it can be a problem.
//Using extension methods
var q = list.GroupBy(x => x.Name)
.Select(x => new {Count = x.Count(),
Name = x.Key,
ID = x.First().ID})
.OrderByDescending(x => x.Count);
//Using LINQ
var q = from x in list
group x by x.Name into g
let count = g.Count()
orderby count descending
select new {Name = g.Key, Count = count, ID = g.First().ID};
foreach (var x in q)
{
Console.WriteLine("Count: " + x.Count + " Name: " + x.Name + " ID: " + x.ID);
}
I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.
The core function
public int Recv(byte[] buffer, int maxLen)
has name and works like "well known" socket's recv()
.
It means that
TimeoutException
.maxLen
bytes .
public class Uart : SerialPort
{
private int _receiveTimeout;
public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }
static private string ComPortName = "";
/// <summary>
/// It builds PortName using ComPortNum parameter and opens SerialPort.
/// </summary>
/// <param name="ComPortNum"></param>
public Uart(int ComPortNum) : base()
{
base.BaudRate = 115200; // default value
_receiveTimeout = 2000;
ComPortName = "COM" + ComPortNum;
try
{
base.PortName = ComPortName;
base.Open();
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine("Error: Port {0} is in use", ComPortName);
}
catch (Exception ex)
{
Console.WriteLine("Uart exception: " + ex);
}
} //Uart()
/// <summary>
/// Private property returning positive only Environment.TickCount
/// </summary>
private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }
/// <summary>
/// It uses SerialPort.BaseStream rather SerialPort functionality .
/// It Receives up to maxLen number bytes of data,
/// Or throws TimeoutException if no any data arrived during ReceiveTimeout.
/// It works likes socket-recv routine (explanation in body).
/// Returns:
/// totalReceived - bytes,
/// TimeoutException,
/// -1 in non-ComPortNum Exception
/// </summary>
/// <param name="buffer"></param>
/// <param name="maxLen"></param>
/// <returns></returns>
public int Recv(byte[] buffer, int maxLen)
{
/// The routine works in "pseudo-blocking" mode. It cycles up to first
/// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
/// If no any message received during ReceiveTimeout property,
/// the routine throws TimeoutException
/// In other hand, if any data has received, first no-data cycle
/// causes to exit from routine.
int TimeOutSpan = 2;
// counts delay in TimeOutSpan-s after end of data to break receive
int EndOfDataCnt;
// pseudo-blocking timeout counter
int TimeOutCnt = _tickCount + _receiveTimeout;
//number of currently received data bytes
int justReceived = 0;
//number of total received data bytes
int totalReceived = 0;
BaseStream.ReadTimeout = TimeOutSpan;
//causes (2+1)*TimeOutSpan delay after end of data in UART stream
EndOfDataCnt = 2;
while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
{
try
{
justReceived = 0;
justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
totalReceived += justReceived;
if (totalReceived >= maxLen)
break;
}
catch (TimeoutException)
{
if (totalReceived > 0)
EndOfDataCnt--;
}
catch (Exception ex)
{
totalReceived = -1;
base.Close();
Console.WriteLine("Recv exception: " + ex);
break;
}
} //while
if (totalReceived == 0)
{
throw new TimeoutException();
}
else
{
return totalReceived;
}
} // Recv()
} // Uart
use json library
import json
json.dumps(list)
by the way, you might consider changing variable list to another name, list
is the builtin function for a list creation, you may get some unexpected behaviours or some buggy code if you don't change the variable name.
Normally, there's no need to set fields to null. I'd always recommend disposing unmanaged resources however.
From experience I'd also advise you to do the following:
I've come across some very hard to find issues that were the direct result of not following the advice above.
A good place to do this is in Dispose(), but sooner is usually better.
In general, if a reference exists to an object the garbage collector (GC) may take a couple of generations longer to figure out that an object is no longer in use. All the while the object remains in memory.
That may not be a problem until you find that your app is using a lot more memory than you'd expect. When that happens, hook up a memory profiler to see what objects are not being cleaned up. Setting fields referencing other objects to null and clearing collections on disposal can really help the GC figure out what objects it can remove from memory. The GC will reclaim the used memory faster making your app a lot less memory hungry and faster.
Why not check HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\[office.exe]
, where [office.exe]
stands for particular office product exe-filename, e.g. winword.exe
, excel.exe
etc.
There you get path to executable and check version of that file.
How to check version of the file: in C++ / in C#
Any criticism towards such approach?
I have had a similar issue in iOS 8, 9 and 10 and the info above couldn't fix it, however I did discover a solution after a day of working on this. Granted it won't work for everyone but in my case my items were stacked in a column and had 0 height when it should have been content height. Switching the css to be row and wrap fixed the issue. This only works if you have a single item and they are stacked but since it took me a day to find this out I thought I should share my fix!
.wrapper {
flex-direction: column; // <-- Remove this line
flex-direction: row; // <-- replace it with
flex-wrap: wrap; // <-- Add wrapping
}
.item {
width: 100%;
}
You need reinstall VS.
Language Pack Support in Visual Studio 2017 RC
Issue:
This release of Visual Studio supports only a single language pack for the user interface. You cannot install two languages for the user interface in the same instance of Visual Studio. In addition, you must select the language of Visual Studio during the initial install, and cannot change it during Modify.
Workaround:
These are known issues that will be fixed in an upcoming release. To change the language in this release, you can uninstall and reinstall Visual Studio.
Reference: https://www.visualstudio.com/en-us/news/releasenotes/vs2017-relnotes#november-16-2016
When you set up your validation, you should be saving the validator object. you can use this to validate individual fields.
<script type="text/javascript">
var _validator;
$(function () {
_validator = $("#form").validate();
});
function doSomething() {
_validator.element($('#someElement'));
}
</script>
-- cross posted with this similar question
You can run it in NuGet Package Manager Console in Visual Studio 2013.
SQL Server default port is 1434.
To allow remote access I had to release those ports on my firewall:
Protocol | Port
---------------------
UDP | 1050
TCP | 1050
TCP | 1433
UDP | 1434
Just another solution using the datetime
module for Python 3+.
round(datetime.datetime.timestamp(datetime.datetime.now()) * 1000)
A reasonable solution would be to use an iterator if you don't know anything about the underlying Collection, but do know that there is a "last" element. This isn't always the case, not all Collections are ordered.
Object lastElement = null;
for (Iterator collectionItr = c.iterator(); collectionItr.hasNext(); ) {
lastElement = collectionItr.next();
}
No matter what we tried we couldn't manage to get the timeout below 21 seconds when the server we were checking was down.
To work around this we combined a TcpClient check to see if the domain was alive followed by a separate check to see if the URL was active
public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
try
{
//check the domain first
if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
{
//only now check the url itself
var request = System.Net.WebRequest.Create(aUrl);
request.Method = "HEAD";
request.Timeout = aTimeoutSeconds * 1000;
var response = (HttpWebResponse)request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
}
catch
{
}
return false;
}
private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
try
{
using (TcpClient client = new TcpClient())
{
var result = client.BeginConnect(aDomain, 80, null, null);
var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));
if (!success)
{
return false;
}
// we have connected
client.EndConnect(result);
return true;
}
}
catch
{
}
return false;
}
The code pasted by Rivers is great. Thanks a lot! I'm new here and can't comment, I'd just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as I've lost a lot of time to figure it out.
You need to add the parameters both to the URL and to the signature creating process. Creating a signature is the article that helped me. Here is my code:
$oauth = array(
'screen_name' => 'DwightHoward',
'count' => 2,
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$options = array(
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
);
You actually can use an inet function. Observe.
main.c:
#include <arpa/inet.h>
main() {
uint32_t ip = 2110443574;
struct in_addr ip_addr;
ip_addr.s_addr = ip;
printf("The IP address is %s\n", inet_ntoa(ip_addr));
}
The results of gcc main.c -ansi; ./a.out
is
The IP address is 54.208.202.125
Note that a commenter said this does not work on Windows.
SELECT last_number
FROM all_sequences
WHERE sequence_owner = '<sequence owner>'
AND sequence_name = '<sequence_name>';
You can get a variety of sequence metadata from user_sequences
, all_sequences
and dba_sequences
.
These views work across sessions.
EDIT:
If the sequence is in your default schema then:
SELECT last_number
FROM user_sequences
WHERE sequence_name = '<sequence_name>';
If you want all the metadata then:
SELECT *
FROM user_sequences
WHERE sequence_name = '<sequence_name>';
Hope it helps...
EDIT2:
A long winded way of doing it more reliably if your cache size is not 1 would be:
SELECT increment_by I
FROM user_sequences
WHERE sequence_name = 'SEQ';
I
-------
1
SELECT seq.nextval S
FROM dual;
S
-------
1234
-- Set the sequence to decrement by
-- the same as its original increment
ALTER SEQUENCE seq
INCREMENT BY -1;
Sequence altered.
SELECT seq.nextval S
FROM dual;
S
-------
1233
-- Reset the sequence to its original increment
ALTER SEQUENCE seq
INCREMENT BY 1;
Sequence altered.
Just beware that if others are using the sequence during this time - they (or you) may get
ORA-08004: sequence SEQ.NEXTVAL goes below the sequences MINVALUE and cannot be instantiated
Also, you might want to set the cache to NOCACHE
prior to the resetting and then back to its original value afterwards to make sure you've not cached a lot of values.
My gulp file produces a final compiled-bundle-min.js, hope this helps someone.
//Gulpfile.js
var gulp = require("gulp");
var watch = require("gulp-watch");
var concat = require("gulp-concat");
var rename = require("gulp-rename");
var uglify = require("gulp-uglify");
var del = require("del");
var minifyCSS = require("gulp-minify-css");
var copy = require("gulp-copy");
var bower = require("gulp-bower");
var sourcemaps = require("gulp-sourcemaps");
var path = {
src: "bower_components/",
lib: "lib/"
}
var config = {
jquerysrc: [
path.src + "jquery/dist/jquery.js",
path.src + "jquery-validation/dist/jquery.validate.js",
path.src + "jquery-validation/dist/jquery.validate.unobtrusive.js"
],
jquerybundle: path.lib + "jquery-bundle.js",
ngsrc: [
path.src + "angular/angular.js",
path.src + "angular-route/angular-route.js",
path.src + "angular-resource/angular-resource.js"
],
ngbundle: path.lib + "ng-bundle.js",
//JavaScript files that will be combined into a Bootstrap bundle
bootstrapsrc: [
path.src + "bootstrap/dist/js/bootstrap.js"
],
bootstrapbundle: path.lib + "bootstrap-bundle.js"
}
// Synchronously delete the output script file(s)
gulp.task("clean-scripts", function (cb) {
del(["lib","dist"], cb);
});
//Create a jquery bundled file
gulp.task("jquery-bundle", ["clean-scripts", "bower-restore"], function () {
return gulp.src(config.jquerysrc)
.pipe(concat("jquery-bundle.js"))
.pipe(gulp.dest("lib"));
});
//Create a angular bundled file
gulp.task("ng-bundle", ["clean-scripts", "bower-restore"], function () {
return gulp.src(config.ngsrc)
.pipe(concat("ng-bundle.js"))
.pipe(gulp.dest("lib"));
});
//Create a bootstrap bundled file
gulp.task("bootstrap-bundle", ["clean-scripts", "bower-restore"], function () {
return gulp.src(config.bootstrapsrc)
.pipe(concat("bootstrap-bundle.js"))
.pipe(gulp.dest("lib"));
});
// Combine and the vendor files from bower into bundles (output to the Scripts folder)
gulp.task("bundle-scripts", ["jquery-bundle", "ng-bundle", "bootstrap-bundle"], function () {
});
//Restore all bower packages
gulp.task("bower-restore", function () {
return bower();
});
//build lib scripts
gulp.task("compile-lib", ["bundle-scripts"], function () {
return gulp.src("lib/*.js")
.pipe(sourcemaps.init())
.pipe(concat("compiled-bundle.js"))
.pipe(gulp.dest("dist"))
.pipe(rename("compiled-bundle.min.js"))
.pipe(uglify())
.pipe(sourcemaps.write("./"))
.pipe(gulp.dest("dist"));
});
It's a mechanism to invoke an API in an asynchrounous way. The sequence is the following
So you can invoke the api and tell your user the request is "processing" or "acquired" for example, and then update the status when you receive the response from the api.
Hope it makes sense. -G
Use input
tag with accept
attribute
<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />
Click here for the latest browser compatibility table
Live demo here
To select only image files, you can use this accept="image/*"
<input type="file" name="my-image" id="image" accept="image/*" />
Live demo here
Only gif, jpg and png will be shown, screen grab from Chrome version 44
Somewhat late to the party - I was doing something similar and needed some pointers and ended up here. Taking no credit - I took all of the code from Brice but got the "zero interactions" than Cengiz got.
Using guidance from what jheriks amd Joseph Lust had put I think I know why - I had my object under test as a field and newed it up in a @Before unlike Brice. Then the actual logger was not the mock but a real class init'd as jhriks suggested...
I would normally do this for my object under test so as to get a fresh object for each test. When I moved the field to a local and newed it in the test it ran ok. However, if I tried a second test it was not the mock in my test but the mock from the first test and I got the zero interactions again.
When I put the creation of the mock in the @BeforeClass the logger in the object under test is always the mock but see the note below for the problems with this...
Class under test
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MyClassWithSomeLogging {
private static final Logger LOG = LoggerFactory.getLogger(MyClassWithSomeLogging.class);
public void doStuff(boolean b) {
if(b) {
LOG.info("true");
} else {
LOG.info("false");
}
}
}
Test
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.mockito.Mockito.*;
import static org.powermock.api.mockito.PowerMockito.mock;
import static org.powermock.api.mockito.PowerMockito.*;
import static org.powermock.api.mockito.PowerMockito.when;
@RunWith(PowerMockRunner.class)
@PrepareForTest({LoggerFactory.class})
public class MyClassWithSomeLoggingTest {
private static Logger mockLOG;
@BeforeClass
public static void setup() {
mockStatic(LoggerFactory.class);
mockLOG = mock(Logger.class);
when(LoggerFactory.getLogger(any(Class.class))).thenReturn(mockLOG);
}
@Test
public void testIt() {
MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
myClassWithSomeLogging.doStuff(true);
verify(mockLOG, times(1)).info("true");
}
@Test
public void testIt2() {
MyClassWithSomeLogging myClassWithSomeLogging = new MyClassWithSomeLogging();
myClassWithSomeLogging.doStuff(false);
verify(mockLOG, times(1)).info("false");
}
@AfterClass
public static void verifyStatic() {
verify(mockLOG, times(1)).info("true");
verify(mockLOG, times(1)).info("false");
verify(mockLOG, times(2)).info(anyString());
}
}
Note
If you have two tests with the same expectation I had to do the verify in the @AfterClass as the invocations on the static are stacked up - verify(mockLOG, times(2)).info("true");
- rather than times(1) in each test as the second test would fail saying there where 2 invocation of this. This is pretty pants but I couldn't find a way to clear the invocations. I'd like to know if anyone can think of a way round this....
You could use location.go(url)
which will basically change your url, without change in route of application.
NOTE this could cause other effect like redirect to child route from the current route.
Related question which describes location.go
will not intimate to Router
to happen changes.
Update to Justin answer above. if you want to use it using Data Annotation in MVC you can do as follow
[RegularExpression(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,15}$", ErrorMessage = "Password must be between 6 and 20 characters and contain one uppercase letter, one lowercase letter, one digit and one special character.")]
Changing the 'w' (write) in this line:
output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)
To 'wb' (write binary) fixed this problem for me:
output = csv.DictWriter(open('file3.csv','wb'), delimiter=',', fieldnames=headers)
Credit to @dandrejvv for the solution in the comment on the original post above.
If you get could not copy and permissions are right disable selinux.
Check if selinux is enabled.
$ adb shell
$su
# getenforce
Enforcing
Selinux is enabled and blocking/enforcing. Disable selinux
# setenforce 0
do your stuff and set selinux to enforcing.
# setenforce 1
..extending Mikaels' answers
SELECT
CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
...
e0
fixes some ISNUMERIC issues (such as +
-
.
and empty string being accepted)in my case this fixed the problem:
sudo apt-get install libssl-dev libcurl4-openssl-dev python-dev
as explained here
This is the combo I'm using to backup, drop, create and restore my database (on macOS and Linux):
sudo -u postgres pg_dump -Fc mydb > ./mydb.sql
sudo -u postgres dropdb mydb
sudo -u postgres createdb -O db_user mydb
sudo -u postgres pg_restore -d mydb < ./mydb.sql
-Fc
will compress the database (format custom)sudo -u postgres psql -c "\du+"
./mydb.sql
, then change it by:
./`hostname`_mydb_`date +"%Y%m%d_%H%M"`.sql
SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.
SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.
Some useful links can be found below:
Disclosure: I am the tech lead on the SciChart project!
Try using rowMeans
:
z$mean=rowMeans(z[,c("x", "y")], na.rm=TRUE)
w x y mean
1 5 1 1 1
2 6 2 2 2
3 7 3 3 3
4 8 4 NA 4
Here is a much simpler solution:
function MyControl($scope){_x000D_
$scope.values = ["a","b","c","d","e","f"];_x000D_
$scope.selectedIndex = -1;_x000D_
_x000D_
$scope.toggleSelect = function(ind){_x000D_
if( ind === $scope.selectedIndex ){_x000D_
$scope.selectedIndex = -1;_x000D_
} else{_x000D_
$scope.selectedIndex = ind;_x000D_
}_x000D_
}_x000D_
_x000D_
$scope.getClass = function(ind){_x000D_
if( ind === $scope.selectedIndex ){_x000D_
return "selected";_x000D_
} else{_x000D_
return "";_x000D_
}_x000D_
}_x000D_
_x000D_
$scope.getButtonLabel = function(ind){_x000D_
if( ind === $scope.selectedIndex ){_x000D_
return "Deselect";_x000D_
} else{_x000D_
return "Select";_x000D_
}_x000D_
}_x000D_
}
_x000D_
.selected {_x000D_
color:red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.1/angular.min.js"></script>_x000D_
<div ng-app ng-controller="MyControl">_x000D_
<ul>_x000D_
<li ng-class="getClass($index)" ng-repeat="value in values" >{{value}} <button ng-click="toggleSelect($index)">{{getButtonLabel($index)}}</button></li>_x000D_
</ul>_x000D_
<p>Selected: {{selectedIndex}}</p>_x000D_
</div>
_x000D_
When I remove AnnotationConfigWebApplicationContext context param from web.xml file This is work
If you have got like param which as shown below you must remove it from web.xml file
<context-param>
<param-name>contextClass</param-name>
<param-value>
org.springframework.web.context.support.AnnotationConfigWebApplicationContext
</param-value>
</context-param>
You need to :
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
Then :
dataGridView1.ColumnHeadersHeight = 60;
Okay, so if later on down the line the issue is that you have a query that's greater than the allowable size (which may happen if it keeps growing) you're going to have to break it into chunks and execute the string values. So, let's say you have a stored procedure like the following:
CREATE PROCEDURE ExecuteMyHugeQuery
@SQL VARCHAR(MAX) -- 2GB size limit as stated by Martin Smith
AS
BEGIN
-- Now, if the length is greater than some arbitrary value
-- Let's say 2000 for this example
-- Let's chunk it
-- Let's also assume we won't allow anything larger than 8000 total
DECLARE @len INT
SELECT @len = LEN(@SQL)
IF (@len > 8000)
BEGIN
RAISERROR ('The query cannot be larger than 8000 characters total.',
16,
1);
END
-- Let's declare our possible chunks
DECLARE @Chunk1 VARCHAR(2000),
@Chunk2 VARCHAR(2000),
@Chunk3 VARCHAR(2000),
@Chunk4 VARCHAR(2000)
SELECT @Chunk1 = '',
@Chunk2 = '',
@Chunk3 = '',
@Chunk4 = ''
IF (@len > 2000)
BEGIN
-- Let's set the right chunks
-- We already know we need two chunks so let's set the first
SELECT @Chunk1 = SUBSTRING(@SQL, 1, 2000)
-- Let's see if we need three chunks
IF (@len > 4000)
BEGIN
SELECT @Chunk2 = SUBSTRING(@SQL, 2001, 2000)
-- Let's see if we need four chunks
IF (@len > 6000)
BEGIN
SELECT @Chunk3 = SUBSTRING(@SQL, 4001, 2000)
SELECT @Chunk4 = SUBSTRING(@SQL, 6001, (@len - 6001))
END
ELSE
BEGIN
SELECT @Chunk3 = SUBSTRING(@SQL, 4001, (@len - 4001))
END
END
ELSE
BEGIN
SELECT @Chunk2 = SUBSTRING(@SQL, 2001, (@len - 2001))
END
END
-- Alright, now that we've broken it down, let's execute it
EXEC (@Chunk1 + @Chunk2 + @Chunk3 + @Chunk4)
END
I'm using Rails 4.2, and could not get the footable icons to show up. Little boxes were showing, instead of the (+) on collapsed rows and the little sorting arrows I expected. After studying the information here, I made one simple change to my code: remove the font directory in css. That is, change all the css entries like this:
src:url('fonts/footable.eot');
to look like this:
src:url('footable.eot');
It worked. I think Rails 4.2 already assumes the font directory, so specifying it again in the css code makes the font files not get found. Hope this helps.
JPanel jPanel = new JPanel();
jPanel.setBorder(BorderFactory.createLineBorder(Color.black));
Here not only jPanel, you can add border to any Jcomponent
You can change this in your CSS with the property padding
:
.navbar-nav > li{
padding-left:30px;
padding-right:30px;
}
Also you can set margin
.navbar-nav > li{
margin-left:30px;
margin-right:30px;
}
You can store favourites with no associated menu in a separate table:
CREATE TABLE FavoriteWithoutMenu
(
FavoriteWithoutMenuId uuid NOT NULL, --Primary key
UserId uuid NOT NULL,
RecipeId uuid NOT NULL,
UNIQUE KEY (UserId, RecipeId)
)
I faced similar issue. My controller name was documents. It manages uploaded documents. It was working fine and started showing this error after completion of code. The mistake I did is - Created a folder 'Documents' to save the uploaded files. So controller name and folder name were same - which made the issue.
This worked for me with a string-array named shoes
loaded from the projects resources:
Spinner spinnerCountShoes = (Spinner)findViewById(R.id.spinner_countshoes);
ArrayAdapter<String> spinnerCountShoesArrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.shoes));
spinnerCountShoes.setAdapter(spinnerCountShoesArrayAdapter);
This is my resource file (res/values/arrays.xml
) with the string-array named shoes
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="shoes">
<item>0</item>
<item>5</item>
<item>10</item>
<item>100</item>
<item>1000</item>
<item>10000</item>
</string-array>
</resources>
With this method it's easier to make it multilingual (if necessary).
Code that works for both IDE's and .jar files:
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import java.util.stream.*;
public class ResourceWalker {
public static void main(String[] args) throws URISyntaxException, IOException {
URI uri = ResourceWalker.class.getResource("/resources").toURI();
Path myPath;
if (uri.getScheme().equals("jar")) {
FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap());
myPath = fileSystem.getPath("/resources");
} else {
myPath = Paths.get(uri);
}
Stream<Path> walk = Files.walk(myPath, 1);
for (Iterator<Path> it = walk.iterator(); it.hasNext();){
System.out.println(it.next());
}
}
}
you can just do
select rownum, l.* from student l where name like %ram%
this assigns the row number as the rows are fetched (so no guaranteed ordering of course).
if you wanted to order first do:
select rownum, l.*
from (select * from student l where name like %ram% order by...) l;
The free Tamper Data Firefox extension is pretty good. Allows you to view, filter and modify all requests.
I made a simple (stupid or not) bash script, that extracts the longs from the adb shell, converts them to timestamps and shows it in red.
echo "Please set a search filter"
read search
adb shell dumpsys alarm | grep $search | (while read i; do echo $i; _DT=$(echo $i | grep -Eo 'when\s+([0-9]{10})' | tr -d '[[:alpha:][:space:]]'); if [ $_DT ]; then echo -e "\e[31m$(date -d @$_DT)\e[0m"; fi; done;)
try it ;)
uname -av;
sudo apt install --reinstall (output from uname -av)
If you see this message in Debug from Visual Studio and solution contains WCF project. Then open this WCF project settings -> go to "WCF Options" tab -> off "Start WCF Service Host when debugging..." option
As error message said your application has no permissions to read from the directory. It can be the case when you created the directory as one user and run script as another user.
A modified version of @nickf code:
function addhttp($url) {
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
$url = "http://" . $url;
}
return $url;
}
Recognizes ftp://
, ftps://
, http://
and https://
in a case insensitive way.
<h1> left <span> right </span></h1>
css:
h1{text-align:left; width:400px; text-decoration:underline;}
span{float:right; text-decoration:underline;}
Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:
.container {_x000D_
border: 1px solid #DDDDDD;_x000D_
width: 200px;_x000D_
height: 200px;_x000D_
position: relative;_x000D_
}_x000D_
.tag {_x000D_
float: left;_x000D_
position: absolute;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
z-index: 1000;_x000D_
background-color: #92AD40;_x000D_
padding: 5px;_x000D_
color: #FFFFFF;_x000D_
font-weight: bold;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="tag">Featured</div>_x000D_
<img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
The key is the container has to be positioned relative and the tag positioned absolute.
In Python string literals, backslash is an escape character. This is also true when the interactive prompt shows you the value of a string. It will give you the literal code representation of the string. Use the print
statement to see what the string actually looks like.
This example shows the difference:
>>> '\\'
'\\'
>>> print '\\'
\
For Windows host, you can :
Be warned, each time the file is opened with this method the old data in the file is destroyed regardless of 'w+' or just 'w'.
import os
with open("file.txt", 'w+') as f:
f.write("file is opened for business")
Use the function to clear cookies:
function clearCookies($clearSession = false)
{
$past = time() - 3600;
if ($clearSession === false)
$sessionId = session_id();
foreach ($_COOKIE as $key => $value)
{
if ($clearSession !== false || $value !== $sessionId)
setcookie($key, $value, $past, '/');
}
}
If you pass true
then it clears session
data, otherwise session data is preserved.
Just for an additional reference.
All of the above answers will work in case of a data frame. But if you are using lambda while creating / modify a column this won't work, Because there it is considered as a int attribute instead of pandas series. You have to use str( target_attribute ) to make it as a string. Please refer the below example.
def add_zero_in_prefix(df):
if(df['Hour']<10):
return '0' + str(df['Hour'])
data['str_hr'] = data.apply(add_zero_in_prefix, axis=1)
And there exists no reliable function for it. Consider for example this filename:
archive.tar.gz
What is the extension? DOS users would have preferred the name archive.tgz
. Sometimes you see stupid Windows applications that first decompress the file (yielding a .tar
file), then you have to open it again to see the archive contents.
In this case, a more reasonable notion of file extension would have been .tar.gz
. There are also .tar.bz2
, .tar.xz
, .tar.lz
and .tar.lzma
file "extensions" in use. But how would you decide, whether to split at the last dot, or the second-to-last dot?
The Java 7 function Files.probeContentType will likely be much more reliable to detect file types than trusting the file extension. Pretty much all the Unix/Linux world as well as your Webbrowser and Smartphone already does it this way.
In order for that to work $time
has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00');
which is what you seem to do, because then I get 0:30 and 1:30 as results too.
Try
$time = strtotime('10:00');
As an alternative, consider using DateTime (the below requires PHP 5.3 though):
$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M')); // substract 30 minutes
echo $dt->format('H:i'); // echo modified time
$dt->add(new DateInterval('PT1H')); // add 1 hour
echo $dt->format('H:i'); // echo modified time
or procedural if you don't like OOP
$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');
I've solved this problem in this way.
String dateUTC = rs.getString("date"); //UTC
DateTime date;
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS").withZoneUTC();
date = dateTimeFormatter.parseDateTime(dateUTC);
In this way you ignore the server TimeZone forcing your chosen TimeZone.
The simplest answer is what Paul H said:
d = []
for p in game.players.passing():
d.append(
{
'Player': p,
'Team': p.team,
'Passer Rating': p.passer_rating()
}
)
pd.DataFrame(d)
But if you really want to "build and fill a dataframe from a loop", (which, btw, I wouldn't recommend), here's how you'd do it.
d = pd.DataFrame()
for p in game.players.passing():
temp = pd.DataFrame(
{
'Player': p,
'Team': p.team,
'Passer Rating': p.passer_rating()
}
)
d = pd.concat([d, temp])
You could create a color using the static FromArgb method:
Color redColor = Color.FromArgb(255, 0, 0);
You can also specify the alpha using the following overload.
I recommend you to use JSON.NET
. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...
Serialization Example:
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);
Performance Comparison To Other JSON serializiation Techniques
You can use a DOM XML parser to create an XML file using Java. A good example can be found on this site:
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
//root elements
Document doc = docBuilder.newDocument();
Element rootElement = doc.createElement("company");
doc.appendChild(rootElement);
//staff elements
Element staff = doc.createElement("Staff");
rootElement.appendChild(staff);
//set attribute to staff element
Attr attr = doc.createAttribute("id");
attr.setValue("1");
staff.setAttributeNode(attr);
//shorten way
//staff.setAttribute("id", "1");
//firstname elements
Element firstname = doc.createElement("firstname");
firstname.appendChild(doc.createTextNode("yong"));
staff.appendChild(firstname);
//lastname elements
Element lastname = doc.createElement("lastname");
lastname.appendChild(doc.createTextNode("mook kim"));
staff.appendChild(lastname);
//nickname elements
Element nickname = doc.createElement("nickname");
nickname.appendChild(doc.createTextNode("mkyong"));
staff.appendChild(nickname);
//salary elements
Element salary = doc.createElement("salary");
salary.appendChild(doc.createTextNode("100000"));
staff.appendChild(salary);
//write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\testing.xml"));
transformer.transform(source, result);
System.out.println("Done");
}catch(ParserConfigurationException pce){
pce.printStackTrace();
}catch(TransformerException tfe){
tfe.printStackTrace();
}
To create these constraints through the GUI you need the "indexes and keys" dialogue not the check constraints one.
But in your case you just need to run the piece of code you already have. It doesn't need to be entered into the expression dialogue at all.
To avoid this warning, do not use:
async: false
in any of your $.ajax() calls. This is the only feature of XMLHttpRequest that's deprecated.
The default is
async: true
Just as an alternative to the '[ -d ]' and '[ -h ]' options, you can make use of stat
to obtain the file type and parse it.
#! /bin/bash
MY_DIR=$1
NODE_TYPE=$(stat -c '%F' ${MY_DIR} 2>/dev/null)
case "${NODE_TYPE}" in
"directory") echo $MY_DIR;;
"symbolic link") echo $(readlink $MY_DIR);;
"") echo "$MY_DIR does not exist";;
*) echo "$NODE_TYPE is unsupported";;
esac
exit 0
Test data:
$ mkdir tmp
$ ln -s tmp derp
$ touch a.txt
$ ./dir.sh tmp
tmp
$ ./dir.sh derp
tmp
$ ./dir.sh a.txt
regular file is unsupported
$ ./dir.sh god
god does not exist
You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,
float arr1[10] = { }; // all elements are 0
float arr2[10] = { 0 }; // all elements are 0
float arr3[10] = { 1 }; // first element is 1, all others are 0
float arr4[10] = { 1, 2 }; // first element is 1, second is 2, all others are 0
In case you are calculating more than one moving average:
for i in range(2,10):
df['MA{}'.format(i)] = df.rolling(window=i).mean()
Then you can do an aggregate average of all the MA
df[[f for f in list(df) if "MA" in f]].mean(axis=1)
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2:Win32_Process")
objWMIService.Create "notepad.exe", null, null, intProcessID
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colMonitoredProcesses = objWMIService.ExecNotificationQuery _
("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process'")
Do Until i = 1
Set objLatestProcess = colMonitoredProcesses.NextEvent
If objLatestProcess.TargetInstance.ProcessID = intProcessID Then
i = 1
End If
Loop
Wscript.Echo "Notepad has been terminated."
String.prototype.replaceArray = function (find, replace) {
var replaceString = this;
for (var i = 0; i < find.length; i++) {
// global replacement
var pos = replaceString.indexOf(find[i]);
while (pos > -1) {
replaceString = replaceString.replace(find[i], replace[i]);
pos = replaceString.indexOf(find[i]);
}
}
return replaceString;
};
var textT = "Hello world,,,,, hello people.....";
var find = [".",","];
var replace = ['2', '5'];
textT = textT.replaceArray(find, replace);
// result: Hello world55555 hello people22222
You never give any value to your strings in main
so they are empty, and thus obviously the function returns an empty string.
Replace:
string str1, str2, str3;
with:
string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";
Also, you have several problems in your replaceSubstring
function:
int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
std::string::find
returns a std::string::size_type
(aka. size_t
) not an int
. Two differences: size_t
is unsigned, and it's not necessarily the same size as an int
depending on your platform (eg. on 64 bits Linux or Windows size_t
is unsigned 64 bits while int
is signed 32 bits).s2
is not part of s1
? I'll leave it up to you to find how to fix that. Hint: std::string::npos
;)To use Redux-saga is the best middleware in React-redux implementation.
Ex: store.js
import createSagaMiddleware from 'redux-saga';
import { createStore, applyMiddleware } from 'redux';
import allReducer from '../reducer/allReducer';
import rootSaga from '../saga';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
allReducer,
applyMiddleware(sagaMiddleware)
)
sagaMiddleware.run(rootSaga);
export default store;
And then saga.js
import {takeLatest,delay} from 'redux-saga';
import {call, put, take, select} from 'redux-saga/effects';
import { push } from 'react-router-redux';
import data from './data.json';
export function* updateLesson(){
try{
yield put({type:'INITIAL_DATA',payload:data}) // initial data from json
yield* takeLatest('UPDATE_DETAIL',updateDetail) // listen to your action.js
}
catch(e){
console.log("error",e)
}
}
export function* updateDetail(action) {
try{
//To write store update details
}
catch(e){
console.log("error",e)
}
}
export default function* rootSaga(){
yield [
updateLesson()
]
}
And then action.js
export default function updateFruit(props,fruit) {
return (
{
type:"UPDATE_DETAIL",
payload:fruit,
props:props
}
)
}
And then reducer.js
import {combineReducers} from 'redux';
const fetchInitialData = (state=[],action) => {
switch(action.type){
case "INITIAL_DATA":
return ({type:action.type, payload:action.payload});
break;
}
return state;
}
const updateDetailsData = (state=[],action) => {
switch(action.type){
case "INITIAL_DATA":
return ({type:action.type, payload:action.payload});
break;
}
return state;
}
const allReducers =combineReducers({
data:fetchInitialData,
updateDetailsData
})
export default allReducers;
And then main.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/components/App.jsx';
import {Provider} from 'react-redux';
import store from './app/store';
import createRoutes from './app/routes';
const initialState = {};
const store = configureStore(initialState, browserHistory);
ReactDOM.render(
<Provider store={store}>
<App /> /*is your Component*/
</Provider>,
document.getElementById('app'));
try this.. is working
For Spring 4, using Spring Boot we can have the following example without using the anti-pattern of getting the Bean from the ApplicationContext directly:
package com.yourproject;
@SpringBootApplication
public class TestBed implements CommandLineRunner {
private MyService myService;
@Autowired
public TestBed(MyService myService){
this.myService = myService;
}
public static void main(String... args) {
SpringApplication.run(TestBed.class, args);
}
@Override
public void run(String... strings) throws Exception {
System.out.println("myService: " + MyService );
}
}
@Service
public class MyService{
public String getSomething() {
return "something";
}
}
Make sure that all your injected services are under com.yourproject
or its subpackages.
I'm using xampp and my problem was fixed once i rename:
extension_dir = "ext"
to
extension_dir = "C:\xampp\php\ext"
PS: Don't forget to restart apache after making this change!
There are many ways to filter for element ancestors.
if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/}
Beware, closest()
method includes element itself while checking for selector.
Alternatively, if you have a unique selector matching the $elem
, e.g #myElem
, you can use:
if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}
If you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:
.parentClass #myElem { /* CSS property set */ }