In the case of some programs, these errors are normal and should not be fixed.
I get these error messages when compiling the program phrap (for example). This program happens to contain code that modifies or replaces some built in functions, and when I include the appropriate header files to fix the warnings, GCC instead generates a bunch of errors. So fixing the warnings effectively breaks the build.
If you got the source as part of a distribution that should compile normally, the errors might be normal. Consult the documentation to be sure.
In MSVC to suppress a particular warning it is enough to specify the it's number to compiler as /wd#. My CMakeLists.txt contains such the block:
If (MSVC)
Set (CMAKE_EXE_LINKER_FLAGS "$ {CMAKE_EXE_LINKER_FLAGS} / NODEFAULTLIB: LIBCMT")
Add_definitions (/W4 /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127)
Add_definitions (/D_CRT_SECURE_NO_WARNINGS)
Elseif (CMAKE_COMPILER_IS_GNUCXX OR CMAKE_COMPILER_IS_GNUC)
Add_definitions (-Wall -W -pedantic)
Else ()
Message ("Unknown compiler")
Endif ()
Now I can not say what exactly /wd4512 /wd4702 /wd4100 /wd4510 /wd4355 /wd4127 mean, because I do not pay any attention to MSVC for three years, but they suppress superpedantic warnings that does not influence the result.
This works well but requires C++11
template <typename ...Args>
void unused(Args&& ...args)
{
(void)(sizeof...(args));
}
I just used =COUNTIF(Range, "<>")
and it counted non-empty cells for me.
My workaround in ASP.NET (pagemethods, webservice, etc.)
protected void Application_BeginRequest(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
You can also use:
.rhead {
width:300px;
}
but this will only with with some browsers, if I remember correctly IE8 does not allow this. Over all, It is safer to just put the width=""
attribute in the <td>
itself.
If you are using java technology(Servlet/JSP) for making web application you will probably use Apache Tomcat. However, if you are using other technologies like Perl, PHP or ruby, its better(easier) to use Apache HTTP Server.
I suspect you meant:
axis.Date(1, as.Date(sites$date, origin = "1970-01-01"))
as the 'x' argument to as.Date()
has to be of type Date
.
As an aside, this would have appropriate as a follow-up or edit of your previous question.
My approach to this would be to use async generators.
Assuming you have an array of questions:
const questions = [
"How are you today ?",
"What are you working on ?",
"What do you think of async generators ?",
]
In order to use the await
keyword, you must wrap your program into an async IIFE.
(async () => {
questions[Symbol.asyncIterator] = async function * () {
const stdin = process.openStdin()
for (const q of this) {
// The promise won't be solved until you type something
const res = await new Promise((resolve, reject) => {
console.log(q)
stdin.addListener('data', data => {
resolve(data.toString())
reject('err')
});
})
yield [q, res];
}
};
for await (const res of questions) {
console.log(res)
}
process.exit(0)
})();
Expected results:
How are you today ?
good
[ 'How are you today ?', 'good\n' ]
What are you working on ?
:)
[ 'What are you working on ?', ':)\n' ]
What do you think about async generators ?
awesome
[ 'What do you think about async generators ?', 'awesome\n' ]
If you want to get questions an answers altogether, you can achieve this with a simple modification:
const questionsAndAnswers = [];
for await (const res of questions) {
// console.log(res)
questionsAndAnswers.push(res)
}
console.log(questionsAndAnswers)
/*
[ [ 'How are you today ?', 'good\n' ],
[ 'What are you working on ?', ':)\n' ],
[ 'What do you think about async generators ?', 'awesome\n' ] ]
*/
With marquee
tag.
HTML
<marquee behavior="scroll" bgcolor="yellow" loop="-1" width="30%">
<i>
<font color="blue">
Today's date is :
<strong>
<span id="time"></span>
</strong>
</font>
</i>
</marquee>
JS
var today = new Date();
document.getElementById('time').innerHTML=today;
Without marquee
tag and with CSS
.
HTML
<p class="marquee">
<span id="dtText"></span>
</p>
CSS
.marquee {
width: 350px;
margin: 0 auto;
background:yellow;
white-space: nowrap;
overflow: hidden;
box-sizing: border-box;
color:blue;
font-size:18px;
}
.marquee span {
display: inline-block;
padding-left: 100%;
text-indent: 0;
animation: marquee 15s linear infinite;
}
.marquee span:hover {
animation-play-state: paused
}
@keyframes marquee {
0% { transform: translate(0, 0); }
100% { transform: translate(-100%, 0); }
}
JS
var today = new Date();
document.getElementById('dtText').innerHTML=today;
In Bash 5 there's a new variable:
echo $EPOCHSECONDS
Or if you want higher precision (in microseconds):
echo $EPOCHREALTIME
Use the -File
parameter in front of the filename. The quotes make PowerShell think it is a string of commands.
jQuery needs to be the first script you import. The first script on your page
<script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>
appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.
int arr[20] = {0};
C99 [$6.7.8/21]
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
Use onChange={this.handleChange.bind(this, "name")
method and value={this.state.fields["name"]}
on input text field and below that create span element to show error, see the below example.
export default class Form extends Component {
constructor(){
super()
this.state ={
fields: {
name:'',
email: '',
message: ''
},
errors: {},
disabled : false
}
}
handleValidation(){
let fields = this.state.fields;
let errors = {};
let formIsValid = true;
if(!fields["name"]){
formIsValid = false;
errors["name"] = "Name field cannot be empty";
}
if(typeof fields["name"] !== "undefined" && !fields["name"] === false){
if(!fields["name"].match(/^[a-zA-Z]+$/)){
formIsValid = false;
errors["name"] = "Only letters";
}
}
if(!fields["email"]){
formIsValid = false;
errors["email"] = "Email field cannot be empty";
}
if(typeof fields["email"] !== "undefined" && !fields["email"] === false){
let lastAtPos = fields["email"].lastIndexOf('@');
let lastDotPos = fields["email"].lastIndexOf('.');
if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') === -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
formIsValid = false;
errors["email"] = "Email is not valid";
}
}
if(!fields["message"]){
formIsValid = false;
errors["message"] = " Message field cannot be empty";
}
this.setState({errors: errors});
return formIsValid;
}
handleChange(field, e){
let fields = this.state.fields;
fields[field] = e.target.value;
this.setState({fields});
}
handleSubmit(e){
e.preventDefault();
if(this.handleValidation()){
console.log('validation successful')
}else{
console.log('validation failed')
}
}
render(){
return (
<form onSubmit={this.handleSubmit.bind(this)} method="POST">
<div className="row">
<div className="col-25">
<label htmlFor="name">Name</label>
</div>
<div className="col-75">
<input type="text" placeholder="Enter Name" refs="name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
<span style={{color: "red"}}>{this.state.errors["name"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="exampleInputEmail1">Email address</label>
</div>
<div className="col-75">
<input type="email" placeholder="Enter Email" refs="email" aria-describedby="emailHelp" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
<span style={{color: "red"}}>{this.state.errors["email"]}</span>
</div>
</div>
<div className="row">
<div className="col-25">
<label htmlFor="message">Message</label>
</div>
<div className="col-75">
<textarea type="text" placeholder="Enter Message" rows="5" refs="message" onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]}></textarea>
<span style={{color: "red"}}>{this.state.errors["message"]}</span>
</div>
</div>
<div className="row">
<button type="submit" disabled={this.state.disabled}>{this.state.disabled ? 'Sending...' : 'Send'}</button>
</div>
</form>
)
}
}
char[] characters;
...
string s = new string(characters);
For python 3.3
from datetime import datetime, timedelta
futuredate = datetime.now() + timedelta(days=10)
Read : 101 LINQ Samples in that LINQ - Grouping Operators from Microsoft MSDN site
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
forsingle object make use of stringbuilder and append it that will do or convert this in form of dictionary
// fordictionary
var x = (from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() })
.ToDictionary( t => t.type, t => t.count);
//for stringbuilder not sure for this
var x = from t in types group t by t.Type
into grp
select new { type = grp.key, count = grp.Count() };
StringBuilder MyStringBuilder = new StringBuilder();
foreach (var res in x)
{
//: is separator between to object
MyStringBuilder.Append(result.Type +" , "+ result.Count + " : ");
}
Console.WriteLine(MyStringBuilder.ToString());
try to use unix4j. it s about a library in java to run linux command. for instance if you got a command like: cat test.txt | grep "Tuesday" | sed "s/kilogram/kg/g" | sort in this program will become: Unix4j.cat("test.txt").grep("Tuesday").sed("s/kilogram/kg/g").sort();
If you are using NASM, the command-line is just
nasm -felf32 -g -Fdwarf file.asm -o file.o
where 'file.asm' is your assembly file (code) and 'file.o' is an object file you can link with gcc -m32
or ld -melf_i386
. (Assembling with nasm -felf64
will make a 64-bit object file, but the hello world example below uses 32-bit system calls, and won't work in a PIE executable.)
Here is some more info:
http://www.nasm.us/doc/nasmdoc2.html#section-2.1
You can install NASM in Ubuntu with the following command:
apt-get install nasm
Here is a basic Hello World in Linux assembly to whet your appetite:
http://web.archive.org/web/20120822144129/http://www.cin.ufpe.br/~if817/arquivos/asmtut/index.html
I hope this is what you were asking...
Because you defined the struct
as consisting of char
arrays, the two strings are the structure and freeing the struct
is sufficient, nor is there a way to free the struct
but keep the arrays. For that case you would want to do something like struct { char *firstName, *lastName; }
, but then you need to allocate memory for the names separately and handle the question of when to free that memory.
Aside: Is there a reason you want to keep the names after the struct
has been freed?
I ran into same issue when running:
$ /Users/<username>/Library/Android/sdk/tools/bin/sdkmanager "platforms;android-28" "build-tools;28.0.3"_
I solved it as
$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk-11.0.1.jdk/Contents/Home
$ ls /Library/Java/JavaVirtualMachines/
jdk-11.0.1.jdk
jdk1.8.0_202.jdk
Change Java to use 1.8
$ export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_202.jdk/Contents/Home'
Then the same command runs fine
$ /Users/<username>/Library/Android/sdk/tools/bin/sdkmanager "platforms;android-28" "build-tools;28.0.3"
After looking at all solutions, I realised there is a much simpler solution.
In your activity's onBackPressed() that is hosting all your fragments, find the fragment that you want to prevent back press. Then if found, just return. Then popBackStack will never happen for this fragment.
@Override
public void onBackPressed() {
Fragment1 fragment1 = (Fragment1) getFragmentManager().findFragmentByTag(“Fragment1”);
if (fragment1 != null)
return;
if (getFragmentManager().getBackStackEntryCount() > 0){
getFragmentManager().popBackStack();
}
}
If you want to extract from a
tag then
$('.dep_buttons').text().substr(0,25)
With the mouseover event,
$(this).text($(this).text().substr(0, 25));
The above will extract the text of a tag, then extract again assign it back.
Check if the Browser is IE -
$ua = htmlentities($_SERVER['HTTP_USER_AGENT'], ENT_QUOTES, 'UTF-8');
if (preg_match('~MSIE|Internet Explorer~i', $ua) || (strpos($ua, 'Trident/7.0') !== false && strpos($ua, 'rv:11.0') !== false)) {
// do stuff for IE Here
}
It is also worth to mention, that if you DO NOT intent to modify the values of the list, it is possible (and better) to use the const_iterator
, as follows:
for (std::list<Student>::const_iterator it = data.begin(); it != data.end(); ++it){
// do whatever you wish but don't modify the list elements
std::cout << it->name;
}
Here is a version that works well in September 2020 using fetch and https://worldtimeapi.org/api
fetch("https://worldtimeapi.org/api/ip")
.then(response => response.json())
.then(data => console.log(data.dst,data.datetime));
_x000D_
In some cases, DateTime.MinValue
(or equivalenly, default(DateTime)
) is used to indicate an unknown value.
This simple extension method can help handle such situations:
public static class DbDateHelper
{
/// <summary>
/// Replaces any date before 01.01.1753 with a Nullable of
/// DateTime with a value of null.
/// </summary>
/// <param name="date">Date to check</param>
/// <returns>Input date if valid in the DB, or Null if date is
/// too early to be DB compatible.</returns>
public static DateTime? ToNullIfTooEarlyForDb(this DateTime date)
{
return (date >= (DateTime) SqlDateTime.MinValue) ? date : (DateTime?)null;
}
}
Usage:
DateTime? dateToPassOnToDb = tooEarlyDate.ToNullIfTooEarlyForDb();
If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object
Ex:
import each from 'foreach-object';
const object = {
firstName: 'Arosha',
lastName: 'Sum',
country: 'Australia'
};
each(object, (value, key, object) => {
console.log(key + ': ' + value);
});
// Console log output will be:
// firstName: Arosha
// lastName: Sum
// country: Australia
I found out I made a mistake. There's no need to call toObject() or toJSON() at all. The __proto__ in the question came from jquery, not mongoose. Here's my test:
UserModel.find({}, function (err, users) {
console.log(users.save); // { [Function] numAsyncPres: 0 }
var json = JSON.stringify(users);
users = users.map(function (user) {
return user.toObject();
}
console.log(user.save); // undefined
console.log(json == JSON.stringify(users)); // true
}
doc.toObject() removes doc.prototype from a doc. But it makes no difference in JSON.stringify(doc). And it's not needed in this case.
Basically it's a script that is launched before unversioned property is modified on the repository, so that you can manage more precisely what's happening on your repository.
There are templates in the SVN distrib for different hooks, located in the /hooks subdirectory (*.tmpl that you have to edit and rename depending on your OS, to activate).
Your second DELETE
query was nearly correct. Just be sure to put the table name (or an alias) between DELETE
and FROM
to specify which table you are deleting from. This is simpler than using a nested SELECT
statement like in the other answers.
DELETE tableA
FROM tableA
INNER JOIN tableB u on (u.qlabel = tableA.entityrole AND u.fieldnum = tableA.fieldnum)
WHERE (LENGTH(tableA.memotext) NOT IN (8,9,10)
OR tableA.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
DELETE q
FROM tableA q
INNER JOIN tableB u on (u.qlabel = q.entityrole AND u.fieldnum = q.fieldnum)
WHERE (LENGTH(q.memotext) NOT IN (8,9,10)
OR q.memotext NOT LIKE '%/%/%')
AND (u.FldFormat = 'Date')
More examples here:
How to Delete using INNER JOIN with SQL Server?
How about doing this in a much more elegant way with nodejs-config module.
This module is able to set configuration environment based on your computer's name. After that when you request a configuration you will get environment specific value.
For example lets assume your have two development machines named pc1 and pc2 and a production machine named pc3. When ever you request configuration values in your code in pc1 or pc2 you must get "development" environment configuration and in pc3 you must get "production" environment configuration. This can be achieved like this:
Now create new config instance with following syntax.
var config = require('nodejs-config')(
__dirname, // an absolute path to your applications 'config' directory
{
development: ["pc1", "pc2"],
production: ["pc3"],
}
);
Now you can get any configuration value without worrying about the environment like this:
config.get('app').configurationKey;
nothing much to add,
1 - if you want to execute a query in a loop (more than 1 time), prepared statement can be faster, because of optimization that you mentioned.
2 - parameterized query is a good way to avoid SQL Injection. Parameterized querys are only available in PreparedStatement.
Both do the same work as they are used for routing purposes in SPA(Single Page Application).
URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.
HTML
<div ng-view></div>
Above tag will render the template from the $routeProvider.when()
condition which you had mentioned in .config
(configuration phase) of angular
Limitations:-
ng-view
on page$routeProvider
fails. (to achieve that, we need to use directives like ng-include
, ng-switch
, ng-if
, ng-show
, which looks bad to have them in SPA)AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.
Multiple & Named Views
Another great feature is the ability to have multiple ui-views in a template.
While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your view
s, and pairing those views with nested states.
HTML
<div ui-view>
<div ui-view='header'></div>
<div ui-view='content'></div>
<div ui-view='footer'></div>
</div>
The majority of ui-router
's power is it can manage nested state & views.
Pros
ui-view
on single pageui-view="some"
of state just by using absolute routing using @
with state name.@
to change ui-view="some"
. This will replace the ui-view
rather than checking if it is nested or not.ui-sref
to create a href
URL dynamically on the basis of URL
mentioned in a state, also you could give a state params in the json
format.For more Information Angular ui-router
For better flexibility with various nested view with states, I'd prefer you to go for ui-router
Maybe .value_counts()
?
>>> import pandas
>>> my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
>>> my_series
0 1
1 2
2 2
3 3
4 3
5 3
6 fred
7 1.8
8 1.8
>>> counts = my_series.value_counts()
>>> counts
3 3
2 2
1.8 2
fred 1
1 1
>>> len(counts)
5
>>> sum(counts)
9
>>> counts["fred"]
1
>>> dict(counts)
{1.8: 2, 2: 2, 3: 3, 1: 1, 'fred': 1}
Use DATEPART to pull apart your interval, and DATEADD to subtract the parts:
select dateadd(
hh,
-1 * datepart(hh, cast('1:15' as datetime)),
dateadd(
mi,
-1 * datepart(mi, cast('1:15' as datetime)),
'2000-01-01 08:30:00'))
or, we can convert to minutes first (though OP would prefer not to):
declare @mins int
select @mins = datepart(mi, cast('1:15' as datetime)) + 60 * datepart(hh, cast('1:15' as datetime))
select dateadd(mi, -1 * @mins, '2000-01-01 08:30:00')
No there isn't. If you watch the http traffic and dump the page source you can see that there is an API below the covers, but it's not published nor available for 3rd party apps.
Check this link: https://developers.google.com/gsuite/products for updates.
However, there is an unofficial Python API under active development: https://github.com/kiwiz/gkeepapi
There is no way to skip a check if it exists.
The value
attribute of a checkbox
is what you set by:
<input type='checkbox' name='test' value='1'>
So when someone checks that box, the server receives a variable named test
with a value
of 1
- what you want to check for is not the value
of it (which will never change, whether it is checked or not) but the checked
status of the checkbox.
So, if you replace this code:
if (arrChecks[i].value == "on")
{
arrChecks[i].checked = 1;
} else {
arrChecks[i].checked = 0;
}
With this:
arrChecks[i].checked = !arrChecks[i].checked;
It should work. You should use true
and false
instead of 0
and 1
for this.
Next multiple of 5
Consider 51 needs to be converted to 55:
code here
mark = 51;
r = 100 - mark;
a = r%5;
new_mark = mark + a;
You can pass in a pointer to a time_t
object that time will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL
, it just ignores it and merely returns a new time_t
object that represents the current time.
Nb:time(&timer);
is equivalent to timer = time(NULL);
Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:
External
option in Unity ? Preferences ? Packages ? Repository
Hidden Meta Files
in Editor ? Project Settings ? Editor ? Version Control Mode
Force Text
in Editor ? Project Settings ? Editor ? Asset Serialization Mode
File
menuNote that the only folders you need to keep under source control are Assets
and ProjectSettigns
.
More information about keeping Unity Project under source control you can find in this post.
Use dataType:"json"
for json
data
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
dataType:'json', // add json datatype to get json
data: ({name: 145}),
success: function(data){
console.log(data);
}
});
Read Docs http://api.jquery.com/jQuery.ajax/
Also in PHP
<?php
$userAnswer = $_POST['name'];
$sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
// for first row only and suppose table having data
echo json_encode($row); // pass array in json_encode
?>
Following are the ways
From the code (the way you have mentioned) ->
displayBox.Text += sent + "\r\n";
or
displayBox.Text += sent + Environment.NewLine;
From the UI
a) WPF
Set TextWrapping="Wrap" and AcceptsReturn="True"
Press Enter key to the textbox and new line will be created
b) Winform text box
Set TextBox.MultiLine and TextBox.AcceptsReturn to true
The short answer:
If you don't know what reinterpret_cast
stands for, don't use it. If you will need it in the future, you will know.
Full answer:
Let's consider basic number types.
When you convert for example int(12)
to unsigned float (12.0f)
your processor needs to invoke some calculations as both numbers has different bit representation. This is what static_cast
stands for.
On the other hand, when you call reinterpret_cast
the CPU does not invoke any calculations. It just treats a set of bits in the memory like if it had another type. So when you convert int*
to float*
with this keyword, the new value (after pointer dereferecing) has nothing to do with the old value in mathematical meaning.
Example: It is true that reinterpret_cast
is not portable because of one reason - byte order (endianness). But this is often surprisingly the best reason to use it. Let's imagine the example: you have to read binary 32bit number from file, and you know it is big endian. Your code has to be generic and works properly on big endian (e.g. some ARM) and little endian (e.g. x86) systems. So you have to check the byte order. It is well-known on compile time so you can write You can write a function to achieve this:constexpr
function:
/*constexpr*/ bool is_little_endian() {
std::uint16_t x=0x0001;
auto p = reinterpret_cast<std::uint8_t*>(&x);
return *p != 0;
}
Explanation: the binary representation of x
in memory could be 0000'0000'0000'0001
(big) or 0000'0001'0000'0000
(little endian). After reinterpret-casting the byte under p
pointer could be respectively 0000'0000
or 0000'0001
. If you use static-casting, it will always be 0000'0001
, no matter what endianness is being used.
EDIT:
In the first version I made example function is_little_endian
to be constexpr
. It compiles fine on the newest gcc (8.3.0) but the standard says it is illegal. The clang compiler refuses to compile it (which is correct).
#pragma once
is shorter than an include guard, less error prone, supported by most compilers, and some say that it compiles faster (which is not true [any longer]).
But I still suggest you go with standard #ifndef
include guards.
#ifndef
?Consider a contrived class hierarchy like this where each of the classes A
, B
, and C
lives inside its own file:
#ifndef A_H
#define A_H
class A {
public:
// some virtual functions
};
#endif
#ifndef B_H
#define B_H
#include "a.h"
class B : public A {
public:
// some functions
};
#endif
#ifndef C_H
#define C_H
#include "b.h"
class C : public B {
public:
// some functions
};
#endif
Now let's assume you are writing tests for your classes and you need to simulate the behaviour of the really complex class B
. One way to do this would be to write a mock class using for example google mock and put it inside a directory mocks/b.h
. Note, that the class name hasn't changed but it's only stored inside a different directory. But what's most important is that the include guard is named exactly the same as in the original file b.h
.
#ifndef B_H
#define B_H
#include "a.h"
#include "gmock/gmock.h"
class B : public A {
public:
// some mocks functions
MOCK_METHOD0(SomeMethod, void());
};
#endif
With this approach you can mock the behaviour of class B
without touching the original class or telling C
about it. All you have to do is put the directory mocks/
in the include path of your complier.
#pragma once
?If you would have used #pragma once
, you would get a name clash because it cannot protect you from defining the class B
twice, once the original one and once the mocked version.
I launched ubuntu Xampp server on AWS amazon. And met the same problem with FTP, even though add user to group ftp SFTP and set permissions, owner group of htdocs folder. Finally find the reason in inbound rules in security group, added All TCP, 0 - 65535 rule(0.0.0.0/0,::/0) , then working right!
If you are working with numpy you can use
import numpy as np
np.abs(-1.23)
>> 1.23
It will provide absolute values.
The Columns collection is only populated when AutoGenerateColumns=false, and you manually generate the columns yourself.
A nice work-around for this is to dynamically populate the Columns collection yourself, before setting the DataSource property and calling DataBind().
I have a function that manually adds the columns based on the contents of the DataTable that I want to display. Once I have done that (and then set the DataSource and called DataBind(), I can use the Columns collection and the Count value is correct, and I can turn the column visibility on and off as I initially wanted to.
static void AddColumnsToGridView(GridView gv, DataTable table)
{
foreach (DataColumn column in table.Columns)
{
BoundField field = new BoundField();
field.DataField = column.ColumnName;
field.HeaderText = column.ColumnName;
gv.Columns.Add(field);
}
}
The correct value for the content
attribute should include initial-scale
instead:
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
^^^^^^^^^^^^^^^
_x000D_
Assuming that your current primary key constraint is called pk_history, you can replace the following lines:
ALTER TABLE history ADD PRIMARY KEY (id)
ALTER TABLE history
DROP CONSTRAINT userId
DROP CONSTRAINT name
with these:
ALTER TABLE history DROP CONSTRAINT pk_history
ALTER TABLE history ADD CONSTRAINT pk_history PRIMARY KEY (id)
If you don't know what the name of the PK is, you can find it with the following query:
SELECT *
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE TABLE_NAME = 'history'
This example works. Try it.
var array = [0,1,2];
for( var i = 0, ii = array.length; i < ii; i++){
if(i === 1){
break;
}
}
It's best practice to hash passwords so they are not decryptable. This makes things slightly more difficult for attackers that may have gained access to your database or files.
If you must encrypt your data and have it decryptable, a guide to secure encryption/decryption is available at https://paragonie.com/white-paper/2015-secure-php-data-encryption. To summarize that link:
To make reading of this page more valuable (for future search results) I made a list of libraries known to me.. As @CommonsWare mentioned there are super-similar questions/answers.. Anyway some libraries that can be used for making charts are:
Open Source:
Paid:
** - means I didn't try those so I can't really recommend it but other users suggested it..
Here look at the code:
You can simply create a Function and let it do the work for you, kind of functional Style!
Function<Person, List<Object>> compositeKey = personRecord ->
Arrays.<Object>asList(personRecord.getName(), personRecord.getAge());
Now you can use it as a map:
Map<Object, List<Person>> map =
people.collect(Collectors.groupingBy(compositeKey, Collectors.toList()));
Cheers!
you can make that using transform and transform origins.
Combining various transfroms gives similar result. I hope you find it helpful. :) See these examples for simpler transforms. this has left point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 100% 50%;_x000D_
-moz-transform-origin: 100% 50%;_x000D_
-o-transform-origin: 100% 50%;_x000D_
transform-origin: 100% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
This has right skew point :
div { _x000D_
width: 300px;_x000D_
height:200px;_x000D_
background-image: url('data:image/gif;base64,R0lGODdhLAHIANUAAKqqqgAAAO7u7uXl5bKysru7u93d3czMzMPDw9TU1BUVFdDQ0B0dHaurqywsLHJyclVVVTc3N5SUlBkZGcHBwRYWFmpqasjIyDAwMJubm39/fyoqKhcXF4qKikJCQnd3d0ZGRhoaGoWFhV1dXVlZWZ+fn7m5uT8/Py4uLqWlpWFhYUlJSTMzM4+Pj25ubkxMTBgYGBwcHG9vbwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAALAHIAAAG/kCAcEgsGo/IpHLJbDqf0Kh0Sq1ar9isdsvter/gsHhMLpvP6LR6zW673/C4fE6v2+/4vH7P7/v/gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp+goaKjpKWmp6ipqqusra6vsLGys7S1tre4ubq7vL2+v8DBwsPExcbHyMnKy8zNzs/Q0dLT1NXW19jZ2tvc3d7f4OHi4+Tl5ufo6err7O3u7/Dx8vP09fb3+Pn6+/z9/v8AAwocSLCgwYMIEypcyLChw4cQI0qcSLGixYsYM2rcyLGjx48gQ4ocSbKkyZMoU6pcybKlS3gBYsZUIESDggAKLBCxiVOn/hQNG2JCKMIz55CiPlUKWLqAQQMAEjg0ENAggAYhUadWvRoFhIsFC14kzUrVKlSpZbmydPCgAAAPbQEU+ABCCFy3c+tGSXCAAIEEMIbclUv3bdy8LSFEOCAkBIEhBEI0fiwkspETajWcSCIhxhDHkCWDrix5pYQJFIYEoAwgQwAhq4e4NpIAhQSoKBIkkTEUNuvZsYXMXukgQAWfryEnT16ZOZEUDiQ4SJ0EhgnVRAi8dq6dpQEBFzDoDHAbOwDyRJwPKdAhQAfWRiBAYI0ee33YLglQeM1AxBAJDAjR338BHqECCSskocEE1w0xIFYBPghVgS1lECAEIwxBQm8Y+WrYG1EsJGCBWkRkBV+HQmwIAIoAqNiSBg48VYJZCzY441U1GhFVagfYZoQDLbhFxI0A5EhkjioFFQAHHeAV1ZINUFbAk1LBZ1cLlKXgQRFKyrQelVHKBaaVJn0nwAAIDIHAAGcKKcSabR6RQJpCFKAbEWYuJQARcA7gZp9uviTooIQWauihiCaq6KKMNuroo5BGKumklFZq6aWYZqrpppx26umnoIYq6qiklmrqqaimquqqrLbq6quwxirrrLTWauutuOaq66689urrr8AGK+ywxBZr7LHIJqvsssw26+yz0EYr7bTUVmvttdhmq+223Hbr7bfghhtPEAA7');_x000D_
-webkit-transform: perspective(300px) rotateX(-30deg);_x000D_
-o-transform: perspective(300px) rotateX(-30deg);_x000D_
-moz-transform: perspective(300px) rotateX(-30deg);_x000D_
-webkit-transform-origin: 0% 50%;_x000D_
-moz-transform-origin: 0% 50%;_x000D_
-o-transform-origin: 0% 50%;_x000D_
transform-origin: 0% 50%;_x000D_
margin: 10px 90px;_x000D_
}
_x000D_
<div></div>
_x000D_
what transform: 0% 50%;
does is it sets the origin to vertical middle and horizontal left of the element. so the perspective is not visible at the left part of the image, so it looks flat. Perspective effect is there at the right part, so it looks slanted.
curl command:
curl -X PUT http://127.0.0.1:8080/api/xxx ...
-H 'content-type: multipart/form-data; boundary=----xxx' \
-F taskStatus=1
python requests - More complicated POST requests:
updateTaskUrl = "http://127.0.0.1:8080/api/xxx"
updateInfoDict = {
"taskStatus": 1,
}
resp = requests.put(updateTaskUrl, data=updateInfoDict)
curl command:
curl -X POST http://127.0.0.1:8080/api/xxx ...
-H 'content-type: multipart/form-data; boundary=----xxx' \
-F file=@/Users/xxx.txt
python requests - POST a Multipart-Encoded File:
filePath = "/Users/xxx.txt"
fileFp = open(filePath, 'rb')
fileInfoDict = {
"file": fileFp,
}
resp = requests.post(uploadResultUrl, files=fileInfoDict)
that's all.
(returnValue != "1" ? false : true);
Two ways to do that..
Option 1:
1. Go to "Start" -> "Run".
2. Write "CMD" and press on "Enter" key.
3. Write the command "net statistics server" and press on "Enter" key.
4. The line that start with "Statistics since …" provides the time that the server was up from.
The command "net stats srv" can be use instead.
Option 2:
Uptime.exe Tool Allows You to Estimate Server Availability with Windows NT 4.0 SP4 or Higher
http://support.microsoft.com/kb/232243
Hope it helped you!!
A simple way to getting resource ID from string. Here resourceName is the name of resource ImageView in drawable folder which is included in XML file as well.
int resID = getResources().getIdentifier(resourceName, "id", getPackageName());
ImageView im = (ImageView) findViewById(resID);
Context context = im.getContext();
int id = context.getResources().getIdentifier(resourceName, "drawable",
context.getPackageName());
im.setImageResource(id);
I would rather use the Date valueOf method instead of === or !==
Seems like === is comparing internal Object's references and nothing concerning date.
This works on Oracle:
with table_max as(
select id
, home
, datetime
, player
, resource
, max(home) over (partition by home) maxhome
from table
)
select id
, home
, datetime
, player
, resource
from table_max
where home = maxhome
This worked for me
var files=data.Contents;
files = files.sort(function(a,b){
return a.LastModified - b. LastModified;
});
OR use Lodash to sort the array
files = _.orderBy(files,'LastModified','asc');
It actually requires inclusion of Twitter Bootstrap's dropdown.js
First set path of python
https://stackoverflow.com/questions/3701646/how-to-add-to-the-pythonpath-in-windows
and run python
file
python filename.py
command line argument with python
python filename.py command-line argument
From the MySql site.
Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).
Try this :
I assume your text file is on sd card
//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"file.txt");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
br.close();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
//Find the view by its id
TextView tv = (TextView)findViewById(R.id.text_view);
//Set the text
tv.setText(text.toString());
following links can also help you :
How can I read a text file from the SD card in Android?
I wrote this to compare the results of a pretty nasty view I ported from Oracle to SQL Server. It creates a pair of temp tables, #DataVariances and #SchemaVariances, with differences in (you guessed it) the data in the tables and the schema of the tables themselves.
It requires both tables have a primary key, but you could drop it into tempdb with an identity column if the source tables don't have one.
declare @TableA_ThreePartName nvarchar(max) = ''
declare @TableB_ThreePartName nvarchar(max) = ''
declare @KeyName nvarchar(max) = ''
/***********************************************************************************************
Script to compare two tables and return differneces in schema and data.
Author: Devin Lamothe 2017-08-11
***********************************************************************************************/
set nocount on
-- Split three part name into database/schema/table
declare @Database_A nvarchar(max) = (
select left(@TableA_ThreePartName,charindex('.',@TableA_ThreePartName) - 1))
declare @Table_A nvarchar(max) = (
select right(@TableA_ThreePartName,len(@TableA_ThreePartName) - charindex('.',@TableA_ThreePartName,len(@Database_A) + 2)))
declare @Schema_A nvarchar(max) = (
select replace(replace(@TableA_ThreePartName,@Database_A + '.',''),'.' + @Table_A,''))
declare @Database_B nvarchar(max) = (
select left(@TableB_ThreePartName,charindex('.',@TableB_ThreePartName) - 1))
declare @Table_B nvarchar(max) = (
select right(@TableB_ThreePartName,len(@TableB_ThreePartName) - charindex('.',@TableB_ThreePartName,len(@Database_B) + 2)))
declare @Schema_B nvarchar(max) = (
select replace(replace(@TableB_ThreePartName,@Database_B + '.',''),'.' + @Table_B,''))
-- Get schema for both tables
declare @GetTableADetails nvarchar(max) = '
use [' + @Database_A +']
select COLUMN_NAME
, DATA_TYPE
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = ''' + @Table_A + '''
and TABLE_SCHEMA = ''' + @Schema_A + '''
'
create table #Table_A_Details (
ColumnName nvarchar(max)
, DataType nvarchar(max)
)
insert into #Table_A_Details
exec (@GetTableADetails)
declare @GetTableBDetails nvarchar(max) = '
use [' + @Database_B +']
select COLUMN_NAME
, DATA_TYPE
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = ''' + @Table_B + '''
and TABLE_SCHEMA = ''' + @Schema_B + '''
'
create table #Table_B_Details (
ColumnName nvarchar(max)
, DataType nvarchar(max)
)
insert into #Table_B_Details
exec (@GetTableBDetails)
-- Get differences in table schema
select ROW_NUMBER() over (order by
a.ColumnName
, b.ColumnName) as RowKey
, a.ColumnName as A_ColumnName
, a.DataType as A_DataType
, b.ColumnName as B_ColumnName
, b.DataType as B_DataType
into #FieldList
from #Table_A_Details a
full outer join #Table_B_Details b
on a.ColumnName = b.ColumnName
where a.ColumnName is null
or b.ColumnName is null
or a.DataType <> b.DataType
drop table #Table_A_Details
drop table #Table_B_Details
select coalesce(A_ColumnName,B_ColumnName) as ColumnName
, A_DataType
, B_DataType
into #SchemaVariances
from #FieldList
-- Get differences in table data
declare @LastColumn int = (select max(RowKey) from #FieldList)
declare @RowNumber int = 1
declare @ThisField nvarchar(max)
declare @TestSql nvarchar(max)
create table #DataVariances (
TableKey nvarchar(max)
, FieldName nvarchar(max)
, TableA_Value nvarchar(max)
, TableB_Value nvarchar(max)
)
delete from #FieldList where A_DataType in ('varbinary','image') or B_DataType in ('varbinary','image')
while @RowNumber <= @LastColumn begin
set @TestSql = '
select coalesce(a.[' + @KeyName + '],b.[' + @KeyName + ']) as TableKey
, ''' + @ThisField + ''' as FieldName
, a.[' + @ThisField + '] as [TableA_Value]
, b.[' + @ThisField + '] as [TableB_Value]
from [' + @Database_A + '].[' + @Schema_A + '].[' + @Table_A + '] a
inner join [' + @Database_B + '].[' + @Schema_B + '].[' + @Table_B + '] b
on a.[' + @KeyName + '] = b.[' + @KeyName + ']
where ltrim(rtrim(a.[' + @ThisField + '])) <> ltrim(rtrim(b.[' + @ThisField + ']))
or (a.[' + @ThisField + '] is null and b.[' + @ThisField + '] is not null)
or (a.[' + @ThisField + '] is not null and b.[' + @ThisField + '] is null)
'
insert into #DataVariances
exec (@TestSql)
set @RowNumber = @RowNumber + 1
set @ThisField = (select coalesce(A_ColumnName,B_ColumnName) from #FieldList a where RowKey = @RowNumber)
end
drop table #FieldList
print 'Query complete. Select from #DataVariances to verify data integrity or #SchemaVariances to verify schemas match. Data types varbinary and image are not checked.'
To embed this in your script, you can do it like this:
Write-Output $server.name | Out-File '(Your Path)\Servers.txt' -Append
That should do the trick.
Keep your entitlements file in Target> Build Settings > Code Signing > Code Signing Entitlements.
Go to Target > Capabilities. Toggle On/Off or Off/On one of the capabilities.
Run.
There are several possible catches. I think that the most common error is in this part of the connection string:
res://xxx/yyy.csdl|res://xxx/yyy.ssdl|res://xxx/yyy.msl;
This is no magic. Once you understand what is stands for you'll get the connection string right.
First the xxx part. That's nothing else than an assembly name where you defined you EF context clas. Usually it would be something like MyProject.Data. Default value is * which stands for all loaded assemblies. It's always better to specify a particular assembly name.
Now the yyy part. That's a resource name in the xxx assembly. It will usually be something like a relative path to your .edmx file with dots instead of slashes. E.g. Models/Catalog - Models.Catalog The easiest way to get the correct string for your application is to build the xxx assembly. Then open the assembly dll file in a text editor (I prefer the Total Commander's default viewer) and search for ".csdl". Usually there won't be more than 1 occurence of that string.
Your final EF connection string may look like this:
res://MyProject.Data/Models.Catalog.DataContext.csdl|res://MyProject.Data/Models.Catalog.DataContext.ssdl|res://MyProject.Data/Models.Catalog.DataContext.msl;
It is not a big deal. you can simply put like this
WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")}");
Excuse here for I used $ which is for string Interpolation .
This is another solution:
if os.path.isfile(os.path.join(path, filename)):
os.remove(os.path.join(path, filename))
There are couple of ways you can search as "LIKE" operator of SQL in C#. If you just want to know whether the pattern exists in the string variable, you can use
string value = "samplevalue";
value.Contains("eva"); // like '%eva%'
value.StartsWith("eva"); // like 'eva%'
value.EndsWith("eva"); // like '%eva'
if you want to search the pattern from a list of string, you should use LINQ to Object Features.
List<string> valuee = new List<string> { "samplevalue1", "samplevalue2", "samplevalue3" };
List<string> contains = (List<string>) (from val in valuee
where val.Contains("pattern")
select val); // like '%pattern%'
List<string> starts = (List<string>) (from val in valuee
where val.StartsWith("pattern")
select val);// like 'pattern%'
List<string> ends = (List<string>) (from val in valuee
where val.EndsWith ("pattern")
select val);// like '%pattern'
I agree that cygwin/OpenSSH is the best choice, but its setup can be involved to say the least. Here is a document to get you started though: Installing OpenSSH
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
you can also use just
StringFormat=d
in your datagrid column for date time showing
finally it will be
<sdk:DataGridTextColumn Binding="{Binding Path=DeliveryDate,StringFormat=d}" Header="Delivery date" Width="*" />
the out put will look like
Take a look at the docs:
In Kotlin, if is an expression, i.e. it returns a value. Therefore there is no ternary operator (condition ? then : else), because ordinary if works fine in this role.
You can use the contains method
var result = parent.contains(child);
or you can try to use compareDocumentPosition()
var result = nodeA.compareDocumentPosition(nodeB);
The last one is more powerful: it return a bitmask as result.
First modify the column to remove the auto_increment field like this: alter table user_customer_permission modify column id int;
Next, drop the primary key. alter table user_customer_permission drop primary key;
This can be done using httpPostedFileBase class returns the HttpInputStreamObject as per specified here
You should convert the stream into byte array and then you can read file content
Please refer following link
http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]
Hope this helps
UPDATE :
The stream that you get from your HTTP call is read-only sequential (non-seekable) and the FileStream is read/write seekable. You will need first to read the entire stream from the HTTP call into a byte array, then create the FileStream from that array.
Taken from here
// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);
string result = System.Text.Encoding.UTF8.GetString(binData);
Try with this
echo date("G:i", strtotime($time));
or you can try like this also
echo date("H:i", strtotime("04:25 PM"));
Here is the code help you to download file from server at the same time you can see the progress of downloading on your status bar.
See the functionality in below image of my code:
STEP - 1 : Create on DownloadFileFromURL.java class file to download file content from server. Here i create an asynchronous task to download file.
public class DownloadFileFromURL extends AsyncTask<String, Integer, String> {
private NotificationManager mNotifyManager;
private NotificationCompat.Builder build;
private File fileurl;
int id = 123;
OutputStream output;
private Context context;
private String selectedDate;
private String ts = "";
public DownloadFileFromURL(Context context, String selectedDate) {
this.context = context;
this.selectedDate = selectedDate;
}
protected void onPreExecute() {
super.onPreExecute();
mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
build = new NotificationCompat.Builder(context);
build.setContentTitle("Download")
.setContentText("Download in progress")
.setChannelId(id + "")
.setAutoCancel(false)
.setDefaults(0)
.setSmallIcon(R.drawable.ic_menu_download);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(id + "",
"Social Media Downloader",
NotificationManager.IMPORTANCE_HIGH);
channel.setDescription("no sound");
channel.setSound(null, null);
channel.enableLights(false);
channel.setLightColor(Color.BLUE);
channel.enableVibration(false);
mNotifyManager.createNotificationChannel(channel);
}
build.setProgress(100, 0, false);
mNotifyManager.notify(id, build.build());
String msg = "Download started";
//CustomToast.showToast(context,msg);
}
@Override
protected String doInBackground(String... f_url) {
int count;
ts = selectedDate.split("T")[0];
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
output = new FileOutputStream(Environment
.getExternalStorageDirectory().toString()
+ Const.DownloadPath + ts + ".pdf");
fileurl = new File(Environment.getExternalStorageDirectory()
+ Const.DownloadPath + ts + ".pdf");
byte[] data = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
int cur = (int) ((total * 100) / lenghtOfFile);
publishProgress(Math.min(cur, 100));
if (Math.min(cur, 100) > 98) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
Log.d("Failure", "sleeping failure");
}
}
Log.i("currentProgress", "currentProgress: " + Math.min(cur, 100) + "\n " + cur);
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
build.setProgress(100, progress[0], false);
mNotifyManager.notify(id, build.build());
super.onProgressUpdate(progress);
}
@Override
protected void onPostExecute(String file_url) {
build.setContentText("Download complete");
build.setProgress(0, 0, false);
mNotifyManager.notify(id, build.build());
} }
Note: If you want code with import package then Click Here
Now Step 2: You need to call above ayncronous task on your click event. for example i have set on pdf image icon. To call AsyncTask use below code:
new DownloadFileFromURL(fContext,filename).execute(serverFileUrl);
Note: Here You can see filename variable in file parameter. This is the name which i use to save my downloaded file in local device. currently i am downloading only pdf file but you can use you url in serverFileUrl parameter.
you can also do that when the mouse clicks, let's suppose your placeholder text is "User_Name"
private void textBox1_MouseClick(object sender, MouseEventArgs e)
{
if(textBox1.Text == "User_Name")
textBox1.Text = "";
}
If you are looking inside dockerfile while creating image, add this line:
RUN apk add --update yourPackageName
https://stackoverflow.com/a/53784508/5626747
Can't comment due to reputation, so I'm making another answer:
In this case you will also have to remove the generally suggested display: block;
property from the element you set the text-overflow: ellipsis;
on, or it will cut off without the ... at the end.
If you encode the & in your URL to %26 it works correctly. Just tested and verified.
Go to src/enviroments/enviroments.ts
and enable the production mode
export const environment = {
production: true
};
for Angular 2
kubectl get nodes
Result:
NAME STATUS AGE
192.168.1.157 NotReady 42d
192.168.1.158 Ready 42d
192.168.1.159 Ready 42d
Here is a NotReady on the node of 192.168.1.157
. Then debugging this notready node, and you can read offical documents - Application Introspection and Debugging.
kubectl describe node 192.168.1.157
Partial Result:
Conditions:
Type Status LastHeartbeatTime LastTransitionTime Reason Message
---- ------ ----------------- ------------------ ------ -------
OutOfDisk Unknown Sat, 28 Dec 2016 12:56:01 +0000 Sat, 28 Dec 2016 12:56:41 +0000 NodeStatusUnknown Kubelet stopped posting node status.
Ready Unknown Sat, 28 Dec 2016 12:56:01 +0000 Sat, 28 Dec 2016 12:56:41 +0000 NodeStatusUnknown Kubelet stopped posting node status.
There is a OutOfDisk on my node, then Kubelet stopped posting node status.
So, I must free some disk space, using the command of df
on my Ubuntu14.04 I can check the details of memory, and using the command of docker rmi image_id/image_name
under the role of su
I can remove the useless images.
Login in 192.168.1.157
by using ssh, like ssh [email protected]
, and switch to the 'su' by sudo su
;
/etc/init.d/kubelet restart
Result:
stop: Unknown instance:
kubelet start/running, process 59261
On the master:
kubectl get nodes
Result:
NAME STATUS AGE
192.168.1.157 Ready 42d
192.168.1.158 Ready 42d
192.168.1.159 Ready 42d
Ok, that node works fine.
Here is a reference: Kubernetes
You can concat many kind of expression by sorrounding your simple/complex expression between ||
characters:
<p th:text="|${bean.field} ! ${bean.field}|">Static content</p>
I'm not sure exactly why I was getting the error, but pip3 uninstall numpy
then pip3 install numpy
resolved the issue for me.
The file is being read as a bunch of str
s, but it should be unicode
s. Python tries to implicitly convert, but fails. Change:
job_titles = [line.strip() for line in title_file.readlines()]
to explicitly decode the str
s to unicode
(here assuming UTF-8):
job_titles = [line.decode('utf-8').strip() for line in title_file.readlines()]
It could also be solved by importing the codecs
module and using codecs.open
rather than the built-in open
.
In Swift, the == operator is equivalent to Objective C's isEqual: method (it calls the isEqual method instead of just comparing pointers, and there's a new === method for testing that the pointers are the same), so you can just write this as:
if username == "" || password == ""
{
println("Sign in failed. Empty character")
}
There is a very simple and easy solution to your question:
var districtId = 210;
if (DistrictsEnum[districtId] != null) {
// Returns 'undefined' if the districtId not exists in the DistrictsEnum
model.handlingDistrictId = districtId;
}
I recently wrote this inline table valued function to solve this very problem. It's not limited in range other than memory and storage. It accesses no tables so there's no need for disk reads or writes generally. It adds joins values exponentially on each iteration so it's very fast even for very large ranges. It creates ten million records in five seconds on my server. It also works with negative values.
CREATE FUNCTION [dbo].[fn_ConsecutiveNumbers]
(
@start int,
@end int
) RETURNS TABLE
RETURN
select
x268435456.X
| x16777216.X
| x1048576.X
| x65536.X
| x4096.X
| x256.X
| x16.X
| x1.X
+ @start
X
from
(VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15)) as x1(X)
join
(VALUES (0),(16),(32),(48),(64),(80),(96),(112),(128),(144),(160),(176),(192),(208),(224),(240)) as x16(X)
on x1.X <= @end-@start and x16.X <= @end-@start
join
(VALUES (0),(256),(512),(768),(1024),(1280),(1536),(1792),(2048),(2304),(2560),(2816),(3072),(3328),(3584),(3840)) as x256(X)
on x256.X <= @end-@start
join
(VALUES (0),(4096),(8192),(12288),(16384),(20480),(24576),(28672),(32768),(36864),(40960),(45056),(49152),(53248),(57344),(61440)) as x4096(X)
on x4096.X <= @end-@start
join
(VALUES (0),(65536),(131072),(196608),(262144),(327680),(393216),(458752),(524288),(589824),(655360),(720896),(786432),(851968),(917504),(983040)) as x65536(X)
on x65536.X <= @end-@start
join
(VALUES (0),(1048576),(2097152),(3145728),(4194304),(5242880),(6291456),(7340032),(8388608),(9437184),(10485760),(11534336),(12582912),(13631488),(14680064),(15728640)) as x1048576(X)
on x1048576.X <= @end-@start
join
(VALUES (0),(16777216),(33554432),(50331648),(67108864),(83886080),(100663296),(117440512),(134217728),(150994944),(167772160),(184549376),(201326592),(218103808),(234881024),(251658240)) as x16777216(X)
on x16777216.X <= @end-@start
join
(VALUES (0),(268435456),(536870912),(805306368),(1073741824),(1342177280),(1610612736),(1879048192)) as x268435456(X)
on x268435456.X <= @end-@start
WHERE @end >=
x268435456.X
| isnull(x16777216.X, 0)
| isnull(x1048576.X, 0)
| isnull(x65536.X, 0)
| isnull(x4096.X, 0)
| isnull(x256.X, 0)
| isnull(x16.X, 0)
| isnull(x1.X, 0)
+ @start
GO
SELECT X FROM fn_ConsecutiveNumbers(5, 500);
It's handy for date and time ranges as well:
SELECT DATEADD(day,X, 0) DayX
FROM fn_ConsecutiveNumbers(datediff(day,0,'5/8/2015'), datediff(day,0,'5/31/2015'))
SELECT DATEADD(hour,X, 0) HourX
FROM fn_ConsecutiveNumbers(datediff(hour,0,'5/8/2015'), datediff(hour,0,'5/8/2015 12:00 PM'));
You could use a cross apply join on it to split records based on values in the table. So for example to create a record for every minute on a time range in a table you could do something like:
select TimeRanges.StartTime,
TimeRanges.EndTime,
DATEADD(minute,X, 0) MinuteX
FROM TimeRanges
cross apply fn_ConsecutiveNumbers(datediff(hour,0,TimeRanges.StartTime),
datediff(hour,0,TimeRanges.EndTime)) ConsecutiveNumbers
On linux, you can run this command and see the result :
ps aux | grep "java"
To say "nodemon" would answer the question.
But on how only to kill (all) node demon(s), the following works for me:
pkill -HUP node
I use this code and works just fine:
input[type="checkbox"],
input[type="radio"],
input.radio,
input.checkbox {
vertical-align:text-top;
width:13px;
height:13px;
padding:0;
margin:0;
position:relative;
overflow:hidden;
top:2px;
}
You may want to readjust top value (depends on your line-height
). If you don't want IE6 compatibility, you just need to put this code into your page. Otherwise, you will must add extra class to your inputs (you can use jQuery - or any other library - for that tho ;) )
You need this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<-- I absolutely don't know why, but go ahead, and add this code snippet to your CSS -->
*{
margin:0;
padding:0;
}
That's it, have fun removing all those white-spaces problems.
Easy way to Fetch Single Record from MySQL Database by using PHP List
The SQL Query is SELECT user_name from user_table WHERE user_id = 6
The PHP Code for the above Query is
$sql_select = "";
$sql_select .= "SELECT ";
$sql_select .= " user_name ";
$sql_select .= "FROM user_table ";
$sql_select .= "WHERE user_id = 6" ;
$rs_id = mysql_query($sql_select, $link) or die(mysql_error());
list($userName) = mysql_fetch_row($rs_id);
Note: The List Concept should be applicable for Single Row Fetching not for Multiple Rows
public String removeFirstChar(String s){
return s.substring(1);
}
Using Jquery
Rather than creating temp variables it can be written in a continuous flow pattern as follows:
$('</form>', { action: url, method: 'POST' }).append(
$('<input>', {type: 'hidden', id: 'id_field_1', name: 'name_field_1', value: val_field_1}),
$('<input>', {type: 'hidden', id: 'id_field_2', name: 'name_field_2', value: val_field_2}),
).appendTo('body').submit();
Since you're using jQuery, you just need to attach to some specific events and some pre defined animations:
$('#cat').hover(function()
{
// Mouse Over Callback
}, function()
{
// Mouse Leave callback
});
Then, to do the animation, you simply need to call the fadeOut / fadeIn animations:
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
Combining the two together, you would simply insert the animations in the hover callbacks (something like so, use this as a reference point):
$('#cat').hover(function()
{
if($('#dog').is(':visible'))
$('#dog').fadeOut(750 /* Animation Time */, function()
{
// animation complete callback
$('#cat').fadeIn(750);
});
}, function()
{
// Mouse Leave callback
});
We're doing this to create thumbnails of images:
BufferedImage tThumbImage = new BufferedImage( tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB );
Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
tGraphics2D.setBackground( Color.WHITE );
tGraphics2D.setPaint( Color.WHITE );
tGraphics2D.fillRect( 0, 0, tThumbWidth, tThumbHeight );
tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );
tGraphics2D.drawImage( tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null ); //draw the image scaled
ImageIO.write( tThumbImage, "JPG", tThumbnailTarget ); //write the image to a file
I've my project in github and heroku, for upload an heroku use :
heroku git:remote -a <project>
The doc it is:
Just go to OUTPUT window, then click on Packages icon (it is located between Plot and Help icons). Remove "tick / check mark" from the package you wanted be unload.
For again using the package just put a "tick or Check mark" in front of package or use :
library (lme4)
JConsole has a graphical view.
You also have VisualVM and Oracle JRockit Mission Control
This is probably simpler than you're thinking:
int w = WIDTH_PX, h = HEIGHT_PX;
Bitmap.Config conf = Bitmap.Config.ARGB_8888; // see other conf types
Bitmap bmp = Bitmap.createBitmap(w, h, conf); // this creates a MUTABLE bitmap
Canvas canvas = new Canvas(bmp);
// ready to draw on that bitmap through that canvas
Here's a series of tutorials I've found on the topic: Drawing with Canvas Series
--
-- STORED PROCEDURE
-- Name of stored procedure.
--
-- DESCRIPTION
-- Business description of the stored procedure's functionality.
--
-- PARAMETERS
-- @InputParameter1
-- * Description of @InputParameter1 and how it is used.
--
-- RETURN VALUE
-- 0 - No Error.
-- -1000 - Description of cause of non-zero return value.
--
-- PROGRAMMING NOTES
-- Gotchas and other notes for your fellow programmer.
--
-- CHANGE HISTORY
-- 05 May 2009 - Who
-- * More comprehensive description of the change than that included with the
-- source code commit message.
--
For this label:
<asp:label id="myLabel" runat="server" />
In the code behind use (C#):
myLabel.Text = "my text";
Update (following updated question):
You do not need to use FindControl
- that whole line is superfluous:
Label myLabel = this.FindControl("myLabel") as Label;
myLabel.Text = "my text";
Should be just:
myLabel.Text = "my text";
The Visual Studio designer should create a file with all the server side controls already added properly to the class (in a RankPage.aspx.designer.cs
file, by default).
You are talking about a RankPage.cs
file - the way Visual Studio would have named it is RankPage.aspx.cs
. How are you linking these files together?
If you want first 2 letters and last 2 letters of a string then you can use the following code:
name = "India"
name[0:2]="In"
names[-2:]="ia"
This may not be the prettiest, but if you don't want to use the MessageBoxManager, (which is awesome):
public static DialogResult DialogBox(string title, string promptText, ref string value, string button1 = "OK", string button2 = "Cancel", string button3 = null)
{
Form form = new Form();
Label label = new Label();
TextBox textBox = new TextBox();
Button button_1 = new Button();
Button button_2 = new Button();
Button button_3 = new Button();
int buttonStartPos = 228; //Standard two button position
if (button3 != null)
buttonStartPos = 228 - 81;
else
{
button_3.Visible = false;
button_3.Enabled = false;
}
form.Text = title;
// Label
label.Text = promptText;
label.SetBounds(9, 20, 372, 13);
label.Font = new Font("Microsoft Tai Le", 10, FontStyle.Regular);
// TextBox
if (value == null)
{
}
else
{
textBox.Text = value;
textBox.SetBounds(12, 36, 372, 20);
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
}
button_1.Text = button1;
button_2.Text = button2;
button_3.Text = button3 ?? string.Empty;
button_1.DialogResult = DialogResult.OK;
button_2.DialogResult = DialogResult.Cancel;
button_3.DialogResult = DialogResult.Yes;
button_1.SetBounds(buttonStartPos, 72, 75, 23);
button_2.SetBounds(buttonStartPos + 81, 72, 75, 23);
button_3.SetBounds(buttonStartPos + (2 * 81), 72, 75, 23);
label.AutoSize = true;
button_1.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_2.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
button_3.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
form.ClientSize = new Size(396, 107);
form.Controls.AddRange(new Control[] { label, button_1, button_2 });
if (button3 != null)
form.Controls.Add(button_3);
if (value != null)
form.Controls.Add(textBox);
form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = button_1;
form.CancelButton = button_2;
DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}
It seems you now do not need to reverse geocode and now get the address directly from ClientLocation:
google.loader.ClientLocation.address.city
NSArray * values = [dictionary allValues];
take a look at codenameone.com project, it's a cross platform mobile framework where the ui part is a fork of LWUIT. This project leverage xmlvm to translates the java bytes code to Objective C
How about:
when(a.method(isA(A.class))).thenReturn(b);
or:
when(a.method((A)notNull())).thenReturn(b);
Here is what you can try
OpenWindow.document.write(output);
call OpenWindow.init()
when the dom is ready So the parent window will have
OpenWindow.onload = function(){
OpenWindow.init('test');
}
and in the child
function init(txt){
$('#test').text(txt);
}
Use %.6f
.
This will print 6 decimals.
Exception : java.net.ConnectException
This means your request didn't getting response from server in stipulated time. And their are some reasons for this exception:
The Groovy way to do this is
def list = []
list << new MyType(...)
which creates a list and uses the overloaded leftShift
operator to append an item
See the Groovy docs on Lists for lots of examples.
SYSDATETIME()
and SYSUTCDATETIME()
are the DateTime2 equivalents of
which return a DateTime.
DateTime2 is now the preferred method for storing the date and time in SQL Server 2008+. See the following StackOverflow Post.
Here is what I have for mine.
Essentially you are utilizing the onfocus and onblur commands in the tag to trigger the appropriate javascript. It could be as simple as:
<span><input name="login_text_password" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="this.select(); this.setAttribute('type','text');" /></span>
An evolved version of this basic functionality checks for and empty string and returns the password input back to the original "Password" in the event of a null textbox:
<script type="text/javascript">
function password_set_attribute() {
if (document.getElementsByName("login_text_password")[0].value.replace(/\s+/g, ' ') == "" || document.getElementsByName[0].value == null) {
document.getElementsByName("login_text_password")[0].setAttribute('type','text')
document.getElementsByName("login_text_password")[0].value = 'Password';
}
else {
document.getElementsByName("login_text_password")[0].setAttribute('type','password')
}
}
</script>
Where HTML looks like:
<span><input name="login_text_password" class="roundCorners" type="text" value="Password" onfocus="this.select(); this.setAttribute('type','password');" onblur="password_set_attribute();" /></span>
d = {1: 2, '2': 3, 5: 7}
del d[5]
print 'd = ', d
Result: d = {1: 2, '2': 3}
You can also check whether an element is in set or not while inserting the element. The single element version return a pair, with its member pair::first set to an iterator pointing to either the newly inserted element or to the equivalent element already in the set. The pair::second element in the pair is set to true if a new element was inserted or false if an equivalent element already existed.
For example: Suppose the set already has 20 as an element.
std::set<int> myset;
std::set<int>::iterator it;
std::pair<std::set<int>::iterator,bool> ret;
ret=myset.insert(20);
if(ret.second==false)
{
//do nothing
}
else
{
//do something
}
it=ret.first //points to element 20 already in set.
If the element is newly inserted than pair::first will point to the position of new element in set.
I used docker-entrypoint-initdb.d approach (Thanks to @Kuhess) But in my case I want to create my DB based on some parameters I defined in .env file so I did these
1) First I define .env file something like this in my docker root project directory
MYSQL_DATABASE=my_db_name
MYSQL_USER=user_test
MYSQL_PASSWORD=test
MYSQL_ROOT_PASSWORD=test
MYSQL_PORT=3306
2) Then I define my docker-compose.yml file. So I used the args directive to define my environment variables and I set them from .env file
version: '2'
services:
### MySQL Container
mysql:
build:
context: ./mysql
args:
- MYSQL_DATABASE=${MYSQL_DATABASE}
- MYSQL_USER=${MYSQL_USER}
- MYSQL_PASSWORD=${MYSQL_PASSWORD}
- MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
ports:
- "${MYSQL_PORT}:3306"
3) Then I define a mysql folder that includes a Dockerfile. So the Dockerfile is this
FROM mysql:5.7
RUN chown -R mysql:root /var/lib/mysql/
ARG MYSQL_DATABASE
ARG MYSQL_USER
ARG MYSQL_PASSWORD
ARG MYSQL_ROOT_PASSWORD
ENV MYSQL_DATABASE=$MYSQL_DATABASE
ENV MYSQL_USER=$MYSQL_USER
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD
ADD data.sql /etc/mysql/data.sql
RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql
RUN cp /etc/mysql/data.sql /docker-entrypoint-initdb.d
EXPOSE 3306
4) Now I use mysqldump to dump my db and put the data.sql inside mysql folder
mysqldump -h <server name> -u<user> -p <db name> > data.sql
The file is just a normal sql dump file but I add 2 lines at the beginning so the file would look like this
--
-- Create a database using `MYSQL_DATABASE` placeholder
--
CREATE DATABASE IF NOT EXISTS `MYSQL_DATABASE`;
USE `MYSQL_DATABASE`;
-- Rest of queries
DROP TABLE IF EXISTS `x`;
CREATE TABLE `x` (..)
LOCK TABLES `x` WRITE;
INSERT INTO `x` VALUES ...;
...
...
...
So what happening is that I used "RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql" command to replace the MYSQL_DATABASE
placeholder with the name of my DB that I have set it in .env file.
|- docker-compose.yml
|- .env
|- mysql
|- Dockerfile
|- data.sql
Now you are ready to build and run your container
The substr()
function will probably help you here:
$str = substr($str, 1);
Strings are indexed starting from 0, and this functions second parameter takes the cutstart. So make that 1, and the first char is gone.
It seems that the problem is in eslint-plugin-react
.
It can not correctly detect what props were mentioned in propTypes
if you have annotated named objects via destructuring anywhere in the class.
There was similar problem in the past
It is probably too late, but for the sake of others (like me) who faced the same problem. It is all about the little '\' at the end of the path variable. When you insert the path to MongoDB's bin directory at the end of the PATH windows variable, do not forget to put the '\' (Backslash) at the end, which tells windows it is a directory and not an executable named bin... e.g. I:\Program Files\MongoDB\Server\3.0\bin\
You can use a powershell script (this works for users with folder redirection as well to not have their recycle bins take up server storage space)
$Shell = New-Object -ComObject Shell.Application
$RecBin = $Shell.Namespace(0xA)
$RecBin.Items() | %{Remove-Item $_.Path -Recurse -Confirm:$false}
The above script is taken from here.
If you have windows 10 and powershell 5 there is the Clear-RecycleBin
commandlet.
To use Clear-RecycleBin
inside PowerShell without confirmation, you can use Clear-RecycleBin -Force
. Official documentation can be found here
String based operators will be deprecated in the future (You've probably seen the warning in console).
Getting this to work with symbolic operators was quite confusing for me, and I've updated the docs with two examples.
Post.findAll({
where: {
[Op.or]: [{authorId: 12}, {authorId: 13}]
}
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
Post.findAll({
where: {
authorId: {
[Op.or]: [12, 13]
}
}
});
// SELECT * FROM post WHERE authorId = 12 OR authorId = 13;
Put this in your server directive:
location /issue {
rewrite ^/issue(.*) http://$server_name/shop/issues/custom_issue_name$1 permanent;
}
Or duplicate it:
location /issue1 {
rewrite ^/.* http://$server_name/shop/issues/custom_issue_name1 permanent;
}
location /issue2 {
rewrite ^.* http://$server_name/shop/issues/custom_issue_name2 permanent;
}
...
Depending on the file type you are focused on, Ctrl+H will open up different types of search screens.
A more consistent hotkey would be using the Alt method: Tap Alt, then A, then F.
Efficient Order of Operations:
You can find more details in my blog post: http://blog.simplyadvanced.net/android-how-to-findreplace-in-multiple-files-using-eclipse/
I tried all of above, nothing worked. What resolved the issue was adding IPv6 bindings in the hosts file. In step 5 of @David Murdochs answer, add two lines instead of one, i.e.:
127.0.0.1 dev.example.com
::1 dev.example.com
I figured it out by checking $ ping localhost
from command line, which used to return:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Instead, it now returns:
Reply from ::1: time<1ms
I don't know why, but for some reason IIS Express started using IPv6 instead of IPv4.
char* someString = "abcdedgh";
char* otherString = 0;
otherString = (char*)malloc(5+1);
memcpy(otherString,someString,5);
otherString[5] = 0;
UPDATE:
Tip: A good way to understand definitions is called the right-left rule (some links at the end):
Start reading from identifier and say aloud => "someString
is..."
Now go to right of someString (statement has ended with a semicolon, nothing to say).
Now go left of identifier (*
is encountered) => so say "...a pointer to...".
Now go to left of "*
" (the keyword char
is found) => say "..char".
Done!
So char* someString;
=> "someString is a pointer to char".
Since a pointer simply points to a certain memory address, it can also be used as the "starting point" for an "array" of characters.
That works with anything .. give it a go:
char* s[2]; //=> s is an array of two pointers to char
char** someThing; //=> someThing is a pointer to a pointer to char.
//Note: We look in the brackets first, and then move outward
char (* s)[2]; //=> s is a pointer to an array of two char
Some links: How to interpret complex C/C++ declarations and How To Read C Declarations
FYI, this is using Angularfire so it may vary a bit for a different service or other use but should solve the same isse $http has. I had this same issue only solution that fit for me the best was to combine all services/factories into a single promise on the scope. On each route/view that needed these services/etc to be loaded I put any functions that require loaded data inside the controller function i.e. myfunct() and the main app.js on run after auth i put
myservice.$loaded().then(function() {$rootScope.myservice = myservice;});
and in the view I just did
ng-if="myservice" ng-init="somevar=myfunct()"
in the first/parent view element/wrapper so the controller can run everything inside
myfunct()
without worrying about async promises/order/queue issues. I hope that helps someone with the same issues I had.
No need to extract the month and year.Just need to use the unix_timestamp(date String,format String) function.
For Example:
select yourdate_column
from your_table
where unix_timestamp(yourdate_column, 'yyyy-MM-dd') >= unix_timestamp('2014-06-02', 'yyyy-MM-dd')
and unix_timestamp(yourdate_column, 'yyyy-MM-dd') <= unix_timestamp('2014-07-02','yyyy-MM-dd')
order by yourdate_column limit 10;
I'm not familiar with void_t
except as a result of a Google search (it's used in a vmalloc
library by Kiem-Phong Vo at AT&T Research - I'm sure it's used in other libraries as well).
The various xxx_t typedefs are used to abstract a type from a particular definite implementation, since the concrete types used for certain things might differ from one platform to another. For example:
Void_t
abstracts the type of pointer returned by the vmalloc
library routines because it was written to work on systems that pre-date ANSI/ISO C where the void
keyword might not exist. At least that's what I'd guess.wchar_t
abstracts the type used for wide characters since on some systems it will be a 16 bit type, on others it will be a 32 bit type.So if you write your wide character handling code to use the wchar_t
type instead of, say unsigned short
, that code will presumably be more portable to various platforms.
Above solution didn't work for me. So what I did is take ProgressDialog
as globally and then add this to my activity
@Override
protected void onDestroy() {
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
super.onDestroy();
}
so that in case if activity is destroyed then the ProgressDialog will also be destroy.
If your data is in a matrix named foo
, the line you would run is
foo.sorted=foo[order[foo[,1]]
Do what the compiler tells you to do, i.e. recompile with -fPIC
. To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual.
In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM.
Finally, you can read about it on Wikipedia too.
In Twitter Bootstrap is not implemented but you can use the this plugin
Update 1:
Sames question here
If there are NO dependencies between files... here is a recursive function to include_once ALL php files in ALL subdirs:
$paths = array();
function include_recursive( $path, $debug=false){
foreach( glob( "$path/*") as $filename){
if( strpos( $filename, '.php') !== FALSE){
# php files:
include_once $filename;
if( $debug) echo "<!-- included: $filename -->\n";
} else { # dirs
$paths[] = $filename;
}
}
# Time to process the dirs:
for( $i=count($paths)-1; $i>0; $i--){
$path = $paths[$i];
unset( $paths[$i]);
include_recursive( $path);
}
}
include_recursive( "tree_to_include");
# or... to view debug in page source:
include_recursive( "tree_to_include", 'debug');
Alternate solution can be:
baseKey hKeyLocalMachine = baseKey.HKEY_LOCAL_MACHINE;
uint value = (uint)hKeyLocalMachine;
Or just:
uint value = (uint)baseKey.HKEY_LOCAL_MACHINE;
a couple years down the road, I'd vote for three.js because
ie 11 supports webgl (to what extent I can't assure you since i'm usually in chrome)
and, as far as importing external models into three.js, here's a link to mrdoob's updated loaders (so many!)
UPDATE nov 2019: the THREE.js loaders are now far more and it makes little sense to post them all: just go to this link
http://threejs.org/examples and review the loaders - at least 20 of them
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim objNS As Outlook.NameSpace
Set olApp = Outlook.Application
Set objNS = olApp.GetNamespace("MAPI")
' default local Inbox
Set Items = objNS.GetDefaultFolder(olFolderInbox).Items
End Sub
Private Sub Items_ItemAdd(ByVal item As Object)
On Error Goto ErrorHandler
Dim Msg As Outlook.MailItem
If TypeName(item) = "MailItem" Then
Set Msg = item
' ******************
' do something here
' ******************
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
You can use Janel. This last works as an application launcher or service launcher (available from 4.x).
Unfortunately, you're out of luck here.
There is inherit
to copy a certain value from a parent to its children, but there is no property the other way round (which would involve another selector to decide which style to revert).
You will have to revert style changes manually:
div { color: green; }
form div { color: red; }
form div div.content { color: green; }
If you have access to the markup, you can add several classes to style precisely what you need:
form div.sub { color: red; }
form div div.content { /* remains green */ }
Edit: The CSS Working Group is up to something:
div.content {
all: revert;
}
No idea, when or if ever this will be implemented by browsers.
Edit 2: As of March 2015 all modern browsers but Safari and IE/Edge have implemented it: https://twitter.com/LeaVerou/status/577390241763467264 (thanks, @Lea Verou!)
Edit 3: default
was renamed to revert
.
When you run composer update
, composer
generates a file called composer.lock
which lists all your packages and the currently installed versions. This allows you to later run composer install
, which will install the packages listed in that file, recreating the environment that you were last using.
It appears from your log that some of the versions of packages that are listed in your composer.lock
file are no longer available. Thus, when you run composer install
, it complains and fails. This is usually no big deal - just run composer update
and it will attempt to build a set of packages that work together and write a new composer.lock
file.
However, you're running into a different problem. It appears that, in your composer.json
file, the original developer has added some pre- or post- update actions that are failing, specifically a php artisan migrate
command. This can be avoided by running the following: composer update --no-scripts
This will run the composer update but will skip over the scripts added to the file. You should be able to successfully run the update this way.
However, this does not solve the problem long-term. There are two problems:
A migration is for database changes, not random stuff like compiling assets. Go through the migrations and remove that code from there.
Assets should not be compiled each time you run composer update
. Remove that step from the composer.json
file.
From what I've read, best practice seems to be compiling assets on an as-needed basis during development (ie. when you're making changes to your LESS files - ideally using a tool like gulp.js) and before deployment.
Both the Vars() and dict methods will work for the example the OP posted, but they won't work for "loosely" defined objects like:
class foo:
a = 'foo'
b = 'bar'
To print all non-callable attributes, you can use the following function:
def printVars(object):
for i in [v for v in dir(object) if not callable(getattr(object,v))]:
print '\n%s:' % i
exec('print object.%s\n\n') % i
The error usually gets introduced while creation of CSV. Try using Linux for saving the CSV as a TextCSV. Libre Office in Ubuntu can enforce the encoding to be UTF-8, worked for me. I wasted a lot of time trying this on Mac OS. Linux is the key. I've tested on Ubuntu.
Good Luck
To checkout the branch via Jenkins scripts use:
stage('Checkout SCM') {
git branch: 'branchName', credentialsId: 'your_credentials', url: "giturlrepo"
}
Browsing the registry for guids or using paths, which method is best. If browsing the registry is no longer necessary, won't it be the better way to use guids? Office is not always installed in the same directory. The installation path can be manually altered. Also the version number is a part of the path. I could have never predicted that Microsoft would ever add '(x86)' to 'Program Files' before the introduction of 64 bits processors. If possible I would try to avoid using a path.
The code below is derived from Siddharth Rout's answer, with an additional function to list all the references that are used in the active workbook. What if I open my workbook in a later version of Excel? Will the workbook still work without adapting the VBA code? I have already checked that the guids for office 2003 and 2010 are identical. Let's hope that Microsoft doesn't change guids in future versions.
The arguments 0,0 (from .AddFromGuid) should use the latest version of a reference (which I have not been able to test).
What are your thoughts? Of course we cannot predict the future but what can we do to make our code version proof?
Sub AddReferences(wbk As Workbook)
' Run DebugPrintExistingRefs in the immediate pane, to show guids of existing references
AddRef wbk, "{00025E01-0000-0000-C000-000000000046}", "DAO"
AddRef wbk, "{00020905-0000-0000-C000-000000000046}", "Word"
AddRef wbk, "{91493440-5A91-11CF-8700-00AA0060263B}", "PowerPoint"
End Sub
Sub AddRef(wbk As Workbook, sGuid As String, sRefName As String)
Dim i As Integer
On Error GoTo EH
With wbk.VBProject.References
For i = 1 To .Count
If .Item(i).Name = sRefName Then
Exit For
End If
Next i
If i > .Count Then
.AddFromGuid sGuid, 0, 0 ' 0,0 should pick the latest version installed on the computer
End If
End With
EX: Exit Sub
EH: MsgBox "Error in 'AddRef'" & vbCrLf & vbCrLf & err.Description
Resume EX
Resume ' debug code
End Sub
Public Sub DebugPrintExistingRefs()
Dim i As Integer
With Application.ThisWorkbook.VBProject.References
For i = 1 To .Count
Debug.Print " AddRef wbk, """ & .Item(i).GUID & """, """ & .Item(i).Name & """"
Next i
End With
End Sub
The code above does not need the reference to the "Microsoft Visual Basic for Applications Extensibility" object anymore.
You can add float:none; margin:auto;
styling to centerize column content.
I'd just like to add to the very helpful answer from Kurt Pfeifle - there is now a Python wrapper for Tabula, and this seems to work very well so far: https://github.com/chezou/tabula-py
This will convert your PDF table to a Pandas data frame. You can also set the area in x,y co-ordinates which is obviously very handy for irregular data.
DataTable dt = new DataTable();
foreach (DataRow dr in drResults)
{
dt.ImportRow(dr);
}
Use node.js for that, here is example how to install node
by using brew
on mac:
brew update && install node
Then run your program by typing node filename.js
, and you can use console.log()
for output.
Import Linking the module from React Native
import { TouchableOpacity, Linking } from "react-native";
Try it:-
<TouchableOpacity onPress={() => Linking.openURL('http://Facebook.com')}>
<Text> Facebook </Text>
</TouchableOpacity>
On my AWS beanstalk server, I don't see $_SERVER['HTTPS'] variable. I do see $_SERVER['HTTP_X_FORWARDED_PROTO'] which can be either 'http' or 'https' so if you're hosting on AWS, use this:
if ($_SERVER['HTTP_HOST'] != 'localhost' and $_SERVER['HTTP_X_FORWARDED_PROTO'] != "https") {
$location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $location);
exit;
}
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
Java IO using stream oriented APIs is performed using a buffer as temporary storage of data within user space. Data read from disk by DMA is first copied to buffers in kernel space, which is then transfer to buffer in user space. Hence there is overhead. Avoiding it can achieve considerable gain in performance.
We could skip this temporary buffer in user space, if there was a way directly to access the buffer in kernel space. Java NIO provides a way to do so.
ByteBuffer
is among several buffers provided by Java NIO. Its just a container or holding tank to read data from or write data to. Above behavior is achieved by allocating a direct buffer using allocateDirect()
API on Buffer.
Easier solution: set the environment variable USE_SDK_WRAPPER=1, or hack tools/android.bat to add the line "set USE_SDK_WRAPPER=1". This prevents android.bat from popping up a "y/n" prompt, which is what's confusing Unity.
You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
Sharing a few functions which I created for dates:
Please note that I wanted to get time for a particular location (not just UTC time). If you want UTC time, just remove loc variable and .In(loc) function call.
func GetTimeStamp() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
t := time.Now().In(loc)
return t.Format("20060102150405")
}
func GetTodaysDate() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02")
}
func GetTodaysDateTime() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("2006-01-02 15:04:05")
}
func GetTodaysDateTimeFormatted() string {
loc, _ := time.LoadLocation("America/Los_Angeles")
current_time := time.Now().In(loc)
return current_time.Format("Jan 2, 2006 at 3:04 PM")
}
func GetTimeStampFromDate(dtformat string) string {
form := "Jan 2, 2006 at 3:04 PM"
t2, _ := time.Parse(form, dtformat)
return t2.Format("20060102150405")
}
While entering the serial port name into the code in arduino IDE, enter the whole port address i.e:
/dev/cu.usbmodem*
or
/dev/cu.UG-*
where the *
is the port number.
And for the port number in case of mac just open terminal and type
ls /dev/*
and then search for the port that u have set in arduino IDE.
Is there any disadvantages/consequences of pushing empty commits?
Aside from the extreme confusion someone might get as to why there's a bunch of commits with no content in them on master, not really.
You can change the commit that you pushed to remote, but the sha1 of the commit (basically it's id number) will change permanently, which alters the source tree -- You'd then have to do a git push -f
back to remote.
Could not commit JPA transaction: Transaction marked as rollbackOnly
This exception occurs when you invoke nested methods/services also marked as @Transactional
. JB Nizet explained the mechanism in detail. I'd like to add some scenarios when it happens as well as some ways to avoid it.
Suppose we have two Spring services: Service1
and Service2
. From our program we call Service1.method1()
which in turn calls Service2.method2()
:
class Service1 {
@Transactional
public void method1() {
try {
...
service2.method2();
...
} catch (Exception e) {
...
}
}
}
class Service2 {
@Transactional
public void method2() {
...
throw new SomeException();
...
}
}
SomeException
is unchecked (extends RuntimeException) unless stated otherwise.
Scenarios:
Transaction marked for rollback by exception thrown out of method2
. This is our default case explained by JB Nizet.
Annotating method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating both method1
and method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating method2
with @Transactional(noRollbackFor = SomeException)
prevents marking transaction for rollback (no exception thrown when exiting from method1
).
Suppose method2
belongs to Service1
. Invoking it from method1
does not go through Spring's proxy, i.e. Spring is unaware of SomeException
thrown out of method2
. Transaction is not marked for rollback in this case.
Suppose method2
is not annotated with @Transactional
. Invoking it from method1
does go through Spring's proxy, but Spring pays no attention to exceptions thrown. Transaction is not marked for rollback in this case.
Annotating method2
with @Transactional(propagation = Propagation.REQUIRES_NEW)
makes method2
start new transaction. That second transaction is marked for rollback upon exit from method2
but original transaction is unaffected in this case (no exception thrown when exiting from method1
).
In case SomeException
is checked (does not extend RuntimeException), Spring by default does not mark transaction for rollback when intercepting checked exceptions (no exception thrown when exiting from method1
).
See all scenarios tested in this gist.
So I get you are using Eclipse with the M2E plugin. Try to update your Maven configuration : In the Project Explorer, right-click on the project, Maven -> Update project.
If the problem still remains, try to clean your project: right-click on your pom.xml, Run as -> Maven build (the second one). Enter "clean package" in the Goals fields. Check the Skip Tests box. Click on the Run button.
Edit: For your new problem, you need to add Spring MVC to your pom.xml. Add something like the following:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.0.RELEASE</version>
</dependency>
Maybe you have to change the version to match the version of your Spring framework. Take a look here:
http://mvnrepository.com/artifact/org.springframework/spring-webmvc
Array's include?
method accepts any object, not just a string. This should work:
@suggested_horses = []
@suggested_horses << Horse.first(:offset => rand(Horse.count))
while @suggested_horses.length < 8
horse = Horse.first(:offset => rand(Horse.count))
@suggested_horses << horse unless @suggested_horses.include?(horse)
end
html
<div class="text-lg-right text-center">
center in xs and right in lg devices
</div>
The error says it all, change:
ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
to
final ViewPager mPager = (ViewPager) findViewById(R.id.fieldspager);
A more modern version of kaiido's answer using fetch would be:
function toObjectUrl(url) {
return fetch(url)
.then((response)=> {
return response.blob();
})
.then(blob=> {
return URL.createObjectURL(blob);
});
}
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Edit: As pointed out in the comments this will return an object url which points to a file in your local system instead of an actual DataURL so depending on your use case this might not be what you need.
You can look at the following answer to use fetch and an actual dataURL: https://stackoverflow.com/a/50463054/599602
def attributeSelection():
balance = 25
print("Your SP balance is currently 25.")
strength = input("How much SP do you want to put into strength?")
balanceAfterStrength = balance - int(strength)
if balanceAfterStrength == 0:
print("Your SP balance is now 0.")
attributeConfirmation()
elif strength < 0:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif strength > balance:
print("That is an invalid input. Restarting attribute selection. Keep an eye on your balance this time!")
attributeSelection()
elif balanceAfterStrength > 0 and balanceAfterStrength < 26:
print("Ok. You're balance is now at " + str(balanceAfterStrength) + " skill points.")
else:
print("That is an invalid input. Restarting attribute selection.")
attributeSelection()
To add to an existing answer in ASP.NET Core >= 1.0 you can
return Unauthorized();
return Unauthorized(object value);
To pass info to the client you can do a call like this:
return Unauthorized(new { Ok = false, Code = Constants.INVALID_CREDENTIALS, ...});
On the client besides the 401 response you will have the passed data too. For example on most clients you can await response.json()
to get it.
Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.
This is similar to aSeptik's answer, but what about this approach? Wrap the CSS code which you want to disable using JavaScript in <noscript>
tags. That way if javaScript is off, the CSS :hover
will be used, otherwise the JavaScript effect will be used.
Example:
<noscript>
<style type="text/css">
ul#mainFilter a:hover {
/* some CSS attributes here */
}
</style>
</noscript>
<script type="text/javascript">
$("ul#mainFilter a").hover(
function(o){ /* ...do your stuff... */ },
function(o){ /* ...do your stuff... */ });
</script>
jQuery:
$("#tbodyid").empty();
HTML:
<table>
<tbody id="tbodyid">
<tr>
<td>something</td>
</tr>
</tbody>
</table>
Works for me
http://jsfiddle.net/mbsh3/
To delete a job which has not yet run, you need the atrm
command. You can use atq
command to get its number in the at list.
To kill a job which has already started to run, you'll need to grep for it using:
ps -eaf | grep <command name>
and then use kill
to stop it.
A quicker way to do this on most systems is:
pkill <command name>
I tried using React.FormEvent<HTMLSelectElement>
but it led to an error in the editor, even though there is no EventTarget
visible in the code:
The property 'value' does not exist on value of type 'EventTarget'
Then I changed React.FormEvent
to React.ChangeEvent
and it helped:
private changeName(event: React.ChangeEvent<HTMLSelectElement>) {
event.preventDefault();
this.props.actions.changeName(event.target.value);
}
ffmpeg -i movie.mp4 -ss 00:00:03 -t 00:00:08 -async 1 -c copy cut.mp4
Use -c copy for make in instantly. In that case ffmpeg will not re-encode video, just will cut to according size.
ORDER BY column OFFSET 0 ROWS
Surprisingly makes it work, what a strange feature.
A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:
;WITH cte AS (
SELECT .....long select statement here....
)
SELECT * FROM
(
SELECT * FROM
( -- necessary to nest selects for union to work with where & order clauses
SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS
) first
UNION ALL
SELECT * FROM
(
SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS
) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example
So we get all results ordered by MainCol
But the results with MainCol = 1
get ordered by ColX
And the results with MainCol = 0
get ordered by ColY
I guess this is where you are pointing at ..
<div id="divActivites" name="divActivites" style="border:thin">
<textarea id="inActivities" name="inActivities" style="border:solid">
</textarea>
</div>
Well. it must be written as border-width:thin
Here you go with the link (click here) check out the different types of Border-styles
you can also set the border width by writing the width in terms of pixels.. (like border-width:1px), minimum width is 1px.
Try this:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog OptionDialog = builder.create();
background.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
SetBackground();
OptionDialog .dismiss();
}
});
It is important to note that there was a bug with jailbroken phones on 9.0.x which broke url schemes. If you're running a jailbroken device then make sure you update Patcyh in Cydia
Got a gotcha for those with their headspace in Pandas and moving to pyspark
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext
spark_conf = SparkConf().setMaster("local").setAppName("MyAppName")
sc = SparkContext(conf = spark_conf)
sqlContext = SQLContext(sc)
records = [
{"colour": "red"},
{"colour": "blue"},
{"colour": None},
]
pandas_df = pd.DataFrame.from_dict(records)
pyspark_df = sqlContext.createDataFrame(records)
So if we wanted the rows that are not red:
pandas_df[~pandas_df["colour"].isin(["red"])]
Looking good, and in our pyspark DataFrame
pyspark_df.filter(~pyspark_df["colour"].isin(["red"])).collect()
So after some digging, I found this: https://issues.apache.org/jira/browse/SPARK-20617 So to include nothingness in our results:
pyspark_df.filter(~pyspark_df["colour"].isin(["red"]) | pyspark_df["colour"].isNull()).show()
use for each loop for accessing keys in Object or Maps in javascript
for(key in foo){
console.log(key);//for key name in your case it will be bar
console.log(foo[key]);// for key value in your case it will be baz
}
Note: you can also use
Object.keys(foo);
it will give you like this output:
[bar];
It seems that you'll need two fields, a choice list for the currency and a number field for the value.
A common technique in such case is to use a div or span for the display (form fields offscreen), and on click switch to the form elements for editing.
Change your And
s to AndAlso
s
A standard And
will test both expressions. If comp.Container
is Nothing
, then the second expression will raise a NullReferenceException
because you're accessing a property on a null object.
AndAlso
will short-circuit the logical evaluation. If comp.Container
is Nothing
, then the 2nd expression will not be evaluated.
class SuperType {
public static void classMethod(){
System.out.println("Super type class method");
}
public void instancemethod(){
System.out.println("Super Type instance method");
}
}
public class SubType extends SuperType{
public static void classMethod(){
System.out.println("Sub type class method");
}
public void instancemethod(){
System.out.println("Sub Type instance method");
}
public static void main(String args[]){
SubType s=new SubType();
SuperType su=s;
SuperType.classMethod();// Prints.....Super type class method
su.classMethod(); //Prints.....Super type class method
SubType.classMethod(); //Prints.....Sub type class method
}
}
This example for static method overriding
Note: if we call a static method with object reference, then reference type(class) static method will be called, not object class static method.
Static method belongs to class only.
For me to reset the state to its initial state, I wrote the following code:
const appReducers = (state, action) =>
combineReducers({ reducer1, reducer2, user })(
action.type === "LOGOUT" ? undefined : state,
action
);
You can do both in one if you use index
<div *ngFor="let item of items; let myIndex = index>
{{myIndex}}
</div>
With this you can get the best of both worlds.
Try this:
MyContext Context = new MyContext();
Context.YourEntity.Add(obj);
Context.SaveChanges();
int ID = obj._ID;
Try:
$('#mytable').attr('offsetTop')
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
for (int j = 0; j < adapterView.getChildCount(); j++)
adapterView.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
// change the background color of the selected element
view.setBackgroundColor(Color.LTGRAY);
});
Perhaps you might want to save the current selected element in a global variable using the index i.
Ok after doing reverse engineering and a little pixie dust of reflection, one can do this operation on SelectedCells
(at any point) to get all (regardless of selected on one row or many rows) the data from one to many selected cells:
MessageBox.Show(
string.Join(", ", myGrid.SelectedCells
.Select(cl => cl.Item.GetType()
.GetProperty(cl.Column.SortMemberPath)
.GetValue(cl.Item, null)))
);
I tried this on text (string) fields only though a DateTime field should return a value the initiate ToString()
. Also note that SortMemberPath
is not the same as Header
so that should always provide the proper property to reflect off of.
<DataGrid ItemsSource="{Binding MyData}"
AutoGenerateColumns="True"
Name="myGrid"
IsReadOnly="True"
SelectionUnit="Cell"
SelectionMode="Extended">
This tutorial is very useful. To give a quick summary:
Use the CORS package available on Nuget: Install-Package Microsoft.AspNet.WebApi.Cors
In your WebApiConfig.cs
file, add config.EnableCors()
to the Register()
method.
Add an attribute to the controllers you need to handle cors:
[EnableCors(origins: "<origin address in here>", headers: "*", methods: "*")]
If you deal regularly with Attributes in Reflection, it is very, very practical to define some extension methods. You will see that in many projects out there. This one here is one I often have:
public static bool HasAttribute<T>(this ICustomAttributeProvider provider) where T : Attribute
{
var atts = provider.GetCustomAttributes(typeof(T), true);
return atts.Length > 0;
}
which you can use like typeof(Foo).HasAttribute<BarAttribute>();
Other projects (e.g. StructureMap) have full-fledged ReflectionHelper classes that use Expression trees to have a fine syntax to identity e.g. PropertyInfos. Usage then looks like that:
ReflectionHelper.GetProperty<Foo>(x => x.MyProperty).HasAttribute<BarAttribute>()
To Download Specific Branch - Go To Downloads from Left panel, Select Branches on Downloads page. It will list all Branches available. Download your desired branch in zip, gz, or bz2 format.
You can also use a combination of cat
and paste0
cat(paste0("File not supplied.\n", "Usage: ./program F=filename"))
I find this to be more useful when incorporating variables into the printout. For example:
file <- "myfile.txt"
cat(paste0("File not supplied.\n", "Usage: ./program F=", file))
I think you may want to introduce some helper functions to build
your button as well as a Stateful widget along with some property to key off of.
isButtonDisabled
)onPressed
value to either null
or some function onPressed: () {}
isButtonDisabled
as part of this conditional and return either null
or some function.setState(() => isButtonDisabled = true)
to flip the conditional variable.build()
method again with the new state and the button will be rendered with a null
press handler and be disabled.Here's is some more context using the Flutter counter project.
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
bool _isButtonDisabled;
@override
void initState() {
_isButtonDisabled = false;
}
void _incrementCounter() {
setState(() {
_isButtonDisabled = true;
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text("The App"),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Text(
'You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
_buildCounterButton(),
],
),
),
);
}
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _isButtonDisabled ? null : _incrementCounter,
);
}
}
In this example I am using an inline ternary to conditionally set the Text
and onPressed
, but it may be more appropriate for you to extract this into a function (you can use this same method to change the text of the button as well):
Widget _buildCounterButton() {
return new RaisedButton(
child: new Text(
_isButtonDisabled ? "Hold on..." : "Increment"
),
onPressed: _counterButtonPress(),
);
}
Function _counterButtonPress() {
if (_isButtonDisabled) {
return null;
} else {
return () {
// do anything else you may want to here
_incrementCounter();
};
}
}