According to uber-JAR Documentation Approaches: There are three common methods for constructing an uber-JAR:
Unshaded Unpack all JAR files, then repack them into a single JAR. Tools: Maven Assembly Plugin, Classworlds Uberjar
Shaded Same as unshaded, but rename (i.e., "shade") all packages of all dependencies. Tools: Maven Shade Plugin
JAR of JARs The final JAR file contains the other JAR files embedded within. Tools: Eclipse JAR File Exporter, One-JAR.
Based on the proposed solution by @blootsvoets, I edited my jar target this way :
jar {
manifest {
attributes('Main-Class': 'eu.tib.sre.Main')
}
// Include the classpath from the dependencies
from { configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) } }
// This help solve the issue with jar lunch
{
exclude "META-INF/*.SF"
exclude "META-INF/*.DSA"
exclude "META-INF/*.RSA"
}
}
In my case I didn't see any tables under my database on phpMyAdmin
I am using Wamp server
but when I checked the directory under C:\wamp\bin\mysql\mysql5.6.12\data
I found this employed.ibd
when I deleted this file manually I was able to drop
the database from phpMyAdmin
smoothly without any problems.
The correct answer for Java is use a Set. If you already have a List<Customer>
and want to de duplicate it
Set<Customer> s = new HashSet<Customer>(listCustomer);
Otherise just use a Set
implemenation HashSet
, TreeSet
directly and skip the List
construction phase.
You will need to override hashCode()
and equals()
on your domain classes that are put in the Set
as well to make sure that the behavior you want actually what you get. equals()
can be as simple as comparing unique ids of the objects to as complex as comparing every field. hashCode()
can be as simple as returning the hashCode()
of the unique id' String
representation or the hashCode()
.
Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:
<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin" />
<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />
The outcome would be
$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'],
'city' => [ 'Berlin' , 'New York'] ];
To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:
<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin" />
<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />
The outcome would be
$POST = [ 'address' => [
1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
2 => ['street' => 'Wallstreet', 'city' => 'New York'],
]
]
If you're after a promise-based solution, this is @Dmitri's code adapted for that:
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
data => console.log(data)
);
Checkout to temporary branch with last commit
git branch temp HEAD@{1}
Reset last commit
git reset temp
Now, you'll have all files your commit as well as previous commit. Check status of all the files.
git status
Reset your commit files from git stage.
git reset myfile1.js
(so on)
Reattach this commit
git commit -C HEAD@{1}
Add and commit your files to new commit.
To get the fragment instance in a class that extends FragmentActivity:
MyclassFragment instanceFragment=
(MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);
To get the fragment instance in a class that extends Fragment:
MyclassFragment instanceFragment =
(MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);
Extract the hour, look for a leading space, if found replace with a zero;
set hr=%time:~0,2%
if "%hr:~0,1%" equ " " set hr=0%hr:~1,1%
echo Archive_%date:~-4,4%%date:~-10,2%%date:~-7,2%_%hr%%time:~3,2%%time:~6,2%.zip
Let's say you have a class ClassA
which contains a method methodA
defined as:
def methodA(self, arg1, arg2):
# do something
and ObjectA
is an instance of this class.
Now when ObjectA.methodA(arg1, arg2)
is called, python internally converts it for you as:
ClassA.methodA(ObjectA, arg1, arg2)
The self
variable refers to the object itself.
As some people already pointed out, spring-boot 1.4+, has specific namespaces for the four connections pools. By default, hikaricp is used in spring-boot 2+. So you will have to specify the SQL here. The default is SELECT 1
. Here's what you would need for DB2 for example:
spring.datasource.hikari.connection-test-query=SELECT current date FROM sysibm.sysdummy1
Caveat: If your driver supports JDBC4 we strongly recommend not setting this property. This is for "legacy" drivers that do not support the JDBC4 Connection.isValid() API. This is the query that will be executed just before a connection is given to you from the pool to validate that the connection to the database is still alive. Again, try running the pool without this property, HikariCP will log an error if your driver is not JDBC4 compliant to let you know. Default: none
explode — Split a string by a string
Syntax :
array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )
Example :
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
In your example :
$str = "this is string";
$array = explode(' ', $str);
@Component({
selector: 'my-app',
template: `
<div>
<input type="text" placeholder="Search..." [(ngModel)]="searchValue">
<button (click)="clearSearch()">Clear</button>
</div>
`,
})
export class App {
searchValue:string = '';
clearSearch() {
this.searchValue = null;
}
}
Plunker code: Plunker1
@Component({
selector: 'my-app',
template: `
<div>
<input type="text" placeholder="Search..." [value]="searchValue">
<button (click)="clearSearch()">Clear</button>
</div>
`,
})
export class App {
searchValue:string = '';
clearSearch() {
this.searchValue = null;
}
}
Plunker code: Plunker2
Just to add to the solution presented, in my case I wanted to fetch multiple data from Firebase for a list of products. Here is how I did it:
useEffect(() => {
const fn = p => firebase.firestore().doc(`products/${p.id}`).get();
const actions = data.occasion.products.map(fn);
const results = Promise.all(actions);
results.then(data => {
const newProducts = [];
data.forEach(p => {
newProducts.push({ id: p.id, ...p.data() });
});
setProducts(newProducts);
});
}, [data]);
This is an old thread, but I would have thought markdown's blockquotes ('> ') would be best for this:
Use this code to generate horizontal scrolling blocks contents. I got this from here http://www.htmlexplorer.com/2014/02/horizontal-scrolling-webpage-content.html
<html>
<title>HTMLExplorer Demo: Horizontal Scrolling Content</title>
<head>
<style type="text/css">
#outer_wrapper {
overflow: scroll;
width:100%;
}
#outer_wrapper #inner_wrapper {
width:6000px; /* If you have more elements, increase the width accordingly */
}
#outer_wrapper #inner_wrapper div.box { /* Define the properties of inner block */
width: 250px;
height:300px;
float: left;
margin: 0 4px 0 0;
border:1px grey solid;
}
</style>
</head>
<body>
<div id="outer_wrapper">
<div id="inner_wrapper">
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<div class="box">
<!-- Add desired content here -->
HTMLExplorer.com - Explores HTML, CSS, Jquery, XML, PHP, JSON, Javascript
</div>
<!-- more boxes here -->
</div>
</div>
</body>
</html>
I have used this :
request_cmd="$(curl -i -o - --silent -X GET --header 'Accept: application/json' --header 'Authorization: _your_auth_code==' 'https://example.com')"
To get the HTTP status
http_status=$(echo "$request_cmd" | grep HTTP | awk '{print $2}')
echo $http_status
To get the response body I've used this
output_response=$(echo "$request_cmd" | grep body)
echo $output_response
You can also do this:
var x = new object[] {
new { firstName = "john", lastName = "walter" },
new { brand = "BMW" }
};
And if they are the same anonymous type (firstName and lastName), you won't need to cast as object
.
var y = new [] {
new { firstName = "john", lastName = "walter" },
new { firstName = "jill", lastName = "white" }
};
I did what BalusC said but it was not enough for me, I had to clean the Tomcat workdirectory : ( Click right on right on Tomcat in the Servers Tab -> Clean Tomcat Work Directory )
Simple example: Form with textbox and Search button.
If you write "name" into the textbox
and submit form, it will brings you patients with "name" in table.
View:
@using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
UpdateTargetId = "patientList",
LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading
}))
{
string patient_Name = "";
@Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
<input type="submit" value="Search" />
}
@* ... *@
<div id="loader" class=" aletr" style="display:none">
Loading...<img src="~/Images/ajax-loader.gif" />
</div>
@Html.Partial("_patientList") @* this is view with patient table. Same view you will return from controller *@
_patientList.cshtml:
@model IEnumerable<YourApp.Models.Patient>
<table id="patientList" >
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Number)
</th>
</tr>
@foreach (var patient in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => patient.Name)
</td>
<td>
@Html.DisplayFor(modelItem => patient.Number)
</td>
</tr>
}
</table>
Patient.cs
public class Patient
{
public string Name { get; set; }
public int Number{ get; set; }
}
PatientController.cs
public PartialViewResult GetPatients(string patient_Name="")
{
var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
return PartialView("_patientList", patients);
}
And also as TSmith said in comments, don´t forget to install jQuery Unobtrusive Ajax library through NuGet.
mysqldump
has options for CSV formatting:
--fields-terminated-by=name
Fields in the output file are terminated by the given
--lines-terminated-by=name
Lines in the output file are terminated by the given
The name
should contain one of the following:
`--fields-terminated-by`
\t
or "\""
`--fields-enclosed-by=name`
Fields in the output file are enclosed by the given
and
--lines-terminated-by
\r
\n
\r\n
Naturally you should mysqldump each table individually.
I suggest you gather all table names in a text file. Then, iterate through all tables running mysqldump. Here is a script that will dump and gzip 10 tables at a time:
MYSQL_USER=root
MYSQL_PASS=rootpassword
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
SQLSTMT="SELECT CONCAT(table_schema,'.',table_name)"
SQLSTMT="${SQLSTMT} FROM information_schema.tables WHERE table_schema NOT IN "
SQLSTMT="${SQLSTMT} ('information_schema','performance_schema','mysql')"
mysql ${MYSQL_CONN} -ANe"${SQLSTMT}" > /tmp/DBTB.txt
COMMIT_COUNT=0
COMMIT_LIMIT=10
TARGET_FOLDER=/path/to/csv/files
for DBTB in `cat /tmp/DBTB.txt`
do
DB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $1}'`
TB=`echo "${DBTB}" | sed 's/\./ /g' | awk '{print $2}'`
DUMPFILE=${DB}-${TB}.csv.gz
mysqldump ${MYSQL_CONN} -T ${TARGET_FOLDER} --fields-terminated-by="," --fields-enclosed-by="\"" --lines-terminated-by="\r\n" ${DB} ${TB} | gzip > ${DUMPFILE}
(( COMMIT_COUNT++ ))
if [ ${COMMIT_COUNT} -eq ${COMMIT_LIMIT} ]
then
COMMIT_COUNT=0
wait
fi
done
if [ ${COMMIT_COUNT} -gt 0 ]
then
wait
fi
I really like cdmckay's answer, but it does not really look good to check the size in a real time: it is just too slow (2 seconds for me). This is the improved version, which is way faster and more exact, also with an option to choose how big the error can be (default 250,000
, the smaller error is - the longer the calculation is):
function getLocalStorageMaxSize(error) {
if (localStorage) {
var max = 10 * 1024 * 1024,
i = 64,
string1024 = '',
string = '',
// generate a random key
testKey = 'size-test-' + Math.random().toString(),
minimalFound = 0,
error = error || 25e4;
// fill a string with 1024 symbols / bytes
while (i--) string1024 += 1e16;
i = max / 1024;
// fill a string with 'max' amount of symbols / bytes
while (i--) string += string1024;
i = max;
// binary search implementation
while (i > 1) {
try {
localStorage.setItem(testKey, string.substr(0, i));
localStorage.removeItem(testKey);
if (minimalFound < i - error) {
minimalFound = i;
i = i * 1.5;
}
else break;
} catch (e) {
localStorage.removeItem(testKey);
i = minimalFound + (i - minimalFound) / 2;
}
}
return minimalFound;
}
}
To test:
console.log(getLocalStorageMaxSize()); // takes .3s
console.log(getLocalStorageMaxSize(.1)); // takes 2s, but way more exact
This works dramatically faster for the standard error; also it can be much more exact when necessary.
Give links in value of the option tag
<select size="1" name="links" onchange="window.location.href=this.value;">
<option value="http://www.google.com">Google</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
The top voted answer is right and simplest. However, sometimes you may find that not working for some font, but working for others.(Which problem I just came across when dealing with Chinese.)
Solution is do not use "WRAP_CONTENT" only for your TextView, cause there is no extra space for drawing the line. You may set fixed height to your TextView, or use android:paddingVertical with WRAP_CONTENT.
Yes it can. A private constructor would exist to prevent the class from being instantiated, or because construction happens only internally, e.g. a Factory pattern. See here for more information.
use isset
for this purpose
<?php
$index = 1;
if(isset($_POST['filename'])) {
$filename = $_POST['filename'];
echo $filename;
}
?>
Do simply like below....
HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put(yourKey+"message","message");
yourHash.put(yourKey+"timestamp",timestamp);
yourHash.put(yourKey+"count ",count);
yourHash.put(yourKey+"version ",version);
typecast the value while getting back. For ex:
int count = Integer.parseInt(yourHash.get(yourKey+"count"));
//or
int count = Integer.valueOf(yourHash.get(yourKey+"count"));
//or
int count = (Integer)yourHash.get(yourKey+"count"); //or (int)
In my case, I got a huge performance advantage by disabling Rainbow (it's a plugin that is used to color brackets in the code):
Tools -> Options -> Miscellaneous -> Rainbow
(uncheck enabled)
Tested on Netbeans 10 with Java 8.
The problem of serious slowdowns occurred exclusively with particularly large Java files (more than 5000 lines of code), while there was no problem with smaller files (within 1000 or 2000 lines of code).
I made other optimizations, but this one was the most relevant, because it drastically reduced the amount of CPU used.
Change the content-type to "application/x-www-form-urlencoded", i solved the problem.
__init_subclass__
As other answer mentioned you can check the __subclasses__
attribute to get the list of subclasses, since python 3.6 you can modify this attribute creation by overriding the __init_subclass__
method.
class PluginBase:
subclasses = []
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
cls.subclasses.append(cls)
class Plugin1(PluginBase):
pass
class Plugin2(PluginBase):
pass
This way, if you know what you're doing, you can override the behavior of of __subclasses__
and omit/add subclasses from this list.
No, the dataType
option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify
and set the processData
option to false
.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON
object, and although jQuery has .parseJSON
, it has no stringifier included; you'll need another polyfill library.
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
private String getDateTime() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date);
}
I faced this issue and was looking for the solution. Finally I was trying all the options from the https://github.com/mkleehammer/pyodbc/wiki/Connecting-to-SQL-Server-from-Windows , and for my MSSQL 12 only "{ODBC Driver 11 for SQL Server}" works. Just try it one by one. And the second important thing you have to get correct server name, because I thought preciously that I need to set \SQLEXPRESS in all of the cases, but found out that you have to set EXACTLY what you see in the server properties. Example on the screenshot:
UPDATED
For python 3, you should use items()
instead of iteritems()
PYTHON 2
for attr, value in k.__dict__.iteritems():
print attr, value
PYTHON 3
for attr, value in k.__dict__.items():
print(attr, value)
This will print
'names', [a list with names]
'tweet', [a list with tweet]
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})
I would always use a Unix timestamp when working with MySQL and PHP. The main reason for this being the default date method in PHP uses a timestamp as the parameter, so there would be no parsing needed.
To get the current Unix timestamp in PHP, just do time();
and in MySQL do SELECT UNIX_TIMESTAMP();
.
There is no reflection in C++. True. But if the compiler can't provide you the metadata you need, you can provide it yourself.
Let's start by making a property struct:
template<typename Class, typename T>
struct PropertyImpl {
constexpr PropertyImpl(T Class::*aMember, const char* aName) : member{aMember}, name{aName} {}
using Type = T;
T Class::*member;
const char* name;
};
template<typename Class, typename T>
constexpr auto property(T Class::*member, const char* name) {
return PropertyImpl<Class, T>{member, name};
}
Of course, you also can have a property
that takes a setter and getter instead of a pointer to member, and maybe read only properties for calculated value you'd like to serialize. If you use C++17, you can extend it further to make a property that works with lambdas.
Ok, now we have the building block of our compile-time introspection system.
Now in your class Dog
, add your metadata:
struct Dog {
std::string barkType;
std::string color;
int weight = 0;
bool operator==(const Dog& rhs) const {
return std::tie(barkType, color, weight) == std::tie(rhs.barkType, rhs.color, rhs.weight);
}
constexpr static auto properties = std::make_tuple(
property(&Dog::barkType, "barkType"),
property(&Dog::color, "color"),
property(&Dog::weight, "weight")
);
};
We will need to iterate on that list. To iterate on a tuple, there are many ways, but my preferred one is this:
template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
using unpack_t = int[];
(void)unpack_t{(static_cast<void>(f(std::integral_constant<T, S>{})), 0)..., 0};
}
If C++17 fold expressions are available in your compiler, then for_sequence
can be simplified to:
template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
(static_cast<void>(f(std::integral_constant<T, S>{})), ...);
}
This will call a function for each constant in the integer sequence.
If this method don't work or gives trouble to your compiler, you can always use the array expansion trick.
Now that you have the desired metadata and tools, you can iterate through the properties to unserialize:
// unserialize function
template<typename T>
T fromJson(const Json::Value& data) {
T object;
// We first get the number of properties
constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;
// We iterate on the index sequence of size `nbProperties`
for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i) {
// get the property
constexpr auto property = std::get<i>(T::properties);
// get the type of the property
using Type = typename decltype(property)::Type;
// set the value to the member
// you can also replace `asAny` by `fromJson` to recursively serialize
object.*(property.member) = Json::asAny<Type>(data[property.name]);
});
return object;
}
And for serialize:
template<typename T>
Json::Value toJson(const T& object) {
Json::Value data;
// We first get the number of properties
constexpr auto nbProperties = std::tuple_size<decltype(T::properties)>::value;
// We iterate on the index sequence of size `nbProperties`
for_sequence(std::make_index_sequence<nbProperties>{}, [&](auto i) {
// get the property
constexpr auto property = std::get<i>(T::properties);
// set the value to the member
data[property.name] = object.*(property.member);
});
return data;
}
If you want recursive serialization and unserialization, you can replace asAny
by fromJson
.
Now you can use your functions like this:
Dog dog;
dog.color = "green";
dog.barkType = "whaf";
dog.weight = 30;
Json::Value jsonDog = toJson(dog); // produces {"color":"green", "barkType":"whaf", "weight": 30}
auto dog2 = fromJson<Dog>(jsonDog);
std::cout << std::boolalpha << (dog == dog2) << std::endl; // pass the test, both dog are equal!
Done! No need for run-time reflection, just some C++14 goodness!
This code could benefit from some improvement, and could of course work with C++11 with some ajustements.
Note that one would need to write the asAny
function. It's just a function that takes a Json::Value
and call the right as...
function, or another fromJson
.
Here's a complete, working example made from the various code snippet of this answer. Feel free to use it.
As mentionned in the comments, this code won't work with msvc. Please refer to this question if you want a compatible code: Pointer to member: works in GCC but not in VS2015
In a new sheet (where you want to create a new pivot table) press the key combination (Alt+D+P). In the list of data source options choose "Microsoft Excel list of database". Click Next and select the pivot table that you want to use as a source (select starting with the actual headers of the fields). I assume that this range is rather static and if you refresh the source pivot and it changes it's size you would have to re-size the range as well. Hope this helps.
Yes, add the System.Security
assembly, import the System.Security.Cryptography
namespace. Here's a simple example of a symmetric (DES) algorithm encryption:
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
des.GenerateKey();
byte[] key = des.Key; // save this!
ICryptoTransform encryptor = des.CreateEncryptor();
// encrypt
byte[] enc = encryptor.TransformFinalBlock(new byte[] { 1, 2, 3, 4 }, 0, 4);
ICryptoTransform decryptor = des.CreateDecryptor();
// decrypt
byte[] originalAgain = decryptor.TransformFinalBlock(enc, 0, enc.Length);
Debug.Assert(originalAgain[0] == 1);
In the Web Application(not Web Site), I change App_Code*.cs Build Action(file properties) from Compile to Content. then the problem solve.
What you really want is the jQuery URL Parser plugin. With this plugin, getting the value of a specific URL parameter (for the current URL) looks like this:
$.url().param('foo');
If you want an object with parameter names as keys and parameter values as values, you'd just call param()
without an argument, like this:
$.url().param();
This library also works with other urls, not just the current one:
$.url('http://allmarkedup.com?sky=blue&grass=green').param();
$('#myElement').url().param(); // works with elements that have 'src', 'href' or 'action' attributes
Since this is an entire URL parsing library, you can also get other information from the URL, like the port specified, or the path, protocol etc:
var url = $.url('http://allmarkedup.com/folder/dir/index.html?item=value');
url.attr('protocol'); // returns 'http'
url.attr('path'); // returns '/folder/dir/index.html'
It has other features as well, check out its homepage for more docs and examples.
Instead of writing your own URI parser for this specific purpose that kinda works in most cases, use an actual URI parser. Depending on the answer, code from other answers can return 'null'
instead of null
, doesn't work with empty parameters (?foo=&bar=x
), can't parse and return all parameters at once, repeats the work if you repeatedly query the URL for parameters etc.
Use an actual URI parser, don't invent your own.
For those averse to jQuery, there's a version of the plugin that's pure JS.
I was just trying to solve this issue.
I'd tried everything from running as admin through to the suggestions found here and elsewhere; what solved it for me in the end was to check the "relocate files" option in the Files property tab.
Hopefully this helps somebody else.
The way to do this in .NET Core is (at the time of writing) as follows:
public async Task<IActionResult> YourAction(YourModel model)
{
if (ModelState.IsValid)
{
return StatusCode(200);
}
return StatusCode(400);
}
The StatusCode method returns a type of StatusCodeResult which implements IActionResult and can thus be used as a return type of your action.
As a refactor, you could improve readability by using a cast of the HTTP status codes enum like:
return StatusCode((int)HttpStatusCode.OK);
Furthermore, you could also use some of the built in result types. For example:
return Ok(); // returns a 200
return BadRequest(ModelState); // returns a 400 with the ModelState as JSON
Ref. StatusCodeResult - https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.statuscoderesult?view=aspnetcore-2.1
The docs are pretty clear that you pass in a second parameter to specify granularity.
If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.
moment('2010-10-20').isAfter('2010-01-01', 'year'); // false moment('2010-10-20').isAfter('2009-12-31', 'year'); // true
As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.
For your case you would pass 'day'
as the second parameter.
-- Table: "user"
-- DROP TABLE "user";
CREATE TABLE "user"
(
id bigserial NOT NULL,
name text NOT NULL,
email character varying(20) NOT NULL,
password text NOT NULL,
CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "user"
OWNER TO postgres;
In my case, I had made a stupid typo in the shebang.
So in case someone else on with fat fingers stumbles across this question:
Whoops: #!/usr/local/bin ruby
I meant to write: #!/usr/bin/env ruby
The vague error ZSH gives sent me down the wrong path:
ZSH: zsh: permission denied: ./foo.rb
Bash: bash: ./foo.rb: /usr/local/bin: bad interpreter: Permission denied
Here is a practical addition to the answers of PierreBdR and Moe:
dir()
seems to be enough.For old-style classes, we can at least do what a standard module does to support tab completion: in addition to dir()
, look for __class__
, and then to go for its __bases__
:
# code borrowed from the rlcompleter module
# tested under Python 2.6 ( sys.version = '2.6.5 (r265:79063, Apr 16 2010, 13:09:56) \n[GCC 4.4.3]' )
# or: from rlcompleter import get_class_members
def get_class_members(klass):
ret = dir(klass)
if hasattr(klass,'__bases__'):
for base in klass.__bases__:
ret = ret + get_class_members(base)
return ret
def uniq( seq ):
""" the 'set()' way ( use dict when there's no set ) """
return list(set(seq))
def get_object_attrs( obj ):
# code borrowed from the rlcompleter module ( see the code for Completer::attr_matches() )
ret = dir( obj )
## if "__builtins__" in ret:
## ret.remove("__builtins__")
if hasattr( obj, '__class__'):
ret.append('__class__')
ret.extend( get_class_members(obj.__class__) )
ret = uniq( ret )
return ret
(Test code and output are deleted for brevity, but basically for new-style objects we seem to have the same results for get_object_attrs()
as for dir()
, and for old-style classes the main addition to the dir()
output seem to be the __class__
attribute.)
From the answer here, spark.sql.shuffle.partitions
configures the number of partitions that are used when shuffling data for joins or aggregations.
spark.default.parallelism
is the default number of partitions in RDD
s returned by transformations like join
, reduceByKey
, and parallelize
when not set explicitly by the user. Note that spark.default.parallelism
seems to only be working for raw RDD
and is ignored when working with dataframes.
If the task you are performing is not a join or aggregation and you are working with dataframes then setting these will not have any effect. You could, however, set the number of partitions yourself by calling df.repartition(numOfPartitions)
(don't forget to assign it to a new val
) in your code.
To change the settings in your code you can simply do:
sqlContext.setConf("spark.sql.shuffle.partitions", "300")
sqlContext.setConf("spark.default.parallelism", "300")
Alternatively, you can make the change when submitting the job to a cluster with spark-submit
:
./bin/spark-submit --conf spark.sql.shuffle.partitions=300 --conf spark.default.parallelism=300
Delete your .git folder, and reinitialize the git with git init, in my case that's work , because git add command staging the folder and the files in .git folder, if you close CLI after the commit , there will be double folder in staging area that make git system throw this issue.
You can use the :checkbox
and :checked
pseudo-selectors and the .class
selector, with that you will make sure that you are getting the right elements, only checked checkboxes with the class you specify.
Then you can easily use the Traversing/map method to get an array of values:
var values = $('input:checkbox:checked.group1').map(function () {
return this.value;
}).get(); // ["18", "55", "10"]
you can use this add string to list on a button click
final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
int k=sp.getCount();
String a1[]=new String[k+1];
for(int i=0;i<k;i++)
a1[i]=sp.getItemAtPosition(i).toString();
a1[k]=et.getText().toString();
ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
sp.setAdapter(ats);
}
});
So on a button click it will get string from edittext and store in listitem. you can change this to your needs.
This code works fine with me
<script type="text/javascript">
$(document).ready(function(){
$("#select_all").change(function(){
$(".checkbox_class").prop("checked", $(this).prop("checked"));
});
});
</script>
you only need to add class checkbox_class to all checkbox
Easy and simple :D
I'd argue that most of the solutions shown here suffer from being over-engineerd. Probably the most simple way to check if a value is of type [object Object]
is to check against the .constructor
property of it:
function isObject (a) { return a != null && a.constructor === Object; }
or even shorter with arrow-functions:
const isObject = a => a != null && a.constructor === Object;
The a != null
part is necessary because one might pass in null
or undefined
and you cannot extract a constructor property from either of these.
It works with any object created via:
Object
constructor{}
Another neat feature of it, is it's ability to give correct reports for custom classes which make use of Symbol.toStringTag
. For example:
class MimicObject {
get [Symbol.toStringTag]() {
return 'Object';
}
}
The problem here is that when calling Object.prototype.toString
on an instance of it, the false report [object Object]
will be returned:
let fakeObj = new MimicObject();
Object.prototype.toString.call(fakeObj); // -> [object Object]
But checking against the constructor gives a correct result:
let fakeObj = new MimicObject();
fakeObj.constructor === Object; // -> false
To complete a bit more previous great answers, you need to be aware that forms leverage observables to detect and handle value changes. It's something really important and powerful. Both Mark and dfsq described this aspect in their answers.
Observables allow not only to use the subscribe
method (something similar to the then
method of promises in Angular 1). You can go further if needed to implement some processing chains for updated data in forms.
I mean you can specify at this level the debounce time with the debounceTime
method. This allows you to wait for an amount of time before handling the change and correctly handle several inputs:
this.form.valueChanges
.debounceTime(500)
.subscribe(data => console.log('form changes', data));
You can also directly plug the processing you want to trigger (some asynchronous one for example) when values are updated. For example, if you want to handle a text value to filter a list based on an AJAX request, you can leverage the switchMap
method:
this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
You even go further by linking the returned observable directly to a property of your component:
this.list = this.textValue.valueChanges
.debounceTime(500)
.switchMap(data => this.httpService.getListValues(data))
.subscribe(data => console.log('new list values', data));
and display it using the async
pipe:
<ul>
<li *ngFor="#elt of (list | async)">{{elt.name}}</li>
</ul>
Just to say that you need to think the way to handle forms differently in Angular2 (a much more powerful way ;-)).
Hope it helps you, Thierry
To amend the "git config" answer just a bit:
git config --global --add alias.root '!pwd -P'
and get the path cleaned up. Very nice.
The examples above work fine when there is only one delimiter, but it doesn't scale well for multiple delimiters. Note that this will only work for SQL Server 2016 and above.
/*Some Sample Data*/
DECLARE @mytable TABLE ([id] VARCHAR(10), [name] VARCHAR(1000));
INSERT INTO @mytable
VALUES ('1','John/Smith'),('2','Jane/Doe'), ('3','Steve'), ('4','Bob/Johnson')
/*Split based on delimeter*/
SELECT P.id, [1] 'FirstName', [2] 'LastName', [3] 'Col3', [4] 'Col4'
FROM(
SELECT A.id, X1.VALUE, ROW_NUMBER() OVER (PARTITION BY A.id ORDER BY A.id) RN
FROM @mytable A
CROSS APPLY STRING_SPLIT(A.name, '/') X1
) A
PIVOT (MAX(A.[VALUE]) FOR A.RN IN ([1],[2],[3],[4],[5])) P
One solution could be to wrap the options inside optgroup:
optgroup { font-size:40px; }
_x000D_
<select>
<optgroup>
<option selected="selected" class="service-small">Service area?</option>
<option class="service-small">Volunteering</option>
<option class="service-small">Partnership & Support</option>
<option class="service-small">Business Services</option>
</optgroup>
</select>
_x000D_
This is an old question I know but um....
n=n-(n*2)
This is an easy way to create custom events and raise them. You create a delegate and an event in the class you are throwing from. Then subscribe to the event from another part of your code. You have already got a custom event argument class so you can build on that to make other event argument classes. N.B: I have not compiled this code.
public partial class Form1 : Form
{
private TestClass _testClass;
public Form1()
{
InitializeComponent();
_testClass = new TestClass();
_testClass.OnUpdateStatus += new TestClass.StatusUpdateHandler(UpdateStatus);
}
private void UpdateStatus(object sender, ProgressEventArgs e)
{
SetStatus(e.Status);
}
private void SetStatus(string status)
{
label1.Text = status;
}
private void button1_Click_1(object sender, EventArgs e)
{
TestClass.Func();
}
}
public class TestClass
{
public delegate void StatusUpdateHandler(object sender, ProgressEventArgs e);
public event StatusUpdateHandler OnUpdateStatus;
public static void Func()
{
//time consuming code
UpdateStatus(status);
// time consuming code
UpdateStatus(status);
}
private void UpdateStatus(string status)
{
// Make sure someone is listening to event
if (OnUpdateStatus == null) return;
ProgressEventArgs args = new ProgressEventArgs(status);
OnUpdateStatus(this, args);
}
}
public class ProgressEventArgs : EventArgs
{
public string Status { get; private set; }
public ProgressEventArgs(string status)
{
Status = status;
}
}
Bash's set
will parse all output into position parameters.
For instance, with set $(free -h)
command, echo $7
will show "Mem:"
Imo use cases for ng-container
are simple replacements for which a custom template/component would be overkill. In the API doc they mention the following
use a ng-container to group multiple root nodes
and I guess that's what it is all about: grouping stuff.
Be aware that the ng-container
directive falls away instead of a template where its directive wraps the actual content.
You can get the index of the select box by using : .prop() method of JQuery
Check This :
<!doctype html>
<html>
<head>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function check(){
alert($("#NumberSelector").prop('selectedIndex'));
alert(document.getElementById("NumberSelector").value);
}
</script>
</head>
<body bgcolor="yellow">
<div>
<select id="NumberSelector" onchange="check()">
<option value="Its Zero">Zero</option>
<option value="Its One">One</option>
<option value="Its Two">Two</option>
<option value="Its Three">Three</option>
<option value="Its Four">Four</option>
<option value="Its Five">Five</option>
<option value="Its Six">Six</option>
<option value="Its Seven">Seven</option>
</select>
</div>
</body>
</html>
Turns out that I had this problem and it was because I used "tabs" to indent lines instead of spaces. Just posting, in case it helps anyone.
If you're using WordPress, I created a plugin that can do this & much more without needing to know how to code anything. All you need to do is add the selector of the link(s) that you want to disable & then choose "Disable all links with this selector in a new tab." from the dropdown menu that appears and click update.
Click here to view a gif that demonstrates this
You can get the free version from the WordPress.org Plugin repository to try it out.
Lets go over 4 methods
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l.insert(0, 5)
>>> l
[5, 0, 1, 2, 3, 4]
>>>
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = [5] + l
>>> l
[5, 0, 1, 2, 3, 4]
>>>
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l[:0] = [5]
>>> l
[5, 0, 1, 2, 3, 4]
>>>
>>>
>>> from collections import deque
>>>
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = deque(l)
>>> l.appendleft(5)
>>> l = list(l)
>>> l
[5, 0, 1, 2, 3, 4]
>>>
Project -> Clean seemed to work for me on on JRE 8
This works in my case. I hope you can extract meaning out of it.
//div[text()='building1' and @class='wrap']/ancestor::tr/td/div/div[@class='x-grid-row-checker']
$.each()
works for objects and arrays both:
var data = { "programs": [ { "name":"zonealarm", "price":"500" }, { "name":"kaspersky", "price":"200" } ] };
$.each(data.programs, function (i) {
$.each(data.programs[i], function (key, val) {
alert(key + val);
});
});
...and since you will get the current array element as second argument:
$.each(data.programs, function (i, currProgram) {
$.each(currProgram, function (key, val) {
alert(key + val);
});
});
This CSS is what finally worked for me in conjunction with a linefeed in my editor:
.tooltip-inner {
white-space: pre-wrap;
}
Found here: How to make Twitter bootstrap tooltips have multiple lines?
You can also use now()
in Postgres. The problem is you can't add/subtract integers from timestamp
or timestamptz
. You can either do as Mark Byers suggests and subtract an interval, or use the date
type which does allow you to add/subtract integers
SELECT now()::date + 100 AS date1, current_date - 100 AS date2
The question has already been answered but I thought I would also let you know that rather than using the native PHP $_POST I reccomend you use the CodeIgniter input class so your controller code would be
function post_action()
{
if($this->input->post('textbox') == "")
{
$message = "You can't send empty text";
}
else
{
$message = $this->input->post('textbox');
}
echo $message;
}
First : npm install mongoose-timestamp
Next: let Timestamps = require('mongoose-timestamp')
Next: let MySchema = new Schema
Next: MySchema.plugin(Timestamps)
Next : const Collection = mongoose.model('Collection',MySchema)
Then you can use the Collection.createdAt
or Collection.updatedAt
anywhere your want.
Created on: Date Of The Week Month Date Year 00:00:00 GMT
Time is in this format.
This is how you do it
SELECT ID,NAME, (C_COUNTS+F_COUNTS) AS SUM_COUNTS
FROM TABLE
ORDER BY SUM_COUNTS LIMIT 20
The SUM function will add up all rows, so the order by
clause is useless, instead you will have to use the group by
clause.
Use a semaphore with a count that is equal to the number of readers. Let each reader take one count of the semaphore in order to read, that way they can all read at the same time. Then let the writer take ALL the semaphore counts prior to writing. This causes the writer to wait for all reads to finish and then block out reads while writing.
Here's my implementation in Elixir
defmodule Geo do
@earth_radius_km 6371
@earth_radius_sm 3958.748
@earth_radius_nm 3440.065
@feet_per_sm 5280
@d2r :math.pi / 180
def deg_to_rad(deg), do: deg * @d2r
def great_circle_distance(p1, p2, :km), do: haversine(p1, p2) * @earth_radius_km
def great_circle_distance(p1, p2, :sm), do: haversine(p1, p2) * @earth_radius_sm
def great_circle_distance(p1, p2, :nm), do: haversine(p1, p2) * @earth_radius_nm
def great_circle_distance(p1, p2, :m), do: great_circle_distance(p1, p2, :km) * 1000
def great_circle_distance(p1, p2, :ft), do: great_circle_distance(p1, p2, :sm) * @feet_per_sm
@doc """
Calculate the [Haversine](https://en.wikipedia.org/wiki/Haversine_formula)
distance between two coordinates. Result is in radians. This result can be
multiplied by the sphere's radius in any unit to get the distance in that unit.
For example, multiple the result of this function by the Earth's radius in
kilometres and you get the distance between the two given points in kilometres.
"""
def haversine({lat1, lon1}, {lat2, lon2}) do
dlat = deg_to_rad(lat2 - lat1)
dlon = deg_to_rad(lon2 - lon1)
radlat1 = deg_to_rad(lat1)
radlat2 = deg_to_rad(lat2)
a = :math.pow(:math.sin(dlat / 2), 2) +
:math.pow(:math.sin(dlon / 2), 2) *
:math.cos(radlat1) * :math.cos(radlat2)
2 * :math.atan2(:math.sqrt(a), :math.sqrt(1 - a))
end
end
The negation pseudo-class seems to be what you are looking for.
table:not(.dojoxGrid) {color:red;}
You need:
public int sumAll(int...numbers){
int result = 0;
for(int i = 0 ; i < numbers.length; i++) {
result += numbers[i];
}
return result;
}
Then call the method and give it as many int values as you need:
int result = sumAll(1,4,6,3,5,393,4,5);//.....
System.out.println(result);
In my case, I didn't want to keep the files, so this worked for me:
Git 2.11 and newer:
git clean -d -fx .
Older Git:
git clean -d -fx ""
Reference: http://www.kernel.org/pub/software/scm/git/docs/git-clean.html
-x means ignored files are also removed as well as files unknown to git.
-d means remove untracked directories in addition to untracked files.
-f is required to force it to run.
This might be more desirable, that is use float instead
SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC
Configuring this worked for me: -vmargs -Xms1536m -Xmx2048m -XX:MaxPermSize=1024m on Eclipse Java Photon June 2018
Running Windows 10, 8 GB ram and 64 bit. You can extend -Xmx2048 -XX:MaxpermSize= 1024m to 4096m too, if your computer has good ram.Mine worked well.
You need to set M2 and M2_HOME. I was facing same problem and issue was I had put one extra space in PATH variable after semicolon. Just removed space from path and it worked. (Windows 7 machine)
Another good trick is to go into UTF8 mode in your editor so that you can actually see these funny characters and delete them yourself.
try this
function getmoviename(id)
{
var p_url= yoururl from where you get movie name,
jQuery.ajax({
type: "GET",
url: p_url,
data: "id=" + id,
success: function(data) {
$('#summary').html(data);
}
});
}
and you html part is
<a href="javascript:void(0);" class="movie" onclick="getmoviename(youridvariable)">
Name of movie</a>
<div id="summary">Here is summary of movie</div>
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
Linking to local resources is disabled in all modern browsers due to security restrictions.
For Firefox:
For security purposes, Mozilla applications block links to local files (and directories) from remote files. This includes linking to files on your hard drive, on mapped network drives, and accessible via Uniform Naming Convention (UNC) paths. This prevents a number of unpleasant possibilities, including:
- Allowing sites to detect your operating system by checking default installation paths
- Allowing sites to exploit system vulnerabilities (e.g., C:\con\con in Windows 95/98)
- Allowing sites to detect browser preferences or read sensitive data
for IE:
Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.
for Opera (in the context of a security advisory, I'm sure there is a more canonical link for this):
As a security precaution, Opera does not allow Web pages to link to files on the user's local disk
function mailValidation(val) {
var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!expr.test(val)) {
$('#errEmail').text('Please enter valid email.');
}
else {
$('#errEmail').hide();
}
}
AWS EC2 install running python34:
sudo yum install python34-devel
You reference a Linux distribution, so you need to install the readline development libraries
On Debian based platforms, like Ubuntu, you can run:
sudo apt-get install libreadline-dev
and that should install the correct headers in the correct places,.
If you use a platform with yum
, like SUSE, then the command should be:
yum install readline-devel
You could add some logging to the Global.asax in Session_Start and Application_Start to track what's going on with the user's Session and the Application as a whole.
Also, watch out of you're running in Web Farm mode (multiple IIS threads defined in the application pool) or load balancing because the user can end up hitting a different server that does not have the same memory. If this is the case, you can switch the Session mode to SQL Server.
If you want a true onChangedListener(). Store the initial value in the handler and check to see if it has changed. It is simple and does not require a global variable. Works if you have more than one spinner on the page.
String initialValue = // get from Database or your object
mySpinner.setOnItemSelectedListener(new SpinnerSelectedListener(initialValue));
...
protected class SpinnerSelectedListener implements AdapterView.OnItemSelectedListener {
private SpinnerSelectedListener() {
super();
}
public SpinnerSelectedListener(String initialValue) {
this();
this.initialValue = initialValue;
}
private String initialValue;
// getter and setter removed.
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String newValue = (String) spinHeight.getItemAtPosition(position);
if (newValue.equals(initialValue) == false) {
// Add your code here. The spinner has changed value.
// Maybe useful.
// initialValue = newValue;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Maybe useful.
// initialValue = null;
}
}
Objects are your friend, use them.
The character set is part of the locale, which is determined by the value of NLS_LANG
. As the documentation makes clear this is an operating system variable:
NLS_LANG
is set as an environment variable on UNIX platforms.NLS_LANG
is set in the registry on Windows platforms.
Now we can use ALTER SESSION
to change the values for a couple of locale elements, NLS_LANGUAGE and NLS_TERRITORY. But not, alas, the character set. The reason for this discrepancy is - I think - that the language and territory simply effect how Oracle interprets the stored data, e.g. whether to display a comma or a period when displaying a large number. Wheareas the character set is concerned with how the client application renders the displayed data. This information is picked up by the client application at startup time, and cannot be changed from within.
You cannot change a table while the INSERT trigger is firing. The INSERT might do some locking which could result in a deadlock. Also, updating the table from a trigger would then cause the same trigger to fire again in an infinite recursive loop. Both of these reasons are why MySQL prevents you from doing this.
However, depending on what you're trying to achieve, you can access the new values by using NEW.fieldname or even the old values--if doing an UPDATE--with OLD.
If you had a row named full_brand_name
and you wanted to use the first two letters as a short name in the field small_name
you could use:
CREATE TRIGGER `capital` BEFORE INSERT ON `brandnames`
FOR EACH ROW BEGIN
SET NEW.short_name = CONCAT(UCASE(LEFT(NEW.full_name,1)) , LCASE(SUBSTRING(NEW.full_name,2)))
END
Use the onsubmit
event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault
method to disable the form submission.
For example:
<script>
function doSomething() {
alert('Form submitted!');
return false;
}
</script>
<form onsubmit="return doSomething();" class="my-form">
<input type="submit" value="Submit">
</form>
This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:
<script>
$('.my-form').on('submit', function () {
alert('Form submitted!');
return false;
});
</script>
<form class="my-form">
<input type="submit" value="Submit">
</form>
I know this is a little old but for the sake of folks like myself from google who didn't find a complete answer here. Here are some extracts from my app which put the arrows inside a custom listview....
Location loc; //Will hold lastknown location
Location wptLoc = new Location(""); // Waypoint location
float dist = -1;
float bearing = 0;
float heading = 0;
float arrow_rotation = 0;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc == null) { //No recent GPS fix
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(true);
criteria.setCostAllowed(true);
criteria.setSpeedRequired(false);
loc = lm.getLastKnownLocation(lm.getBestProvider(criteria, true));
}
if(loc != null) {
wptLoc.setLongitude(cursor.getFloat(2)); //Cursor is from SimpleCursorAdapter
wptLoc.setLatitude(cursor.getFloat(3));
dist = loc.distanceTo(wptLoc);
bearing = loc.bearingTo(wptLoc); // -180 to 180
heading = loc.getBearing(); // 0 to 360
// *** Code to calculate where the arrow should point ***
arrow_rotation = (360+((bearing + 360) % 360)-heading) % 360;
}
I willing to bet it could be simplified but it works! LastKnownLocation was used since this code was from new SimpleCursorAdapter.ViewBinder()
onLocationChanged contains a call to notifyDataSetChanged();
code also from new SimpleCursorAdapter.ViewBinder() to set image rotation and listrow colours (only applied in a single columnIndex mind you)...
LinearLayout ll = ((LinearLayout)view.getParent());
ll.setBackgroundColor(bc);
int childcount = ll.getChildCount();
for (int i=0; i < childcount; i++){
View v = ll.getChildAt(i);
if(v instanceof TextView) ((TextView)v).setTextColor(fc);
if(v instanceof ImageView) {
ImageView img = (ImageView)v;
img.setImageResource(R.drawable.ic_arrow);
Matrix matrix = new Matrix();
img.setScaleType(ScaleType.MATRIX);
matrix.postRotate(arrow_rotation, img.getWidth()/2, img.getHeight()/2);
img.setImageMatrix(matrix);
}
In case you're wondering I did away with the magnetic sensor dramas, wasn't worth the hassle in my case. I hope somebody finds this as useful as I usually do when google brings me to stackoverflow!
Yes it definitely possible. The question here probably assumes Angular 1.x, but for future reference I am including an Angular 2 example:
Conceptually all you have to do is create a recursive template:
<ul>
<li *for="#dir of directories">
<span><input type="checkbox" [checked]="dir.checked" (click)="dir.check()" /></span>
<span (click)="dir.toggle()">{{ dir.name }}</span>
<div *if="dir.expanded">
<ul *for="#file of dir.files">
{{file}}
</ul>
<tree-view [directories]="dir.directories"></tree-view>
</div>
</li>
</ul>
You then bind a tree object to the template and let Angular work its magic. This concept is obviously applicable to Angular 1.x as well.
Here is a complete example: http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0
The location of docker logs has changed for Mac OSX to ~/Library/Containers/com.docker.docker/Data/com.docker.driver.amd64-linux/console-ring
I got the same error when I added the applicationinitialization module with lots of initializationpages and deployed it on Azure app. The issue turned out to be duplicate entries in my applicationinitialization module. I din't see any errors in the logs so it was hard to troubleshoot. Below is an example of the error code:
<configuration>
<system.webServer>
<applicationInitialization doAppInitAfterRestart="true" skipManagedModules="true">
<add initializationPage="/init1.aspx?call=2"/>
<add initializationPage="/init1.aspx?call=2" />
</applicationInitialization>
</system.webServer>
Make sure there are no duplicate entries because those will be treated as duplicate keys which are not allowed and will result in "Cannot add duplicate collection entry" error for web.config.
Can you remove the headers element in @RequestMapping and try..
Like
@RequestMapping(value="/getTemperature/{id}", method = RequestMethod.GET)
I guess spring does an 'contains check' rather than exact match for accept headers. But still, worth a try to remove the headers element and check.
"foobar".gsub(/(o+)/){|s|s+'ball'}
#=> "fooballbar"
You can do it like this
new DirectoryInfo(path).GetFiles().Where(Current => Regex.IsMatch(Current.Extension, "\\.(aspx|ascx)", RegexOptions.IgnoreCase)
I've rearranged the selected answer, used pointers for arrays and user input for number count is not pre-defined.
#include <iostream>
using namespace std;
void merge(int*, int*, int, int, int);
void mergesort(int *a, int*b, int start, int end) {
int halfpoint;
if (start < end) {
halfpoint = (start + end) / 2;
mergesort(a, b, start, halfpoint);
mergesort(a, b, halfpoint + 1, end);
merge(a, b, start, halfpoint, end);
}
}
void merge(int *a, int *b, int start, int halfpoint, int end) {
int h, i, j, k;
h = start;
i = start;
j = halfpoint + 1;
while ((h <= halfpoint) && (j <= end)) {
if (a[h] <= a[j]) {
b[i] = a[h];
h++;
} else {
b[i] = a[j];
j++;
}
i++;
}
if (h > halfpoint) {
for (k = j; k <= end; k++) {
b[i] = a[k];
i++;
}
} else {
for (k = h; k <= halfpoint; k++) {
b[i] = a[k];
i++;
}
}
// Write the final sorted array to our original one
for (k = start; k <= end; k++) {
a[k] = b[k];
}
}
int main(int argc, char** argv) {
int num;
cout << "How many numbers do you want to sort: ";
cin >> num;
int a[num];
int b[num];
for (int i = 0; i < num; i++) {
cout << (i + 1) << ": ";
cin >> a[i];
}
// Start merge sort
mergesort(a, b, 0, num - 1);
// Print the sorted array
cout << endl;
for (int i = 0; i < num; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
An optional means that Swift is not entirely sure if the value corresponds to the type: for example, Int? means that Swift is not entirely sure whether the number is an Int.
To remove it, there are three methods you could employ.
1) If you are absolutely sure of the type, you can use an exclamation mark to force unwrap it, like this:
// Here is an optional variable:
var age: Int?
// Here is how you would force unwrap it:
var unwrappedAge = age!
If you do force unwrap an optional and it is equal to nil, you may encounter this crash error:
This is not necessarily safe, so here's a method that might prevent crashing in case you are not certain of the type and value:
Methods 2 and three safeguard against this problem.
2) The Implicitly Unwrapped Optional
if let unwrappedAge = age {
// continue in here
}
Note that the unwrapped type is now Int, rather than Int?.
3) The guard statement
guard let unwrappedAge = age else {
// continue in here
}
From here, you can go ahead and use the unwrapped variable. Make sure only to force unwrap (with an !), if you are sure of the type of the variable.
Good luck with your project!
The AWS Billing Management Console will give you a Month-to-Date Spend by Service rundown.
I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo
list was coming as empty. So, I tried the following and it worked for me.
Type type = typeof(Record);
FieldInfo[] properties = type.GetFields();
foreach (FieldInfo property in properties) {
Debug.LogError(property.Name);
}
Another super clear way of doing this could be as follows:
let modifiedString = originalString .split('').reverse().join('') .replace('_', '') .split('').reverse().join('')
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.
u can try this..
<div id="placeholder" style="width:auto;height:auto"></div>
width and height depends on your flot or graph..
hope u want this...
or
By clicking, u can use this by jquery
$("#placeholder").css("width", $(window).width());
$("#placeholder").css("height", $(window).height());
You can't use variable names to bind columns or other system objects, you need dynamic sql
DECLARE @value varchar(10)
SET @value = 'intStep'
DECLARE @sqlText nvarchar(1000);
SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)
I answered a similar question before on how to run a Docker container inside Docker.
To run docker inside docker is definitely possible. The main thing is that you
run
the outer container with extra privileges (starting with--privileged=true
) and then install docker in that container.Check this blog post for more info: Docker-in-Docker.
One potential use case for this is described in this entry. The blog describes how to build docker containers within a Jenkins docker container.
However, Docker inside Docker it is not the recommended approach to solve this type of problems. Instead, the recommended approach is to create "sibling" containers as described in this post
So, running Docker inside Docker was by many considered as a good type of solution for this type of problems. Now, the trend is to use "sibling" containers instead. See the answer by @predmijat on this page for more info.
This is how I manage to "download" it:
In Firefox the M3U file appeared as of type application/vnd.apple.mpegurl
The contents of the M3U file would look like:
Open VLC medial player and use the Media => Convert option. Use your (saved) M3U file as the source:
@dev-nish Your code works with little tweaks in them. make the
const navigationExtras: NavigationExtras = {
state: {
transd: 'TRANS001',
workQueue: false,
services: 10,
code: '003'
}
};
into
let navigationExtras: NavigationExtras = {
state: {
transd: '',
workQueue: ,
services: ,
code: ''
}
};
then if you want to specifically sent a type of data, for example, JSON as a result of a form fill you can send the data in the same way as explained before.
SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.
SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.
Some useful links can be found below:
Disclosure: I am the tech lead on the SciChart project!
A wrapper class doesn't necessarily need to wrap another class. It might be a API class wrapping functionality in e.g. a dll file.
For example it might be very useful to create a dll wrapper class, which takes care of all dll initialization and cleanup and create class methods that wrap function pointers created from e.g. GetProcAddress()
.
Cheers !
Put 0 as default in SQL or add 0 into your area of table
Here is my approach- download the freemind and CAM XML Template Editor.
Then open CAM XML, create new Template from XML, View -> View Template As Mind Map
Pros of this solution:
Cons:
I've seen it done. I wouldn't recommend it. C++ originally started this way as a preprocessor that produced C code as an intermediate step.
Essentially what you end up doing is create a dispatch table for all of your methods where you store your function references. Deriving a class would entail copying this dispatch table and replacing the entries that you wanted to override, with your new "methods" having to call the original method if it wants to invoke the base method. Eventually, you end up rewriting C++.
Try
public bool IsDivisible(int x, int n)
{
return (x % n) == 0;
}
The modulus operator % returns the remainder after dividing x by n which will always be 0 if x is divisible by n.
For more information, see the % operator on MSDN.
So I figured out what is wrong with this statement:
Import-Csv H:\Programs\scripts\SomeText.csv |`
(Original)
Import-Csv H:\Programs\scripts\SomeText.csv -Delimiter "|"
(Proposed, You must use quotations; otherwise, it will not work and ISE will give you an error)
It requires the -Delimiter "|"
, in order for the variable to be populated with an array of items. Otherwise, Powershell ISE does not display the list of items.
I cannot say that I would recommend the |
operator, since it is used to pipe cmdlets into one another.
I still cannot get the if statement to return true and output the values entered via the prompt.
If anyone else can help, it would be great. I still appreciate the post, it has been very helpful!
I know you said that you couldn't install any software, but I'm not sure how tight that restriction is. Anyway, I had the same issue (trying to concatenate two files with presumably the same headers) and I thought I'd provide an alternative answer for others who arrive at this page, since it worked just great for me.
After trying a whole bunch of commands in windows and being severely frustrated, and also trying all sorts of graphical editors that promised to be able to open large files, but then couldn't, I finally got back to my Linux roots and opened my Cygwin prompt. Two commands:
cp file1.csv out.csv
tail -n+2 file2.csv >> out.csv
For file1.csv
800MB and file2.csv
400MB, those two commands took under 5 seconds on my machine. In a Cygwin prompt, no less. I thought Linux commands were supposed to be slow in Cygwin but that approach took far less effort and was way easier than any windows approach I could find.
Your problem is that the indices returned by match.start()
correspond to the position of the character as it appeared in the original string when you matched it; however, as you rewrite the string c
every time, these indices become incorrect.
The best approach to solve this is to use replaceAll
, for example:
System.out.println(c.replaceAll("[^a-zA-Z0-9]", ""));
A more simple way is to use fire fox dev tools, console.log(yourObject) -> right click on object -> select "copy object" -> paste results into notepad
thanks.
Also note that a result code in the second column refers to the properties of the file. For example:
U filename.1
U filename.2
UU filename.3
filename.1: the file was updated
filename.2: a property or properties on the file (such as svn:keywords) was updated
filename.3: both the file and its properties were updated
There's a width="400"
on the table, remove it and it will work...
The block approach avoids running the lookup algorithm for every key:
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id value, BOOL* stop) {
NSLog(@"%@ => %@", key, value);
}];
Even though NSDictionary
is implemented as a hashtable (which means that the cost of looking up an element is O(1)
), lookups still slow down your iteration by a constant factor.
My measurements show that for a dictionary d
of numbers ...
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
for (int i = 0; i < 5000000; ++i) {
NSNumber* value = @(i);
dict[value.stringValue] = value;
}
... summing up the numbers with the block approach ...
__block int sum = 0;
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSNumber* value, BOOL* stop) {
sum += value.intValue;
}];
... rather than the loop approach ...
int sum = 0;
for (NSString* key in dict)
sum += [dict[key] intValue];
... is about 40% faster.
EDIT: The new SDK (6.1+) appears to optimise loop iteration, so the loop approach is now about 20% faster than the block approach, at least for the simple case above.
jQuery("input:radio[name=myradiobutton]:checked").val();
JavaScript is a dynamic language. You could just add it to the object itself.
var marker = new google.maps.Marker(markerOptions);
marker.metadata = {type: "point", id: 1};
Also, because all v3 objects extend MVCObject()
. You can use:
marker.setValues({type: "point", id: 1});
// or
marker.set("type", "point");
marker.set("id", 1);
var val = marker.get("id");
Your code can get messy fast when dealing with CSS3 transitions. I would recommend using a plugin such as jQuery Transit that handles the complexity of CSS3 animations/transitions.
Moreover, the plugin uses webkit-transform rather than webkit-transition, which allows for mobile devices to use hardware acceleration in order to give your web apps that native look and feel when the animations occur.
Javascript:
$("#startTransition").on("click", function()
{
if( $(".boxOne").is(":visible"))
{
$(".boxOne").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxOne").hide(); });
$(".boxTwo").css({ x: '100%' });
$(".boxTwo").show().transition({ x: '0%', opacity: 1.0 });
return;
}
$(".boxTwo").transition({ x: '-100%', opacity: 0.1 }, function () { $(".boxTwo").hide(); });
$(".boxOne").css({ x: '100%' });
$(".boxOne").show().transition({ x: '0%', opacity: 1.0 });
});
Most of the hard work of getting cross-browser compatibility is done for you as well and it works like a charm on mobile devices.
This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.
var dat1 = document.getElementById('inputDate').value;
var date1 = new Date(dat1)//converts string to date object
alert(date1);
var dat2 = document.getElementById('inputFinishDate').value;
var date2 = new Date(dat2)
alert(date2);
var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
alert(diffDays);
As of API 24, sending a file://
URI to another app will throw a FileUriExposedException. Instead, use FileProvider to send a content://
URI:
public File getFile(Context context, String fileName) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
File storageDir = context.getExternalFilesDir(null);
return new File(storageDir, fileName);
}
public Uri getFileUri(Context context, String fileName) {
File file = getFile(context, fileName);
return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);
}
You must also define the FileProvider in your manifest:
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.mydomain.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
Example file_paths.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-files-path name="name" path="path" />
</paths>
Replace "name" and "path" as appropriate.
To give the PDF viewer access to the file, you also have to add the FLAG_GRANT_READ_URI_PERMISSION
flag to the intent:
private void displayPdf(String fileName) {
Uri uri = getFileUri(this, fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "application/pdf");
// FLAG_GRANT_READ_URI_PERMISSION is needed on API 24+ so the activity opening the file can read it
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (intent.resolveActivity(getPackageManager()) == null) {
// Show an error
} else {
startActivity(intent);
}
}
See the FileProvider documentation for more details.
Changing all my queries because Studio changed version isn't an option. Tried the preferences mentioned above to no effect. It didn't put the quotes in when there was a CR-LF. Perhaps it only triggers when a comma happens.
Copy-paste to Excel is a mainstay of SQL server. Mircosoft either needs a checkbox to revert back to 2008 behavior or they need to enhance the clipboard transfer to Excel such that ONE ROW EQUALS ONE ROW.
In your example, the TMP
variable is set (and the temporary directory created) whenever the rules for out.tar
are evaluated. In order to create the directory only when out.tar
is actually fired, you need to move the directory creation down into the steps:
out.tar :
$(eval TMP := $(shell mktemp -d))
@echo hi $(TMP)/hi.txt
tar -C $(TMP) cf $@ .
rm -rf $(TMP)
The eval function evaluates a string as if it had been typed into the makefile manually. In this case, it sets the TMP
variable to the result of the shell
function call.
edit (in response to comments):
To create a unique variable, you could do the following:
out.tar :
$(eval $@_TMP := $(shell mktemp -d))
@echo hi $($@_TMP)/hi.txt
tar -C $($@_TMP) cf $@ .
rm -rf $($@_TMP)
This would prepend the name of the target (out.tar, in this case) to the variable, producing a variable with the name out.tar_TMP
. Hopefully, that is enough to prevent conflicts.
Just for completeness, let's not forget the Simplest Thing That Could Possibly Work:
for i in list:
if i.n == 5:
# do something with it
print "YAY! Found one!"
In my rails (rails 4.2)
project, I use
Model.last(10) # get the last 10 record order by id
and it works.
The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field.
One solution would be this:
LOCK TABLES
favorite_food WRITE,
person WRITE;
ALTER TABLE favorite_food
DROP FOREIGN KEY fk_fav_food_person_id,
MODIFY person_id SMALLINT UNSIGNED;
Now you can change you person_id
ALTER TABLE person MODIFY person_id SMALLINT UNSIGNED AUTO_INCREMENT;
recreate foreign key
ALTER TABLE favorite_food
ADD CONSTRAINT fk_fav_food_person_id FOREIGN KEY (person_id)
REFERENCES person (person_id);
UNLOCK TABLES;
EDIT: Added locks above, thanks to comments
You have to disallow writing to the database while you do this, otherwise you risk data integrity problems.
I've added a write lock above
All writing queries in any other session than your own ( INSERT, UPDATE, DELETE
) will wait till timeout or UNLOCK TABLES
; is executed
http://dev.mysql.com/doc/refman/5.5/en/lock-tables.html
EDIT 2: OP asked for a more detailed explanation of the line "The type and definition of foreign key field and reference must be equal. This means your foreign key disallows changing the type of your field."
From MySQL 5.5 Reference Manual: FOREIGN KEY Constraints
Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.
Using react hooks, you can do following way
const [countryList, setCountries] = useState([]);
setCountries((countryList) => [
...countryList,
"India",
]);
from datetime import datetime
listA = range(10000000)
setA = set(listA)
tupA = tuple(listA)
#Source Code
def calc(data, type):
start = datetime.now()
if data in type:
print ""
end = datetime.now()
print end-start
calc(9999, listA)
calc(9999, tupA)
calc(9999, setA)
Output after comparing 10 iterations for all 3 : Comparison
From the C99 standard (C++ should be the same, barring strange overloading)
6.5.2.4 Postfix increment and decrement operators
Constraints
1 The operand of the postfix increment or decrement operator shall have qualified or unqualified real or pointer type and shall be a modifiable lvalue.
Semantics
2 The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate type is added to it.) See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The side effect of updating the stored value of the operand shall occur between the previous and the next sequence point.
3 The postfix -- operator is analogous to the postfix ++ operator, except that the value of the operand is decremented (that is, the value 1 of the appropriate type is subtracted from it).
6.5.3.1 Prefix increment and decrement operators
Constraints
1 The operand of the prefix increment or decrement operator shall have qualified or unqualified real or pointer type and shall be a modifiable lvalue.
Semantics
2 The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1). See the discussions of additive operators and compound assignment for information on constraints, types, side effects, and conversions and the effects of operations on pointers.
3 The prefix -- operator is analogous to the prefix ++ operator, except that the value of the operand is decremented.
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
By design adb root
command works in development builds only (i.e. eng
and userdebug
which have ro.debuggable=1
by default). So to enable the adb root
command on your otherwise rooted device just add the ro.debuggable=1
line to one of the following files:
/system/build.prop
/system/default.prop
/data/local.prop
If you want adb shell
to start as root
by default - then add ro.secure=0
as well.
Alternatively you could use modified adbd
binary (which does not check for ro.debuggable
)
From https://android.googlesource.com/platform/system/core/+/master/adb/daemon/main.cpp
#if defined(ALLOW_ADBD_ROOT)
// The properties that affect `adb root` and `adb unroot` are ro.secure and
// ro.debuggable. In this context the names don't make the expected behavior
// particularly obvious.
//
// ro.debuggable:
// Allowed to become root, but not necessarily the default. Set to 1 on
// eng and userdebug builds.
//
// ro.secure:
// Drop privileges by default. Set to 1 on userdebug and user builds.
Use the LEN
function:
Returns the number of characters of the specified string expression, excluding trailing blanks.
JSONObject site=jsonSites.getJSONObject(i)
should work out
Type :h recording to learn more.
*q* *recording* q{0-9a-zA-Z"} Record typed characters into register {0-9a-zA-Z"} (uppercase to append). The 'q' command is disabled while executing a register, and it doesn't work inside a mapping. {Vi: no recording} q Stops recording. (Implementation note: The 'q' that stops recording is not stored in the register, unless it was the result of a mapping) {Vi: no recording} *@* @{0-9a-z".=*} Execute the contents of register {0-9a-z".=*} [count] times. Note that register '%' (name of the current file) and '#' (name of the alternate file) cannot be used. For "@=" you are prompted to enter an expression. The result of the expression is then executed. See also |@:|. {Vi: only named registers}
Adding screen shots(examples) and some more context for the answer of @Thomas G.
import pandas as pd
is ran properly before checking below shortcut.Place the cursor in middle of parenthesis ()
before you use shortcut.
shift + tab
Display short document and few params
shift + tab + tab
Expands document with scroll bar
shift + tab + tab + tab
Provides document with a Tooltip: "will linger for 10secs while you type". which means it allows you write params and waits for 10secs.
shift + tab + tab + tab + tab
It opens a small window in bottom with option(top righ corner of small window) to open full documentation in new browser tab.
You could use a function similar to:
function redirect($url) {
ob_start();
header('Location: '.$url);
ob_end_flush();
die();
}
Worth noting, you should always use either ob_flush()
or ob_start()
at the beginning of your header('location: ...');
functions, and you should always follow them with a die()
or exit()
function to prevent further code execution.
Here's a more detailed guide than any of the other answers have mentioned: http://www.exchangecore.com/blog/how-redirect-using-php/
This guide includes reasons for using die()
/ exit()
functions in your redirects, as well as when to use ob_flush()
vs ob_start()
, and some potential errors that the others answers have left out at this point.
You should use the excellent OpenCSV for reading and writing CSV files. To adapt your example to use the library it would look like this:
public class ParseCSV {
public static void main(String[] args) {
try {
//csv file containing data
String strFile = "C:/Users/rsaluja/CMS_Evaluation/Drupal_12_08_27.csv";
CSVReader reader = new CSVReader(new FileReader(strFile));
String [] nextLine;
int lineNumber = 0;
while ((nextLine = reader.readNext()) != null) {
lineNumber++;
System.out.println("Line # " + lineNumber);
// nextLine[] is an array of values from the line
System.out.println(nextLine[4] + "etc...");
}
}
}
}
A shorter solution (which doesn't force you to repeat the vector name 4 times) would be to use Boost:
#include <boost/range/algorithm_ext/erase.hpp>
// ...
boost::remove_erase(vec, int_to_remove);
You should use font-size for controlling the height, it is widely supported amongst browsers. And in order to add spacing, you should use padding. Forexample,
.inputField{
font-size: 30px;
padding-top: 10px;
padding-bottom: 10px;
}
Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.
The first element in a collection is generally located at index 0
. The last element is at index n-1
, where n
is the Size
of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1
, you're going to get an error.
When you declare an array like this:
var array = new int[6]
The first and last elements in the array are
var firstElement = array[0];
var lastElement = array[5];
So when you write:
var element = array[5];
you are retrieving the sixth element in the array, not the fifth one.
Typically, you would loop over an array like this:
for (int index = 0; index < array.Length; index++)
{
Console.WriteLine(array[index]);
}
This works, because the loop starts at zero, and ends at Length-1
because index
is no longer less than Length
.
This, however, will throw an exception:
for (int index = 0; index <= array.Length; index++)
{
Console.WriteLine(array[index]);
}
Notice the <=
there? index
will now be out of range in the last loop iteration, because the loop thinks that Length
is a valid index, but it is not.
Lists work the same way, except that you generally use Count
instead of Length
. They still start at zero, and end at Count - 1
.
for (int index = 0; i < list.Count; index++)
{
Console.WriteLine(list[index]);
}
However, you can also iterate through a list using foreach
, avoiding the whole problem of indexing entirely:
foreach (var element in list)
{
Console.WriteLine(element.ToString());
}
You cannot index an element that hasn't been added to a collection yet.
var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]); // Throws exception.
Checkout intent properties like no history , clear back stack etc ... Intent.setFlags
Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
class MyFirebaseIIDService: FirebaseInstanceIdService
{
const string TAG = "MyFirebaseIIDService";
NotificationHub hub;
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
Log.Debug(TAG, "FCM token: " + refreshedToken);
SendRegistrationToServer(refreshedToken);
}
void SendRegistrationToServer(string token)
{
// Register with Notification Hubs
hub = new NotificationHub(Constants.NotificationHubName,
Constants.ListenConnectionString, this);
Employee employee = JsonConvert.DeserializeObject<Employee>(Settings.CurrentUser);
//if user is not logged in
if (employee != null)
{
var tags = new List<string>() { employee.Email};
var regID = hub.Register(token, tags.ToArray()).RegistrationId;
Log.Debug(TAG, $"Successful registration of ID {regID}");
}
else
{
FirebaseInstanceId.GetInstance(Firebase.FirebaseApp.Instance).DeleteInstanceId();
hub.Unregister();
}
}
}
Select "Tab key: Indents always" in Preferences->Text Editing->Indentation Then you can indent a single line or a selection of lines by pressing TAB or SHIFT+TAB Sadly this removes altogether the possibility to insert tabs where you want, and conflict badly with the tab key being used to switch between "autocompletion fields".
I guess we need more tab keys in the keyboard, one is not enough...
Ensure that control Format property is properly set to use a custom format:
DateTimePicker1.Format = DateTimePickerFormat.Custom
Then this is how you can set your desired format:
DateTimePicker1.CustomFormat = "dd-MM-yyyy"
I happened to try this so I could see the list of files first:
git status | grep "modified:" | awk '{print "git add " $2}' > file.sh
cat ./file.sh
execute:
chmod a+x file.sh
./file.sh
Edit: (see comments) This could be achieved in one step:
git status | grep "modified:" | awk '{print $2}' | xargs git add && git status
Try this.
using System.Xml.Linq;
void Main()
{
StringBuilder result = new StringBuilder();
//Load xml
XDocument xdoc = XDocument.Load("data.xml");
//Run query
var lv1s = from lv1 in xdoc.Descendants("level1")
select new {
Header = lv1.Attribute("name").Value,
Children = lv1.Descendants("level2")
};
//Loop through results
foreach (var lv1 in lv1s){
result.AppendLine(lv1.Header);
foreach(var lv2 in lv1.Children)
result.AppendLine(" " + lv2.Attribute("name").Value);
}
Console.WriteLine(result);
}
mysql is not case sensitive by default, try changing the language collation to latin1_general_cs
If you prefer an Integer[]
instead array of an int[]
array:
Integer[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
Integer[] result = Stream.of(parts).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
int[]
String str = "[1,2]";
String plainStr = str.substring(1, str.length()-1); // clear braces []
String[] parts = plainStr.split(",");
int[] result = Stream.of(parts).mapToInt(Integer::parseInt).toArray()
This works for Java 8 and higher.
What the other answers suggest will work for the program in question, but it has the potential to cause breakage in other programs and unknown dependence elsewhere. It's better to make a tiny wrapper script:
#!/bin/sh
export LD_LIBRARY_PATH=/usr/local/lib64:$LD_LIBRARY_PATH
program_needing_different_run_time_library_path
This mostly avoids the problem described in Why LD_LIBRARY_PATH is bad by confining the effects to the program which needs them.
Note that despite the names LD_RUN_PATH works at link-time and is non-evil, while LD_LIBRARY_PATH works at both link and run time (and is evil :).
Please set the request Content Type before you read the response stream;
request.ContentType = "text/xml";
accepted answer doesn't work for me and doesn't follow MDN examples
see the 'Description' section in above link
I'd go with the following it's working for me:
let stringThatIsGoingToChange = 'findMe';
let flagsYouWant = 'gi' //simple string with flags
let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)
// that makes dynamicRegExp = /findMe/gi
I know its pretty old but I just encounter the problem and there is what I saw in the SQL doc :
[For best results when using BETWEEN with date or time values,] use CAST() to explicitly convert the values to the desired data type. Examples: If you compare a DATETIME to two DATE values, convert the DATE values to DATETIME values. If you use a string constant such as '2001-1-1' in a comparison to a DATE, cast the string to a DATE.
I assume it's better to use STR_TO_DATE since they took the time to make a function just for that and also the fact that i found this in the BETWEEN doc...
You could also try setting style
inline without using a variable, like so:
style={{"height" : "100%"}}
or,
for multiple attributes: style={{"height" : "100%", "width" : "50%"}}
I'm using dictionaries as a sort of "database", so I need to find a key that I can reuse. For my case, if a key's value is None
, then I can take it and reuse it without having to "allocate" another id. Just figured I'd share it.
db = {0:[], 1:[], ..., 5:None, 11:None, 19:[], ...}
keys_to_reallocate = [None]
allocate.extend(i for i in db.iterkeys() if db[i] is None)
free_id = keys_to_reallocate[-1]
I like this one because I don't have to try and catch any errors such as StopIteration
or IndexError
. If there's a key available, then free_id
will contain one. If there isn't, then it will simply be None
. Probably not pythonic, but I really didn't want to use a try
here...
You're trying to access a JSON, not JSONP.
Notice the difference between your source:
And actual JSONP (a wrapping function):
Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.
I would use javascript for this.
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://my.remote.url/myremotefile.txt", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4 && txtFile.status == 200) {
allText = txtFile.responseText;
}
document.getElementById('your div id').innerHTML = allText;
This is just a code sample, would need tweaking for all browsers, etc.
This is a simple one.
your_layout.xml
<android.support.v7.widget.AppCompatSpinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/spinner_background"
/>
In the drawable folder, spinner_background.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item><layer-list>
<item>
<shape>
<solid
android:color="@color/colorWhite">
</solid>
<corners android:radius="3dp" />
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
<stroke
android:width="2dp"
android:color="@color/colorDarkGrey"/>
</shape>
</item>
<item >
<bitmap android:gravity="bottom|right"
android:src="@drawable/ic_arrow_drop_down_black_24dp" />
</item>
</layer-list></item>
</selector>
Preview:
As much as I love the occasional upvotes I get for this answer (thanks!), this is really not the greatest approach to this problem. Please check out some of the other wonderful answers here, especially the ones that have found solutions without looping.
Still, for the sake of reference, here's my original answer:
<html>
<head>
<style type="text/css">
#dynamicDiv
{
background: #CCCCCC;
width: 300px;
height: 100px;
font-size: 64px;
overflow: hidden;
}
</style>
<script type="text/javascript">
function shrink()
{
var textSpan = document.getElementById("dynamicSpan");
var textDiv = document.getElementById("dynamicDiv");
textSpan.style.fontSize = 64;
while(textSpan.offsetHeight > textDiv.offsetHeight)
{
textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
}
}
</script>
</head>
<body onload="shrink()">
<div id="dynamicDiv"><span id="dynamicSpan">DYNAMIC FONT</span></div>
</body>
</html>
And here's a version with classes:
<html>
<head>
<style type="text/css">
.dynamicDiv
{
background: #CCCCCC;
width: 300px;
height: 100px;
font-size: 64px;
overflow: hidden;
}
</style>
<script type="text/javascript">
function shrink()
{
var textDivs = document.getElementsByClassName("dynamicDiv");
var textDivsLength = textDivs.length;
// Loop through all of the dynamic divs on the page
for(var i=0; i<textDivsLength; i++) {
var textDiv = textDivs[i];
// Loop through all of the dynamic spans within the div
var textSpan = textDiv.getElementsByClassName("dynamicSpan")[0];
// Use the same looping logic as before
textSpan.style.fontSize = 64;
while(textSpan.offsetHeight > textDiv.offsetHeight)
{
textSpan.style.fontSize = parseInt(textSpan.style.fontSize) - 1;
}
}
}
</script>
</head>
<body onload="shrink()">
<div class="dynamicDiv"><span class="dynamicSpan">DYNAMIC FONT</span></div>
<div class="dynamicDiv"><span class="dynamicSpan">ANOTHER DYNAMIC FONT</span></div>
<div class="dynamicDiv"><span class="dynamicSpan">AND YET ANOTHER DYNAMIC FONT</span></div>
</body>
</html>
I've rolled my own using strtok and used boost to split a string. The best method I have found is the C++ String Toolkit Library. It is incredibly flexible and fast.
#include <iostream>
#include <vector>
#include <string>
#include <strtk.hpp>
const char *whitespace = " \t\r\n\f";
const char *whitespace_and_punctuation = " \t\r\n\f;,=";
int main()
{
{ // normal parsing of a string into a vector of strings
std::string s("Somewhere down the road");
std::vector<std::string> result;
if( strtk::parse( s, whitespace, result ) )
{
for(size_t i = 0; i < result.size(); ++i )
std::cout << result[i] << std::endl;
}
}
{ // parsing a string into a vector of floats with other separators
// besides spaces
std::string s("3.0, 3.14; 4.0");
std::vector<float> values;
if( strtk::parse( s, whitespace_and_punctuation, values ) )
{
for(size_t i = 0; i < values.size(); ++i )
std::cout << values[i] << std::endl;
}
}
{ // parsing a string into specific variables
std::string s("angle = 45; radius = 9.9");
std::string w1, w2;
float v1, v2;
if( strtk::parse( s, whitespace_and_punctuation, w1, v1, w2, v2) )
{
std::cout << "word " << w1 << ", value " << v1 << std::endl;
std::cout << "word " << w2 << ", value " << v2 << std::endl;
}
}
return 0;
}
The toolkit has much more flexibility than this simple example shows but its utility in parsing a string into useful elements is incredible.
SELECT DATEADD(minute, -15, '2000-01-01 08:30:00');
The second value (-15 in this case) must be numeric (i.e. not a string like '00:15'). If you need to subtract hours and minutes I would recommend splitting the string on the : to get the hours and minutes and subtracting using something like
SELECT DATEADD(minute, -60 * @h - @m, '2000-01-01 08:30:00');
where @h is the hour part of your string and @m is the minute part of your string
EDIT:
Here is a better way:
SELECT CAST('2000-01-01 08:30:00' as datetime) - CAST('00:15' AS datetime)
Use a second class that has only the hover assigned:
HTML
<a class="myclass myclass_hover" href="#">My anchor</a>
CSS
.myclass {
/* all anchor styles */
}
.myclass_hover:hover {
/* example color */
color:#00A;
}
Now you can use Jquery to remove the class, for instance if the element has been clicked:
JQUERY
$('.myclass').click( function(e) {
e.preventDefault();
$(this).removeClass('myclass_hover');
});
Hope this answer is helpful.
I needed to extract all the matched search lines (using regex) in a file
selectHighlights
)CURDATE()
will give current date while NOW()
will give full date time.
Run the queries, and you will find out whats the difference between them.
SELECT NOW(); -- You will get 2010-12-09 17:10:18
SELECT CURDATE(); -- You will get 2010-12-09
I was able to fix this error by simply initializing a variable that was being used later in my program. At the time, I wasn't using Option Explicit in my class/module.
This is the case because the pointer you have for the submodule isn’t what is actually in the submodule directory. To fix this, you must run git submodule update
again:
@AHegde - To get the tab delimited output use separator sep='\t'.
For df.to_csv:
df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')
For np.savetxt:
np.savetxt(r'c:\data\np.txt', df.values, fmt='%d', delimiter='\t')
In Python 3.7, and running Windows 10 this worked (I am not sure whether it will work on other platforms and/or other versions of Python)
Replacing this line:
with open('filename', 'w') as f:
With this:
with open('filename', 'w', encoding='utf-8') as f:
The reason why it is working is because the encoding is changed to UTF-8 when using the file, so characters in UTF-8 are able to be converted to text, instead of returning an error when it encounters a UTF-8 character that is not suppord by the current encoding.
Try something like this:
$link = @new mysqli($this->host, $this->user, $this->pass)
$statement = $link->prepare($sqlStatement);
if(!$statement)
{
$this->debug_mode('query', 'error', '#Query Failed<br/>' . $link->error);
return false;
}
diplay: flex;
for it's container and margin:auto;
for it's item works perfect.
NOTE: You have to setup the width
and height
to see the effect.
#container{_x000D_
width: 100%; /*width needs to be setup*/_x000D_
height: 150px; /*height needs to be setup*/_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.item{_x000D_
margin: auto; /*These will make the item in center*/_x000D_
background-color: #CCC;_x000D_
}
_x000D_
<div id="container">_x000D_
<div class="item">CENTER</div>_x000D_
</div>
_x000D_
I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)
Try this as the new trigger:
CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
WHERE patron_info.pid = old.id;
END
Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.
My option is given below:
$(document).ready(function () {_x000D_
var userLang = navigator.language || navigator.userLanguage;_x000D_
_x000D_
var options = $.extend({},_x000D_
$.datepicker.regional["ja"], {_x000D_
dateFormat: "yy/mm/dd",_x000D_
changeMonth: true,_x000D_
changeYear: true,_x000D_
highlightWeek: true_x000D_
}_x000D_
);_x000D_
_x000D_
$("#japaneseCalendar").datepicker(options);_x000D_
});
_x000D_
#ui-datepicker-div {_x000D_
font-size: 14px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="UTF-8">_x000D_
<link rel="stylesheet" type="text/css"_x000D_
href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.min.css">_x000D_
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
<h3>Japanese JQuery UI Datepicker</h3>_x000D_
<input type="text" id="japaneseCalendar"/>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
I had a bootstrap + rails project, and dropdown worked fine. They stopped to works after an update...
This is the solution that fixed the problem, add the following to .js file:
$(document).ready(function() {
$(".dropdown-toggle").dropdown();
});
Some shameless self-promo here, but a while ago I created a library called YieldMachine which allows a limited-complexity state machine to be described in a very clean and simple way. For example, consider a lamp:
Notice that this state machine has 2 triggers and 3 states. In YieldMachine code, we write a single method for all state-related behavior, in which we commit the horrible atrocity of using goto
for each state. A trigger becomes a property or field of type Action
, decorated with an attribute called Trigger
. I've commented the code of the first state and its transitions below; the next states follow the same pattern.
public class Lamp : StateMachine
{
// Triggers (or events, or actions, whatever) that our
// state machine understands.
[Trigger]
public readonly Action PressSwitch;
[Trigger]
public readonly Action GotError;
// Actual state machine logic
protected override IEnumerable WalkStates()
{
off:
Console.WriteLine("off.");
yield return null;
if (Trigger == PressSwitch) goto on;
InvalidTrigger();
on:
Console.WriteLine("*shiiine!*");
yield return null;
if (Trigger == GotError) goto error;
if (Trigger == PressSwitch) goto off;
InvalidTrigger();
error:
Console.WriteLine("-err-");
yield return null;
if (Trigger == PressSwitch) goto off;
InvalidTrigger();
}
}
Short and nice, eh!
This state machine is controlled simply by sending triggers to it:
var sm = new Lamp();
sm.PressSwitch(); //go on
sm.PressSwitch(); //go off
sm.PressSwitch(); //go on
sm.GotError(); //get error
sm.PressSwitch(); //go off
Just to clarify, I've added some comments to the first state to help you understand how to use this.
protected override IEnumerable WalkStates()
{
off: // Each goto label is a state
Console.WriteLine("off."); // State entry actions
yield return null; // This means "Wait until a
// trigger is called"
// Ah, we got triggered!
// perform state exit actions
// (none, in this case)
if (Trigger == PressSwitch) goto on; // Transitions go here:
// depending on the trigger
// that was called, go to
// the right state
InvalidTrigger(); // Throw exception on
// invalid trigger
...
This works because the C# compiler actually created a state machine internally for each method that uses yield return
. This construct is usually used to lazily create sequences of data, but in this case we're not actually interested in the returned sequence (which is all nulls anyway), but in the state behaviour that gets created under the hood.
The StateMachine
base class does some reflection on construction to assign code to each [Trigger]
action, which sets the Trigger
member and moves the state machine forward.
But you don't really need to understand the internals to be able to use it.
try to do this in the behind code
public diagboxclass()
{
List<object> list = new List<object>();
list = GetObjectList();
Imported.ItemsSource = null;
Imported.ItemsSource = list;
}
Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.
I'm sending files(array) using formData in vuejs
for me below code is working
if(this.requiredDocumentForUploads.length > 0) {
this.requiredDocumentForUploads.forEach(file => {
var name = file.attachment_type // attachment_type is using for naming
if(document.querySelector("[name=" + name + "]").files.length > 0) {
formData.append("requiredDocumentForUploadsNew[" + name + "]", document.querySelector("[name=" + name + "]").files[0])
}
})
}
You may use flask-crontab module, which is quite easy.
Step 1: pip install flask-crontab
Step 2:
from flask import Flask
from flask_crontab import Crontab
app = Flask(__name__)
crontab = Crontab(app)
Step 3:
@crontab.job(minute="0", hour="6", day="*", month="*", day_of_week="*")
def my_scheduled_job():
do_something()
Step 4: On cmd, hit
flask crontab add
Done. now simply run your flask application, and you can check your function will call at 6:00 every day.
You may take reference from Here (Official DOc).
You do not need to do it. In C (not C++) you were required to use enum Enumname to refer to a data element of the enumerated type. To simplify it you were allowed to typedef it to a single name data type.
typedef enum MyEnum {
//...
} MyEnum;
allowed functions taking a parameter of the enum to be defined as
void f( MyEnum x )
instead of the longer
void f( enum MyEnum x )
Note that the name of the typename does not need to be equal to the name of the enum. The same happens with structs.
In C++, on the other hand, it is not required, as enums, classes and structs can be accessed directly as types by their names.
// C++
enum MyEnum {
// ...
};
void f( MyEnum x ); // Correct C++, Error in C
An initial reaction to this would be to ask and ensure that the two object files are being linked together. This is done at the compile stage by compiling both files at the same time:
gcc -o programName a.c b.c
Or if you want to compile separately, it would be:
gcc -c a.c
gcc -c b.c
gcc -o programName a.o b.o
Maybe a bit late to post an answer for this, but I found some of the above solutions a bit cumbersome.
I tried simple string replacement in sed and it worked:
sed 's/CLIENTSCRIPT="foo"/&\nCLIENTSCRIPT2="hello"/' file
& sign reflects the matched string, and then you add \n and the new line.
As mentioned, if you want to do it in-place:
sed -i 's/CLIENTSCRIPT="foo"/&\nCLIENTSCRIPT2="hello"/' file
Another thing. You can match using an expression:
sed -i 's/CLIENTSCRIPT=.*/&\nCLIENTSCRIPT2="hello"/' file
Hope this helps someone
For the sake of completness, what works best for me is:
git show YOURHASH --no-color -- file1.txt file2.txt dir3 dir4 | git apply -3 --index -
It does exactly what OP wants. It does conflict resolution when needed, similarly how merge
does it. It does add
but not commit
your new changes, see with status
.
We had the same issue with our ClickOnce application that uses Interop with Microsoft Office. It happened only on a few computers in the company.
The best fix we found out was to modify MS Office installation on problematic computers (through the Programs and Features panel) and ensure that ".NET programmability feature" (not sure of the name of the component - our Microsoft_Office versions are not English) was installed for each of the MS Office applications (Excel, Word, Outlook, etc.). This seems to not be included in a default install.
Then the problem with stdole.dll was fixed.
I hope this might help.
If, as I just encountered, you happen to have a jar file listed in the Project Structures->Libraries that is not in your classpath, the correct answer can be found by following the link given by @CrazyCoder above: Look here http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html
This says that to add the jar file as a module dependency within the Project Structure dialog:
Displayed correct at Chrome OS - screenshots from this system.
? U+0F17
? U+2315
? U+1C04
The meaning of CascadeType.ALL
is that the persistence will propagate (cascade) all EntityManager
operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH
) to the relating entities.
It seems in your case to be a bad idea, as removing an Address
would lead to removing the related User
. As a user can have multiple addresses, the other addresses would become orphans. However the inverse case (annotating the User
) would make sense - if an address belongs to a single user only, it is safe to propagate the removal of all addresses belonging to a user if this user is deleted.
BTW: you may want to add a mappedBy="addressOwner"
attribute to your User
to signal to the persistence provider that the join column should be in the ADDRESS table.
For Transaction in database level
mostly I used @Transactional
in DAO's just on method level, so configuration can be specifically for a method / using default (required)
DAO's method that get data fetch (select .. ) - don't need
@Transactional
this can lead to some overhead because of
transaction interceptor / and AOP proxy that need to be executed as
well.
DAO's methods that do insert / update will get @Transactional
very good blog on transctional
For application level -
I am using transactional for business logic I would like to be able rolback in case of unexpected error
@Transactional(rollbackFor={MyApplicationException.class})
public void myMethod(){
try {
//service logic here
} catch(Throwable e) {
log.error(e)
throw new MyApplicationException(..);
}
}
After adding a jar file to a project's lib folder and after adding it to the build.gradle file as compile'path example' when you sync the gradle it add an additional line as compile files('libs/example.jar'). You just need to remove the line you previously added to the build.gradle file i.e. the compile'path example' after the gradle sync. You also need to remove the line compile fileTree(dir: 'libs', include: '*.jar')
The solution for the issue:
public class yourRecyclerViewAdapter extends RecyclerView.Adapter<yourRecyclerViewAdapter.yourViewHolder> {
private static CheckBox lastChecked = null;
private static int lastCheckedPos = 0;
public void onBindViewHolder(ViewHolder holder, final int position) {
holder.mTextView.setText(fonts.get(position).getName());
holder.checkBox.setChecked(fonts.get(position).isSelected());
holder.checkBox.setTag(new Integer(position));
//for default check in first item
if(position == 0 && fonts.get(0).isSelected() && holder.checkBox.isChecked())
{
lastChecked = holder.checkBox;
lastCheckedPos = 0;
}
holder.checkBox.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
CheckBox cb = (CheckBox)v;
int clickedPos = ((Integer)cb.getTag()).intValue();
if(cb.isChecked())
{
if(lastChecked != null)
{
lastChecked.setChecked(false);
fonts.get(lastCheckedPos).setSelected(false);
}
lastChecked = cb;
lastCheckedPos = clickedPos;
}
else
lastChecked = null;
fonts.get(clickedPos).setSelected(cb.isChecked);
}
});
}
}
Hope this help!
You can do this more simply using plot()
instead of plot_date()
.
First, convert your strings to instances of Python datetime.date
:
import datetime as dt
dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]
y = range(len(x)) # many thanks to Kyss Tao for setting me straight here
Then plot:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()
Result:
Ancient question, but 3Dave's answer supplied the easiest approach. I needed a little helper method to generate a Sql script to decode an enum value in the database for debugging. It worked great:
public static string EnumToCheater<T>() {
var sql = "";
foreach (var enumValue in Enum.GetValues(typeof(T)))
sql += $@"when {(int) enumValue} then '{enumValue}' ";
return $@"case ?? {sql}else '??' end,";
}
I have it in a static method, so usage is:
var cheater = MyStaticClass.EnumToCheater<MyEnum>()
If you've got a string, and you expect it to always be an integer (say, if some web service is handing you an integer in string format), you'd use Int32.Parse()
.
If you're collecting input from a user, you'd generally use Int32.TryParse()
, since it allows you more fine-grained control over the situation when the user enters invalid input.
Convert.ToInt32()
takes an object as its argument. (See Chris S's answer for how it works)
Convert.ToInt32()
also does not throw ArgumentNullException
when its argument is null the way Int32.Parse()
does. That also means that Convert.ToInt32()
is probably a wee bit slower than Int32.Parse()
, though in practice, unless you're doing a very large number of iterations in a loop, you'll never notice it.
I wrote a tiny function for this purpose. Feel free to repurpose,
def is_json_key_present(json, key):
try:
buf = json[key]
except KeyError:
return False
return True