There is comma missing in your tuple.
insert the comma between the tuples as shown:
pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))
Do the same for all
There is a simple solution for you called unique_together which does exactly what you want.
For example:
class MyModel(models.Model):
field1 = models.CharField(max_length=50)
field2 = models.CharField(max_length=50)
class Meta:
unique_together = ('field1', 'field2',)
And in your case:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
unique_together = ('journal_id', 'volume_number',)
You can set the default like this:
b = models.CharField(max_length=7,default="foobar")
and then you can hide the field with your model's Admin class like this:
class SomeModelAdmin(admin.ModelAdmin):
exclude = ("b")
The variable objectSummary holds the current object of type S3ObjectSummary returned from the objectListing.getObjectSummaries() and iterate over the collection.
Here is an example of this enhanced for loop from Java Tutorials
class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}
In this example, the variable item holds the current value from the numbers array.
Output is as follows:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
Hope this helps !
In your activity, where you defined your listview
you write
listview.setOnItemClickListener(new OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
ItemClicked item = adapter.getItemAtPosition(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
//based on item add info to intent
startActivity(intent);
}
});
in your adapter's getItem you write
public ItemClicked getItem(int position){
return items.get(position);
}
A reasonable solution would be to use an iterator if you don't know anything about the underlying Collection, but do know that there is a "last" element. This isn't always the case, not all Collections are ordered.
Object lastElement = null;
for (Iterator collectionItr = c.iterator(); collectionItr.hasNext(); ) {
lastElement = collectionItr.next();
}
maybe not the most efficient, but reads data in one line:
#include<iostream>
#include<vector>
#include<iterator>
main(int argc,char *argv[]){
// read standard input into vector:
std::vector<char>v(std::istream_iterator<char>(std::cin),
std::istream_iterator<char>());
std::cout << "read " << v.size() << "chars\n";
}
Before trying any of the fixes described on this page, I would advise to make a copy of your repo and work on this copy only. Then at the end if you can fix it, compare it with the original to ensure you did not lose any file in the repair process.
Another alternative which worked for me was to reset the git head and index to its previous state using:
git reset --keep
You can also do the same manually by opening the Git GUI and selecting each "Staged changes" and click on "Unstage the change". When everything is unstaged, you should now be able to compress your database, check your database and commit.
I also tried the following commands but they did not work for me, but they might for you depending on the exact issue you have:
git reset --mixed
git fsck --full
git gc --auto
git prune --expire now
git reflog --all
Finally, to avoid this problem of synchronization damaging your git index (which can happen with DropBox, SpiderOak, or any other cloud disk), you can do the following:
.git
folder into a single "bundle" git file by using: git bundle create my_repo.git --all
, then it should work just the same as before, but since everything is in a single file you won't risk the synchronization damaging your git repo anymore.If you are using (PHP 5 >= 5.5.0) you don't have to write your own function to do this, just write this line and it's done.
If you want just one result:
$key = array_search(40489, array_column($userdb, 'uid'));
For multiple results
$keys = array_keys(array_column($userdb, 'uid'), 40489);
In case you have an associative array as pointed in the comments you could make it with:
$keys = array_keys(array_combine(array_keys($userdb), array_column($userdb, 'uid')),40489);
If you are using PHP < 5.5.0, you can use this backport, thanks ramsey!
Update: I've been making some simple benchmarks and the multiple results form seems to be the fastest one, even faster than the Jakub custom function!
You should check with SMTP.
That means you have to connect to that email's SMTP server.
After connecting to the SMTP server you should send these commands:
HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>
If you get "<[email protected]> Relay access denied" that means this email is Invalid.
There is a simple PHP class. You can use it:
http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html
Using React with Typescript you get an error as the function must return a react element, not void
. So I did it this way using the Route render method (and using React router v4):
redirectToHomePage = (): null => {
window.location.reload();
return null;
};
<Route exact path={'/'} render={this.redirectToHomePage} />
Where you could instead also use window.location.assign()
, window.location.replace()
etc
you pass the context to class B in it's constructor, and make sure you pass getApplicationContext() instead of a activityContext()
It should be implemented as a free, non-friend functions, especially if, like most things these days, the output is mainly used for diagnostics and logging. Add const accessors for all the things that need to go into the output, and then have the outputter just call those and do formatting.
I've actually taken to collecting all of these ostream output free functions in an "ostreamhelpers" header and implementation file, it keeps that secondary functionality far away from the real purpose of the classes.
Complete talk fully explaining the problem, which proposes a great paradigm shifting way to avoid these serialization problems: https://github.com/samthebest/dump/blob/master/sams-scala-tutorial/serialization-exceptions-and-memory-leaks-no-ws.md
The top voted answer is basically suggesting throwing away an entire language feature - that is no longer using methods and only using functions. Indeed in functional programming methods in classes should be avoided, but turning them into functions isn't solving the design issue here (see above link).
As a quick fix in this particular situation you could just use the @transient
annotation to tell it not to try to serialise the offending value (here, Spark.ctx
is a custom class not Spark's one following OP's naming):
@transient
val rddList = Spark.ctx.parallelize(list)
You can also restructure code so that rddList lives somewhere else, but that is also nasty.
In future Scala will include these things called "spores" that should allow us to fine grain control what does and does not exactly get pulled in by a closure. Furthermore this should turn all mistakes of accidentally pulling in non-serializable types (or any unwanted values) into compile errors rather than now which is horrible runtime exceptions / memory leaks.
http://docs.scala-lang.org/sips/pending/spores.html
When using kyro, make it so that registration is necessary, this will mean you get errors instead of memory leaks:
"Finally, I know that kryo has kryo.setRegistrationOptional(true) but I am having a very difficult time trying to figure out how to use it. When this option is turned on, kryo still seems to throw exceptions if I haven't registered classes."
Strategy for registering classes with kryo
Of course this only gives you type-level control not value-level control.
... more ideas to come.
Complete working example in Kotlin, I have replaced my API keys with 1111...
val apiService = API.getInstance().retrofit.create(MyApiEndpointInterface::class.java)
val params = HashMap<String, String>()
params["q"] = "munich,de"
params["APPID"] = "11111111111111111"
val call = apiService.getWeather(params)
call.enqueue(object : Callback<WeatherResponse> {
override fun onFailure(call: Call<WeatherResponse>?, t: Throwable?) {
Log.e("Error:::","Error "+t!!.message)
}
override fun onResponse(call: Call<WeatherResponse>?, response: Response<WeatherResponse>?) {
if (response != null && response.isSuccessful && response.body() != null) {
Log.e("SUCCESS:::","Response "+ response.body()!!.main.temp)
temperature.setText(""+ response.body()!!.main.temp)
}
}
})
This seems to work, although still a bit verbose (I'd like something shorter still):
@BeforeClass
public static void beforeClass() {
System.setProperty("some.property", "<value>");
}
// Optionally:
@AfterClass
public static void afterClass() {
System.clearProperty("some.property");
}
You can use these to factor out code common to all tests in the test suite.
If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.
You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.
If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.
For example:
class TurretTest(unittest.TestCase):
def setUp(self):
self.turret_factory = TurretFactory()
self.turret = self.turret_factory.CreateTurret()
def test_turret_is_on_by_default(self):
self.assertEquals(True, self.turret.is_on())
def test_turret_turns_can_be_turned_off(self):
self.turret.turn_off()
self.assertEquals(False, self.turret.is_on())
Change App Package Name with single command
by using following package. It makes the process very easy and fast.
flutter pub run change_app_package_name:main com.new.package.name
Here is the script that will evaluates all script tags in the text.
function evalJSFromHtml(html) {
var newElement = document.createElement('div');
newElement.innerHTML = html;
var scripts = newElement.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
eval(script.innerHTML);
}
}
Just call this function after you receive your HTML from server. Be warned: using eval
can be dangerous.
FractionallySizedBox
may also be useful.
You can also read the screen width directly out of MediaQuery.of(context).size
and create a sized box based on that
MediaQuery.of(context).size.width * 0.65
if you really want to size as a fraction of the screen regardless of what the layout is.
var elem = document.getElementById("myvideo");
function openFullscreen() {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) { /* Firefox */
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { /* IE/Edge */
elem.msRequestFullscreen();
}
}
//Internet Explorer 10 and earlier does not support the msRequestFullscreen() method.
SELECT NAME FROM v$database;
shows the database name in oracle
Javascript is a fine development environment so it seems odd than it doesn't provide a solution to this small problem. The solutions offered elsewhere on this page are potentially slow. Here is my solution. It employs the inbuilt functionality that decodes base64 image and sound data urls.
var req = new XMLHttpRequest;
req.open('GET', "data:application/octet;base64," + base64Data);
req.responseType = 'arraybuffer';
req.onload = function fileLoaded(e)
{
var byteArray = new Uint8Array(e.target.response);
// var shortArray = new Int16Array(e.target.response);
// var unsignedShortArray = new Int16Array(e.target.response);
// etc.
}
req.send();
The send request fails if the base 64 string is badly formed.
The mime type (application/octet) is probably unnecessary.
Tested in chrome. Should work in other browsers.
Actually issues in one of Ubuntu machine is ssh-keygen command was not run properly. I tried running again and navigated into /home/user1/.ssh and able to see id_rsa and id_rsa.pub keys. then tried command ssh-copy-id and it was working fine.
Found this today, made a few tweaks and combined the features of the other answers while updating it to bootstrap 3.x. NB: This answer requires jQuery.
In html:
<div id="form_errors" class="alert alert-danger fade in" style="display:none">
In JS:
<script>
//http://stackoverflow.com/questions/10082330/dynamically-create-bootstrap-alerts-box-through-javascript
function bootstrap_alert(elem, message, timeout) {
$(elem).show().html('<div class="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><span>'+message+'</span></div>');
if (timeout || timeout === 0) {
setTimeout(function() {
$(elem).alert('close');
}, timeout);
}
};
</script>?
Then you can invoke this either as:
bootstrap_alert('#form_errors', 'This message will fade out in 1 second', 1000)
bootstrap_alert('#form_errors', 'User must dismiss this message manually')
You can use the row_number()
function for this.
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
row_number() over (order by (select NULL))
FROM PM_Ingrediants
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
If you want to start with the maximum already in the table then do:
INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
FROM PM_Ingrediants cross join
(select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
)
Finally, you can just make the sequence
column an auto-incrementing identity column. This saves the need to increment it each time:
create table PM_Ingrediants_Arrangement_Temp ( . . .
sequence int identity(1, 1) -- and might consider making this a primary key too
. . .
)
you can use redis-cli INFO keyspace
localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0
in pure js just use offsetLeft
and offsetTop
properties.
Example fiddle: http://jsfiddle.net/WKZ8P/
var elm = document.querySelector('span');_x000D_
console.log(elm.offsetLeft, elm.offsetTop);
_x000D_
p { position:relative; left:10px; top:85px; border:1px solid blue; }_x000D_
span{ position:relative; left:30px; top:35px; border:1px solid red; }
_x000D_
<p>_x000D_
<span>paragraph</span>_x000D_
</p>
_x000D_
You can try intersection()
and subtract()
methods from CollectionUtils
.
intersection()
method gives you a collection containing common elements and the subtract()
method gives you all the uncommon ones.
They should also take care of similar elements
Try this:
;WITH CTE AS (
SELECT DISTINCT id FROM table WHERE fid = 64
)
SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS RowNum
FROM cte
WHERE fid = 64
That's no struts related problem but rather plain HMTL/CSS.
I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.
Is there an universal way to find the location of an external SD card?
By universal way, if you mean official way; yes there is one.
In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type)
in Context
Class that allows apps to store data/files in micro SD cards.
Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.
getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).
But note that,
Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using
getExternalStorageState(File)
.There is no security enforced with these files. For example, any application holding
WRITE_EXTERNAL_STORAGE
can write to these files.
The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.
The whole point of a class is that you create an instance, and that instance encapsulates a set of data. So it's wrong to say that your variables are global within the scope of the class: say rather that an instance holds attributes, and that instance can refer to its own attributes in any of its code (via self.whatever
). Similarly, any other code given an instance can use that instance to access the instance's attributes - ie instance.whatever
.
I recomend this one-liner
List<Video> videos = Arrays.asList(new Gson().fromJson(json, Video[].class));
Warning: the list of videos
, returned by Arrays.asList
is immutable - you can't insert new values. If you need to modify it, wrap in new ArrayList<>(...)
.
Reference:
json
may be of type JsonElement
, Reader
, or String
)To define a 3 column grid you could use the customizer or download the source set your less variables and recompile.
To learn more about the grid and the columns / gutter widths, please also read:
In you case with a container of 960px consider the medium grid (see also: http://getbootstrap.com/css/#grid). This grid will have a max container width of 970px.
When setting @grid-columns:3;
and setting @grid-gutter-width:15px;
in variables.less you will get:
15px | 1st column (298.33) | 15px | 2nd column (298.33) |15px | 3th column (298.33) | 15px
Q. What is Artifact in maven?
ANS: ARTIFACT is a JAR,(WAR or EAR), but it could be also something else. Each artifact has,
Q.Why does Maven need them?
Ans: Maven is used to make them available for our applications.
with open('writing_file.json', 'w') as w:
with open('reading_file.json', 'r') as r:
for line in r:
element = json.loads(line.strip())
if 'hours' in element:
del element['hours']
w.write(json.dumps(element))
this is the method i use..
table
{
margin-left: auto;
margin-right: auto;
}
This will definitely work. Cheers
Visual Studio 2017 is supported in Crystal Reports SP 21, which is available for download as of 1 Sep 2017.
Update maven version to 3.6.3 and run
mvn -Dhttps.protocols=TLSv1.2 install
it worked on centos 6.9
Script is called before element exists.
You should try one of the following:
I would say via the HTML canvas tag.
You can find here a post by @Georg talking about a small code by the Opera dev :
// Get the CanvasPixelArray from the given coordinates and dimensions.
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;
// Loop over each pixel and invert the color.
for (var i = 0, n = pix.length; i < n; i += 4) {
pix[i ] = 255 - pix[i ]; // red
pix[i+1] = 255 - pix[i+1]; // green
pix[i+2] = 255 - pix[i+2]; // blue
// i+3 is alpha (the fourth element)
}
// Draw the ImageData at the given (x,y) coordinates.
context.putImageData(imgd, x, y);
This invert the image by using the R, G and B value of each pixel. You could easily store the RGB values, then round up the Red, Green and Blue arrays, and finally converting them back into an HEX code.
For self-hiding you can use getCmdPID.bat and windowMode.bat:
@echo off
echo --- self hiding bat ----
pause
call getCmdPid.bat
set PID=%errorlevel%
call windowMode.bat -pid %PID% -mode hidden
Here's my collection of ways to achieve that - and even more - where it was possible I've tried to return also the PID of the started process (all linked scripts can be downloaded and saved with whatever name you find convenient):
Example usage:
call IEXPhidden.bat "cmd /c myBat.bat" "argument"
Example usage:
call SCHPhidden.bat "cmd /c myBat.bat" "argument"
Example usage (for more info print the help with '-h'):
call ShellRunJS.bat "notepad.exe" -style 0 -wait no
Example usage (for more info print the help with '-h'):
call win32process.bat "notepad" -arguments "/A openFile.txt" -showWindows 0 -title "notepad"
Example usage (for more info print the help with '-h'):
call ProcessStartJS.bat "notepad" -arguments "/A openFile.txt" -style Hidden -directory "." -title "notepad" -priority Normal
You could read Google answer for it here: http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Preincrement_and_Predecrement
So, main point is, what no difference for simple object, but for iterators and other template objects you should use preincrement.
EDITED:
There are no difference because you use simple type, so no side effects, and post- or preincrements executed after loop body, so no impact on value in loop body.
You could check it with such a loop:
for (int i = 0; i < 5; cout << "we still not incremented here: " << i << endl, i++)
{
cout << "inside loop body: " << i << endl;
}
They are both constant, but a const is available also at compile time. This means that one aspect of the difference is that you can use const variables as input to attribute constructors, but not readonly variables.
Example:
public static class Text {
public const string ConstDescription = "This can be used.";
public readonly static string ReadonlyDescription = "Cannot be used.";
}
public class Foo
{
[Description(Text.ConstDescription)]
public int BarThatBuilds {
{ get; set; }
}
[Description(Text.ReadOnlyDescription)]
public int BarThatDoesNotBuild {
{ get; set; }
}
}
In JavaScript you cannot have the direct access to the filesystem.
However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace
method with your Base64String and replace "image/png"
with "image/octet-stream"
:
"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");
Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:
Probably, you will find them useful in a way...
Here is a refactored version of what I understand you need:
window.addEventListener('DOMContentLoaded', () => {_x000D_
const img = document.getElementById('embedImage');_x000D_
img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
'9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
_x000D_
const button = document.getElementById('saveImage');_x000D_
button.addEventListener('click', () => {_x000D_
window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
});_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
<img id="embedImage" alt="Red dot" />_x000D_
<button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
Abstract Class
1. Contains an abstract method
2. Cannot be directly initialized
3. Cannot create an object of abstract class
4. Only used for inheritance purposes
Abstract Method
1. Cannot contain a body
2. Cannot be defined as private
3. Child classes must define the methods declared in abstract class
Example Code:
abstract class A {
public function test1() {
echo 'Hello World';
}
abstract protected function f1();
abstract public function f2();
protected function test2(){
echo 'Hello World test';
}
}
class B extends A {
public $a = 'India';
public function f1() {
echo "F1 Method Call";
}
public function f2() {
echo "F2 Method Call";
}
}
$b = new B();
echo $b->test1() . "<br/>";
echo $b->a . "<br/>";
echo $b->test2() . "<br/>";
echo $b->f1() . "<br/>";
echo $b->f2() . "<br/>";
Output:
Hello World
India
Hello World test
F1 Method Call
F2 Method Call
@rahul-kumar 's solution works good for me, but i wanted to call my javascript function in my typescript
foo.myFunctions() // works in browser console, but foo can't be used in typescript file
I fixed it by declaring it in my typescript :
import { Component } from '@angular/core';
import { ScriptService } from './script.service';
declare var foo;
And now, i can call foo anywhere in my typecript file
In my case, I am not using the built in ajax api to feed Json to the table (this is due to some formatting that was rather difficult to implement inside the datatable's render callback).
My solution was to create the variable in the outer scope of the onload functions and the function that handles the data refresh (var table = null
, for example).
Then I instantiate my table in the on load method
$(function () {
//.... some code here
table = $("#detailReportTable").DataTable();
.... more code here
});
and finally, in the function that handles the refresh, i invoke the clear() and destroy() method, fetch the data into the html table, and re-instantiate the datatable, as such:
function getOrderDetail() {
table.clear();
table.destroy();
...
$.ajax({
//.....api call here
});
....
table = $("#detailReportTable").DataTable();
}
I hope someone finds this useful!
A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.
If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).
I think there is a very simple solution:
public boolean isPositive(int|float|double|long i){
return (((i-i)==0)? true : false);
}
tell me if I'm wrong!
I will suggest you not to really depend of database for translation it could be really a messy task and could be a extreme problem in case of data encoding.
I had face similar issue while ago and written following class to solve my problem
<?php
namespace Locale;
class Locale{
// Following array stolen from Zend Framework
public $country_to_locale = array(
'AD' => 'ca_AD',
'AE' => 'ar_AE',
'AF' => 'fa_AF',
'AG' => 'en_AG',
'AI' => 'en_AI',
'AL' => 'sq_AL',
'AM' => 'hy_AM',
'AN' => 'pap_AN',
'AO' => 'pt_AO',
'AQ' => 'und_AQ',
'AR' => 'es_AR',
'AS' => 'sm_AS',
'AT' => 'de_AT',
'AU' => 'en_AU',
'AW' => 'nl_AW',
'AX' => 'sv_AX',
'AZ' => 'az_Latn_AZ',
'BA' => 'bs_BA',
'BB' => 'en_BB',
'BD' => 'bn_BD',
'BE' => 'nl_BE',
'BF' => 'mos_BF',
'BG' => 'bg_BG',
'BH' => 'ar_BH',
'BI' => 'rn_BI',
'BJ' => 'fr_BJ',
'BL' => 'fr_BL',
'BM' => 'en_BM',
'BN' => 'ms_BN',
'BO' => 'es_BO',
'BR' => 'pt_BR',
'BS' => 'en_BS',
'BT' => 'dz_BT',
'BV' => 'und_BV',
'BW' => 'en_BW',
'BY' => 'be_BY',
'BZ' => 'en_BZ',
'CA' => 'en_CA',
'CC' => 'ms_CC',
'CD' => 'sw_CD',
'CF' => 'fr_CF',
'CG' => 'fr_CG',
'CH' => 'de_CH',
'CI' => 'fr_CI',
'CK' => 'en_CK',
'CL' => 'es_CL',
'CM' => 'fr_CM',
'CN' => 'zh_Hans_CN',
'CO' => 'es_CO',
'CR' => 'es_CR',
'CU' => 'es_CU',
'CV' => 'kea_CV',
'CX' => 'en_CX',
'CY' => 'el_CY',
'CZ' => 'cs_CZ',
'DE' => 'de_DE',
'DJ' => 'aa_DJ',
'DK' => 'da_DK',
'DM' => 'en_DM',
'DO' => 'es_DO',
'DZ' => 'ar_DZ',
'EC' => 'es_EC',
'EE' => 'et_EE',
'EG' => 'ar_EG',
'EH' => 'ar_EH',
'ER' => 'ti_ER',
'ES' => 'es_ES',
'ET' => 'en_ET',
'FI' => 'fi_FI',
'FJ' => 'hi_FJ',
'FK' => 'en_FK',
'FM' => 'chk_FM',
'FO' => 'fo_FO',
'FR' => 'fr_FR',
'GA' => 'fr_GA',
'GB' => 'en_GB',
'GD' => 'en_GD',
'GE' => 'ka_GE',
'GF' => 'fr_GF',
'GG' => 'en_GG',
'GH' => 'ak_GH',
'GI' => 'en_GI',
'GL' => 'iu_GL',
'GM' => 'en_GM',
'GN' => 'fr_GN',
'GP' => 'fr_GP',
'GQ' => 'fan_GQ',
'GR' => 'el_GR',
'GS' => 'und_GS',
'GT' => 'es_GT',
'GU' => 'en_GU',
'GW' => 'pt_GW',
'GY' => 'en_GY',
'HK' => 'zh_Hant_HK',
'HM' => 'und_HM',
'HN' => 'es_HN',
'HR' => 'hr_HR',
'HT' => 'ht_HT',
'HU' => 'hu_HU',
'ID' => 'id_ID',
'IE' => 'en_IE',
'IL' => 'he_IL',
'IM' => 'en_IM',
'IN' => 'hi_IN',
'IO' => 'und_IO',
'IQ' => 'ar_IQ',
'IR' => 'fa_IR',
'IS' => 'is_IS',
'IT' => 'it_IT',
'JE' => 'en_JE',
'JM' => 'en_JM',
'JO' => 'ar_JO',
'JP' => 'ja_JP',
'KE' => 'en_KE',
'KG' => 'ky_Cyrl_KG',
'KH' => 'km_KH',
'KI' => 'en_KI',
'KM' => 'ar_KM',
'KN' => 'en_KN',
'KP' => 'ko_KP',
'KR' => 'ko_KR',
'KW' => 'ar_KW',
'KY' => 'en_KY',
'KZ' => 'ru_KZ',
'LA' => 'lo_LA',
'LB' => 'ar_LB',
'LC' => 'en_LC',
'LI' => 'de_LI',
'LK' => 'si_LK',
'LR' => 'en_LR',
'LS' => 'st_LS',
'LT' => 'lt_LT',
'LU' => 'fr_LU',
'LV' => 'lv_LV',
'LY' => 'ar_LY',
'MA' => 'ar_MA',
'MC' => 'fr_MC',
'MD' => 'ro_MD',
'ME' => 'sr_Latn_ME',
'MF' => 'fr_MF',
'MG' => 'mg_MG',
'MH' => 'mh_MH',
'MK' => 'mk_MK',
'ML' => 'bm_ML',
'MM' => 'my_MM',
'MN' => 'mn_Cyrl_MN',
'MO' => 'zh_Hant_MO',
'MP' => 'en_MP',
'MQ' => 'fr_MQ',
'MR' => 'ar_MR',
'MS' => 'en_MS',
'MT' => 'mt_MT',
'MU' => 'mfe_MU',
'MV' => 'dv_MV',
'MW' => 'ny_MW',
'MX' => 'es_MX',
'MY' => 'ms_MY',
'MZ' => 'pt_MZ',
'NA' => 'kj_NA',
'NC' => 'fr_NC',
'NE' => 'ha_Latn_NE',
'NF' => 'en_NF',
'NG' => 'en_NG',
'NI' => 'es_NI',
'NL' => 'nl_NL',
'NO' => 'nb_NO',
'NP' => 'ne_NP',
'NR' => 'en_NR',
'NU' => 'niu_NU',
'NZ' => 'en_NZ',
'OM' => 'ar_OM',
'PA' => 'es_PA',
'PE' => 'es_PE',
'PF' => 'fr_PF',
'PG' => 'tpi_PG',
'PH' => 'fil_PH',
'PK' => 'ur_PK',
'PL' => 'pl_PL',
'PM' => 'fr_PM',
'PN' => 'en_PN',
'PR' => 'es_PR',
'PS' => 'ar_PS',
'PT' => 'pt_PT',
'PW' => 'pau_PW',
'PY' => 'gn_PY',
'QA' => 'ar_QA',
'RE' => 'fr_RE',
'RO' => 'ro_RO',
'RS' => 'sr_Cyrl_RS',
'RU' => 'ru_RU',
'RW' => 'rw_RW',
'SA' => 'ar_SA',
'SB' => 'en_SB',
'SC' => 'crs_SC',
'SD' => 'ar_SD',
'SE' => 'sv_SE',
'SG' => 'en_SG',
'SH' => 'en_SH',
'SI' => 'sl_SI',
'SJ' => 'nb_SJ',
'SK' => 'sk_SK',
'SL' => 'kri_SL',
'SM' => 'it_SM',
'SN' => 'fr_SN',
'SO' => 'sw_SO',
'SR' => 'srn_SR',
'ST' => 'pt_ST',
'SV' => 'es_SV',
'SY' => 'ar_SY',
'SZ' => 'en_SZ',
'TC' => 'en_TC',
'TD' => 'fr_TD',
'TF' => 'und_TF',
'TG' => 'fr_TG',
'TH' => 'th_TH',
'TJ' => 'tg_Cyrl_TJ',
'TK' => 'tkl_TK',
'TL' => 'pt_TL',
'TM' => 'tk_TM',
'TN' => 'ar_TN',
'TO' => 'to_TO',
'TR' => 'tr_TR',
'TT' => 'en_TT',
'TV' => 'tvl_TV',
'TW' => 'zh_Hant_TW',
'TZ' => 'sw_TZ',
'UA' => 'uk_UA',
'UG' => 'sw_UG',
'UM' => 'en_UM',
'US' => 'en_US',
'UY' => 'es_UY',
'UZ' => 'uz_Cyrl_UZ',
'VA' => 'it_VA',
'VC' => 'en_VC',
'VE' => 'es_VE',
'VG' => 'en_VG',
'VI' => 'en_VI',
'VN' => 'vn_VN',
'VU' => 'bi_VU',
'WF' => 'wls_WF',
'WS' => 'sm_WS',
'YE' => 'ar_YE',
'YT' => 'swb_YT',
'ZA' => 'en_ZA',
'ZM' => 'en_ZM',
'ZW' => 'sn_ZW'
);
/**
* Store the transaltion for specific languages
*
* @var array
*/
protected $translation = array();
/**
* Current locale
*
* @var string
*/
protected $locale;
/**
* Default locale
*
* @var string
*/
protected $default_locale;
/**
*
* @var string
*/
protected $locale_dir;
/**
* Construct.
*
*
* @param string $locale_dir
*/
public function __construct($locale_dir)
{
$this->locale_dir = $locale_dir;
}
/**
* Set the user define localte
*
* @param string $locale
*/
public function setLocale($locale = null)
{
$this->locale = $locale;
return $this;
}
/**
* Get the user define locale
*
* @return string
*/
public function getLocale()
{
return $this->locale;
}
/**
* Get the Default locale
*
* @return string
*/
public function getDefaultLocale()
{
return $this->default_locale;
}
/**
* Set the default locale
*
* @param string $locale
*/
public function setDefaultLocale($locale)
{
$this->default_locale = $locale;
return $this;
}
/**
* Determine if transltion exist or translation key exist
*
* @param string $locale
* @param string $key
* @return boolean
*/
public function hasTranslation($locale, $key = null)
{
if (null == $key && isset($this->translation[$locale])) {
return true;
} elseif (isset($this->translation[$locale][$key])) {
return true;
}
return false;
}
/**
* Get the transltion for required locale or transtion for key
*
* @param string $locale
* @param string $key
* @return array
*/
public function getTranslation($locale, $key = null)
{
if (null == $key && $this->hasTranslation($locale)) {
return $this->translation[$locale];
} elseif ($this->hasTranslation($locale, $key)) {
return $this->translation[$locale][$key];
}
return array();
}
/**
* Set the transtion for required locale
*
* @param string $locale
* Language code
* @param string $trans
* translations array
*/
public function setTranslation($locale, $trans = array())
{
$this->translation[$locale] = $trans;
}
/**
* Remove transltions for required locale
*
* @param string $locale
*/
public function removeTranslation($locale = null)
{
if (null === $locale) {
unset($this->translation);
} else {
unset($this->translation[$locale]);
}
}
/**
* Initialize locale
*
* @param string $locale
*/
public function init($locale = null, $default_locale = null)
{
// check if previously set locale exist or not
$this->init_locale();
if ($this->locale != null) {
return;
}
if ($locale == null || (! preg_match('#^[a-z]+_[a-zA-Z_]+$#', $locale) && ! preg_match('#^[a-z]+_[a-zA-Z]+_[a-zA-Z_]+$#', $locale))) {
$this->detectLocale();
} else {
$this->locale = $locale;
}
$this->init_locale();
}
/**
* Attempt to autodetect locale
*
* @return void
*/
private function detectLocale()
{
$locale = false;
// GeoIP
if (function_exists('geoip_country_code_by_name') && isset($_SERVER['REMOTE_ADDR'])) {
$country = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
if ($country) {
$locale = isset($this->country_to_locale[$country]) ? $this->country_to_locale[$country] : false;
}
}
// Try detecting locale from browser headers
if (! $locale) {
if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
$languages = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
foreach ($languages as $lang) {
$lang = str_replace('-', '_', trim($lang));
if (strpos($lang, '_') === false) {
if (isset($this->country_to_locale[strtoupper($lang)])) {
$locale = $this->country_to_locale[strtoupper($lang)];
}
} else {
$lang = explode('_', $lang);
if (count($lang) == 3) {
// language_Encoding_COUNTRY
$this->locale = strtolower($lang[0]) . ucfirst($lang[1]) . strtoupper($lang[2]);
} else {
// language_COUNTRY
$this->locale = strtolower($lang[0]) . strtoupper($lang[1]);
}
return;
}
}
}
}
// Resort to default locale specified in config file
if (! $locale) {
$this->locale = $this->default_locale;
}
}
/**
* Check if config for selected locale exists
*
* @return void
*/
private function init_locale()
{
if (! file_exists(sprintf('%s/%s.php', $this->locale_dir, $this->locale))) {
$this->locale = $this->default_locale;
}
}
/**
* Load a Transtion into array
*
* @return void
*/
private function loadTranslation($locale = null, $force = false)
{
if ($locale == null)
$locale = $this->locale;
if (! $this->hasTranslation($locale)) {
$this->setTranslation($locale, include (sprintf('%s/%s.php', $this->locale_dir, $locale)));
}
}
/**
* Translate a key
*
* @param
* string Key to be translated
* @param
* string optional arguments
* @return string
*/
public function translate($key)
{
$this->init();
$this->loadTranslation($this->locale);
if (! $this->hasTranslation($this->locale, $key)) {
if ($this->locale !== $this->default_locale) {
$this->loadTranslation($this->default_locale);
if ($this->hasTranslation($this->default_locale, $key)) {
$translation = $this->getTranslation($this->default_locale, $key);
} else {
// return key as it is or log error here
return $key;
}
} else {
return $key;
}
} else {
$translation = $this->getTranslation($this->locale, $key);
}
// Replace arguments
if (false !== strpos($translation, '{a:')) {
$replace = array();
$args = func_get_args();
for ($i = 1, $max = count($args); $i < $max; $i ++) {
$replace['{a:' . $i . '}'] = $args[$i];
}
// interpolate replacement values into the messsage then return
return strtr($translation, $replace);
}
return $translation;
}
}
<?php
## /locale/en.php
return array(
'name' => 'Hello {a:1}'
'name_full' => 'Hello {a:1} {a:2}'
);
$locale = new Locale(__DIR__ . '/locale');
$locale->setLocale('en');// load en.php from locale dir
//want to work with auto detection comment $locale->setLocale('en');
echo $locale->translate('name', 'Foo');
echo $locale->translate('name', 'Foo', 'Bar');
{a:1}
is replaced by 1st argument passed to method Locale::translate('key_name','arg1')
{a:2}
is replaced by 2nd argument passed to method Locale::translate('key_name','arg1','arg2')
geoip
is installed then it will return country code by geoip_country_code_by_name
and if geoip is not installed the fallback to HTTP_ACCEPT_LANGUAGE
headerA method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.
Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.
In my case, I was looking for a solution that allows one of the navbar items to be right aligned. In order to do this, you must add style="width:100%;"
to the <ul class="navbar-nav">
and then add the ml-auto
class to your navbar item.
If you are in a JEE7 environment, you must have a decent implementation of JAXRS hanging around, which would allow you to easily make asynchronous HTTP request using its client API.
This would looks like this:
public class Main {
public static Future<Response> getAsyncHttp(final String url) {
return ClientBuilder.newClient().target(url).request().async().get();
}
public static void main(String ...args) throws InterruptedException, ExecutionException {
Future<Response> response = getAsyncHttp("http://www.nofrag.com");
while (!response.isDone()) {
System.out.println("Still waiting...");
Thread.sleep(10);
}
System.out.println(response.get().readEntity(String.class));
}
}
Of course, this is just using futures. If you are OK with using some more libraries, you could take a look at RxJava, the code would then look like:
public static void main(String... args) {
final String url = "http://www.nofrag.com";
rx.Observable.from(ClientBuilder.newClient().target(url).request().async().get(String.class), Schedulers
.newThread())
.subscribe(
next -> System.out.println(next),
error -> System.err.println(error),
() -> System.out.println("Stream ended.")
);
System.out.println("Async proof");
}
And last but not least, if you want to reuse your async call, you might want to take a look at Hystrix, which - in addition to a bazillion super cool other stuff - would allow you to write something like this:
For example:
public class AsyncGetCommand extends HystrixCommand<String> {
private final String url;
public AsyncGetCommand(final String url) {
super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("HTTP"))
.andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
.withExecutionIsolationThreadTimeoutInMilliseconds(5000)));
this.url = url;
}
@Override
protected String run() throws Exception {
return ClientBuilder.newClient().target(url).request().get(String.class);
}
}
Calling this command would look like:
public static void main(String ...args) {
new AsyncGetCommand("http://www.nofrag.com").observe().subscribe(
next -> System.out.println(next),
error -> System.err.println(error),
() -> System.out.println("Stream ended.")
);
System.out.println("Async proof");
}
PS: I know the thread is old, but it felt wrong that no ones mentions the Rx/Hystrix way in the up-voted answers.
This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:
Press the Windows + R keys to open the Run dialog, type
eventvwr.msc
, and press Enter.If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).
In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.
Do either step 5 or 6 below for what shutdown events you would like to see.
To See the Dates and Times of All User Shut Downs of the Computer
A) In Event sources, click/tap on the drop down arrow and check the
USER32
box.B) In the All Event IDs field, type
1074
, then click/tap on OK.C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.
D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.
E) Go to step 7.
To See the Dates and Times of All Unexpected Shut Downs of the Computer
A) In the All Event IDs field, type
6008
, then click/tap on OK.B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.
Pure javascript can do!
var scrollTop = window.pageYOffset || document.documentElement.scrollTop;
This get today date then tell the week number for the week
<?php
$date=date("W");
echo $date." Week Number";
?>
To prevent text selection ONLY after a double click:
You could use MouseEvent#detail
property.
For mousedown or mouseup events, it is 1 plus the current click count.
document.addEventListener('mousedown', function (event) {
if (event.detail > 1) {
event.preventDefault();
// of course, you still do not know what you prevent here...
// You could also check event.ctrlKey/event.shiftKey/event.altKey
// to not prevent something useful.
}
}, false);
See https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail
On Ubuntu and Debian systems, there are several steps needed:
In server.xml, change the line <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
to have port="80"
.
Install the recommended (not required) authbind package, with a command like:
sudo apt-get install authbind
Enable authbind in the server.xml file (in either /etc/tomcat6
or /etc/tomcat7
) by uncommenting and setting the line like:
AUTHBIND=yes
All three steps are needed.
This should get you started
<div class="menuBar">
<img class="logo" src="logo.jpg"/>
<div class="nav">
<ul>
<li>Menu1</li>
<li>Menu 2</li>
<li>Menu 3</li>
</ul>
</div>
</div>
body{
margin-top:50px;}
.menuBar{
width:100%;
height:50px;
display:block;
position:absolute;
top:0;
left:0;
}
.logo{
float:left;
}
.nav{
float:right;
margin-right:10px;}
.nav ul li{
list-style:none;
float:left;
}
#include <sstream>
#include <vector>
const char *input = "1,1,1,1,2,1,1,1,0";
int main() {
std::stringstream ss(input);
std::vector<int> output;
int i;
while (ss >> i) {
output.push_back(i);
ss.ignore(1);
}
}
Bad input (for instance consecutive separators) will mess this up, but you did say simple.
You should not use bash in this case to get rid of the output. Yum does have an option -q
which suppresses the output.
You'll most certainly also want to use -y
echo "Installing nano..."
yum -y -q install nano
To see all the options for yum, use man yum
.
You could also do this with a union query. As the number of columns increase, you would need to modify the query, but at least it would be a straight forward modification.
Select T.Id, T.Col1, T.Col2, T.Col3, A.TheMin
From YourTable T
Inner Join (
Select A.Id, Min(A.Col1) As TheMin
From (
Select Id, Col1
From YourTable
Union All
Select Id, Col2
From YourTable
Union All
Select Id, Col3
From YourTable
) As A
Group By A.Id
) As A
On T.Id = A.Id
None of the above answers worked for me using Hibernate 5.2.10, Jersey 2.25.1 and Jackson 2.8.9. I finally found the answer (sort of, they reference hibernate4module but it works for 5 too) here. None of the Json annotations worked at all with @Transient
. Apparently Jackson2 is 'smart' enough to kindly ignore stuff marked with @Transient
unless you explicitly tell it not to. The key was to add the hibernate5 module (which I was using to deal with other Hibernate annotations) and disable the USE_TRANSIENT_ANNOTATION
feature in my Jersey Application:
ObjectMapper jacksonObjectMapper = new ObjectMapper();
Hibernate5Module jacksonHibernateModule = new Hibernate5Module();
jacksonHibernateModule.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
jacksonObjectMapper.registerModule(jacksonHibernateModule);
Here is the dependency for the Hibernate5Module:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.8.9</version>
</dependency>
When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this:
GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1
Host: stackoverflow.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate,sdch
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cookie: <cookie data removed>
Pragma: no-cache
Cache-Control: no-cache
These information are all used by the web server to determine how to handle the request; the preferred language and whether compression is allowed.
In PHP, all this information is stored in the $_SERVER
array. To see what you're sending to a web server, create a new PHP file and print out everything from the array.
<pre><?php print_r($_SERVER); ?></pre>
This will give you a nice representation of everything that's being sent to the server, from where you can extract the desired information, e.g. $_SERVER['HTTP_USER_AGENT']
to get the operating system and browser.
Use preg_replace()
and instead of [ \t\n\r]
use \s
:
$output = preg_replace('!\s+!', ' ', $input);
From Regular Expression Basic Syntax Reference:
\d, \w and \s
Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.
The opposite of read
is show
.
Prelude> show 3
"3"
Prelude> read $ show 3 :: Int
3
Use TextAreaFor
@Html.TextAreaFor(model => model.Description, new { @class = "whatever-class", @cols = 80, @rows = 10 })
or use style for multi-line
class.
You could also write EditorTemplate for this.
I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe
which gives this value on my machine:
C:\Python25\Python.exe
You just read the registry key to get the location.
However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.
The formatter option '%x' % seems to work in assignment statements as well for me. (Assuming Python 3.0 and later)
Example
a = int('0x100', 16)
print(a) #256
print('%x' % a) #100
b = a
print(b) #256
c = '%x' % a
print(c) #100
Uninstall the old app from the device/emulator. It worked for me
up above we saw some with iteration. Let's do the same thing using forEach:
var funcs = [function () {
console.log(1)
},
function () {
console.log(2)
}
];
funcs.forEach(function (func) {
func(); // outputs 1, then 2
});
//for (i = 0; i < funcs.length; i++) funcs[i]();
A memory error means that your program has ran out of memory. This means that your program somehow creates too many objects.
In your example, you have to look for parts of your algorithm that could be consuming a lot of memory. I suspect that your program is given very long strings as inputs. Therefore, s[i:j+1]
could be the culprit, since it creates a new list. The first time you use it though, it is not necessary because you don't use the created list. You could try to see if the following helps:
if j + 1 < a:
sub_strings.append(s[i:j+1])
To replace the second list creation, you should definitely use a buffer object, as suggested by glglgl.
Also note that since you use if j >= i:
, you don't need to start your xrange
at 0. You can have:
for i in xrange(0, a):
for j in xrange(i, a):
# No need for if j >= i
A more radical alternative would be to try to rework your algorithm so that you don't pre-compute all possible sub-strings. Instead, you could simply compute the substring that are asked.
Here is another approach, up to the OP to choose which one he prefers.
When including the code below in the __init__
.py file before any other code, messages printed with print
and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:
import sys
path = "/Users/#username#"
errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog
(for Mac, change #username#
to the name of your user folder. On Windows the path to your user folder will have a different format)
When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.
Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella
Natural versus artificial keys to me is a matter of how much of the business logic you want in your database. Social Security number (SSN) is a great example.
"Each client in my database will, and must, have an SSN." Bam, done, make it the primary key and be done with it. Just remember when your business rule changes you're burned.
I don't like natural keys myself, due to my experience with changing business rules. But if your sure it won't change, it might prevent a few critical joins.
Very simply said, new X
is Object.create(X.prototype)
with additionally running the constructor
function. (And giving the constructor
the chance to return
the actual object that should be the result of the expression instead of this
.)
That’s it. :)
The rest of the answers are just confusing, because apparently nobody else reads the definition of new
either. ;)
Just use getActionBar().hide();
in your main activity onCreate()
method.
You can easily do this with a Hashmap
. You obviously have a key (which is the String data) and some values.
Loop on all your lines and add them to your Map.
Map<String, List<Integer>> map = new HashMap<>();
...
while (s.hasNext()){
String stringData = ...
List<Integer> values = ...
map.put(stringData,values);
}
Note that in this case, you will keep the last occurence of duplicate lines. If you prefer keeping the first occurence and removing the others, you can add a check with Map.containsKey(String stringData);
before putting in the map.
Normal Dict.values()
will return something like this
dict_values(['value1'])
dict_values(['value2'])
If you want only Values use
list(Dict.values())[0] # Under the List
In our company, we moved from SVN to Git. Lack of revision numbers was a big problem!
Do git svn clone
, and then tag the last SVN commit by its SVN revision number:
export hr=`git svn find-rev HEAD`
git tag "$hr" -f HEAD
Then you can get the revision number with help of
git describe --tags --long
This command gives something like:
7603-3-g7f4610d
Means: The last tag is 7603 - it's the SVN revision. 3 - is count of commits from it. We need to add them.
So, the revision number can be counted by this script:
expr $(git describe --tags --long | cut -d '-' -f 1) + $(git describe --tags --long | cut -d '-' -f 2)
You could use the (chainable, but lazily evaluated) Select
, first doing your operation, and then returning identity (or something else if you prefer)
IEnumerable<string> people = new List<string>(){"alica", "bob", "john", "pete"};
people.Select(p => { Console.WriteLine(p); return p; });
You will need to make sure it is still evaluated, either with Count()
(the cheapest operation to enumerate afaik) or another operation you needed anyway.
I would love to see it brought in to the standard library though:
static IEnumerable<T> WithLazySideEffect(this IEnumerable<T> src, Action<T> action) {
return src.Select(i => { action(i); return i; } );
}
The above code then becomes people.WithLazySideEffect(p => Console.WriteLine(p))
which is effectively equivalent to foreach, but lazy and chainable.
Set the html tag, too. This way no weird position hacks are required.
html, body {height: 100%}
<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>
To read a specific set of columns from a dataset you, there are several other options:
1) With fread
from the data.table
-package:
You can specify the desired columns with the select
parameter from fread
from the data.table
package. You can specify the columns with a vector of column names or column numbers.
For the example dataset:
library(data.table)
dat <- fread("data.txt", select = c("Year","Jan","Feb","Mar","Apr","May","Jun"))
dat <- fread("data.txt", select = c(1:7))
Alternatively, you can use the drop
parameter to indicate which columns should not be read:
dat <- fread("data.txt", drop = c("Jul","Aug","Sep","Oct","Nov","Dec"))
dat <- fread("data.txt", drop = c(8:13))
All result in:
> data
Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27 -2 -6 -10 -32
UPDATE: When you don't want fread
to return a data.table, use the data.table = FALSE
-parameter, e.g.: fread("data.txt", select = c(1:7), data.table = FALSE)
2) With read.csv.sql
from the sqldf
-package:
Another alternative is the read.csv.sql
function from the sqldf
package:
library(sqldf)
dat <- read.csv.sql("data.txt",
sql = "select Year,Jan,Feb,Mar,Apr,May,Jun from file",
sep = "\t")
3) With the read_*
-functions from the readr
-package:
library(readr)
dat <- read_table("data.txt",
col_types = cols_only(Year = 'i', Jan = 'i', Feb = 'i', Mar = 'i',
Apr = 'i', May = 'i', Jun = 'i'))
dat <- read_table("data.txt",
col_types = list(Jul = col_skip(), Aug = col_skip(), Sep = col_skip(),
Oct = col_skip(), Nov = col_skip(), Dec = col_skip()))
dat <- read_table("data.txt", col_types = 'iiiiiii______')
From the documentation an explanation for the used characters with col_types
:
each character represents one column: c = character, i = integer, n = number, d = double, l = logical, D = date, T = date time, t = time, ? = guess, or _/- to skip the column
max-device-width is the device rendering width
@media all and (max-device-width: 400px) {
/* styles for devices with a maximum width of 400px and less
Changes only on device orientation */
}
@media all and (max-width: 400px) {
/* styles for target area with a maximum width of 400px and less
Changes on device orientation , browser resize */
}
The max-width is the width of the target display area means the current size of browser.
Try a simple where query
var filtered = unfilteredApps.Where(i => !excludedAppIds.Contains(i.Id));
The except method uses equality, your lists contain objects of different types, so none of the items they contain will be equal!
I don't like to use regex, so here is another simple solution.
public String removePunctuations(String s) {
String res = "";
for (Character c : s.toCharArray()) {
if(Character.isLetterOrDigit(c))
res += c;
}
return res;
}
Note: This will include both Letters and Digits
FETCH_HEAD
is a short-lived ref, to keep track of what has just been fetched from the remote repository. git pull
first invokes git fetch
, in normal cases fetching a branch from the remote; FETCH_HEAD
points to the tip of this branch (it stores the SHA1 of the commit, just as branches do). git pull
then invokes git merge
, merging FETCH_HEAD
into the current branch.
The result is exactly what you'd expect: the commit at the tip of the appropriate remote branch is merged into the commit at the tip of your current branch.
This is a bit like doing git fetch
without arguments (or git remote update
), updating all your remote branches, then running git merge origin/<branch>
, but using FETCH_HEAD
internally instead to refer to whatever single ref was fetched, instead of needing to name things.
"At run time, the authorization module iterates through the allow and deny elements, starting at the most local configuration file, until the authorization module finds the first access rule that fits a particular user account. Then, the authorization module grants or denies access to a URL resource depending on whether the first access rule found is an allow or a deny rule. The default authorization rule is . Thus, by default, access is allowed unless configured otherwise."
Article at MSDN
deny = * means deny everyone
deny = ? means deny unauthenticated users
In your 1st example deny * will not affect dan, matthew since they were already allowed by the preceding rule.
According to the docs, here is no difference in your 2 rule sets.
these will both work in Python 2.7 and Python 3.x:
>>> l = [1, 2, 3]
>>> print(' '.join(str(x) for x in l))
1 2 3
>>> print(' '.join(map(str, l)))
1 2 3
btw, array
is a reserved word in Python.
Based on bryanmac's answer. I'm just saving all logs into one file and then reading it with tail. Simple, but effective way to do this.
forever -o common.log -e common.log index.js && tail -f common.log
I guess you're learning how to Python. The other answers are right. But I am going to answer your main question: "how to calculate percentage in python"
Although it works the way you did it, it doesn´t look very pythonic. Also, what happens if you need to add a new subject? You'll have to add another variable, use another input, etc. I guess you want the average of all marks, so you will also have to modify the count of the subjects everytime you add a new one! Seems a mess...
I´ll throw a piece of code where the only thing you'll have to do is to add the name of the new subject in a list. If you try to understand this simple piece of code, your Python coding skills will experiment a little bump.
#!/usr/local/bin/python2.7
marks = {} #a dictionary, it's a list of (key : value) pairs (eg. "Maths" : 34)
subjects = ["Tamil","English","Maths","Science","Social"] # this is a list
#here we populate the dictionary with the marks for every subject
for subject in subjects:
marks[subject] = input("Enter the " + subject + " marks: ")
#and finally the calculation of the total and the average
total = sum(marks.itervalues())
average = float(total) / len(marks)
print ("The total is " + str(total) + " and the average is " + str(average))
Here you can test the code and experiment with it.
Here is one possible solution of first part
#include<iostream>
using namespace std;
int main()
{
int marks[][4] = {
10, 20, 30, 50,
40, 50, 60, 60,
10, 20, 10, 70
};
int rows = sizeof(marks)/sizeof(marks[0]);
int cols = sizeof(marks)/(sizeof(int)*rows);
for(int i=0; i<rows; i++)
{
for(int j=0; j<cols; j++)
{
cout<<marks[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
You can try out this code. Since you cannot override valueOf
method you have to define a custom method (getEnum
in the sample code below) which returns the value that you need and change your client to use this method instead.
public enum RandomEnum {
StartHere("Start Here"),
StopHere("Stop Here");
private String value;
RandomEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return this.getValue();
}
public static RandomEnum getEnum(String value) {
for(RandomEnum v : values())
if(v.getValue().equalsIgnoreCase(value)) return v;
throw new IllegalArgumentException();
}
}
Old question, but I sure wish I read this answer here before I started my own search for a good solution. Calligraphy extends the android:fontFamily
attribute to add support for custom fonts in your asset folder, like so:
<TextView
android:text="@string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="fonts/Roboto-Bold.ttf"/>
The only thing you have to do to activate it is attaching it to the Context of the Activity you're using:
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(new CalligraphyContextWrapper(newBase));
}
You can also specify your own custom attribute to replace android:fontFamily
It also works in themes, including the AppTheme.
On Linux, you can read from /proc/sys/kernel/random/uuid
:
package main
import "io/ioutil"
import "fmt"
func main() {
u, _ := ioutil.ReadFile("/proc/sys/kernel/random/uuid")
fmt.Println(string(u))
}
No external dependencies!
$ go run uuid.go
3ee995e3-0c96-4e30-ac1e-f7f04fd03e44
Simpler with the ANY
construct:
SELECT value_variable = ANY ('{1,2,3}'::int[])
The right operand of ANY
(between parentheses) can either be a set (result of a subquery, for instance) or an array. There are several ways to use it:
Important difference: Array operators (<@
, @>
, &&
et al.) expect array types as operands and support GIN or GiST indices in the standard distribution of PostgreSQL, while the ANY
construct expects an element type as left operand and does not support these indices. Example:
None of this works for NULL
elements. To test for NULL
:
Just do this:
var $div = $('div');
var a = 0;
setInterval(function() {
a++;
$div.stop(true,true).css("left", a);
}, 1000 / 30);
Inactive browser tabs buffer some of the setInterval
or setTimeout
functions.
stop(true,true)
will stop all buffered events and execute immediatly only the last animation.
The window.setTimeout()
method now clamps to send no more than one timeout per second in inactive tabs. In addition, it now clamps nested timeouts to the smallest value allowed by the HTML5 specification: 4 ms (instead of the 10 ms it used to clamp to).
Try this
SELECT TOP 1 salary FROM (
SELECT TOP 3 salary
FROM employees
ORDER BY salary DESC) AS emp
ORDER BY salary ASC
For 3 you can replace any value...
There is delete
, delete_all
, destroy
, and destroy_all
.
The docs are: older docs and Rails 3.0.0 docs
delete
doesn't instantiate the objects, while destroy
does. In general, delete
is faster than destroy
.
Use LayoutParams (as explained already). However be careful which LayoutParams to choose. According to https://stackoverflow.com/a/11971553/3184778 "you need to use the one that relates to the PARENT of the view you're working on, not the actual view"
If for example the TextView is inside a TableRow, then you need to use TableRow.LayoutParams instead of RelativeLayout or LinearLayout
I use Visual Studio git plugin, and I have some websites running on IIS I wanted to move. A simple way that worked for me:
Close Visual Studio.
Move the code (including git folder, etc)
Click on the solution file from the new location
This refreshes the mapping to the new location, using the existing local git files that were moved. Once i was back in Visual Studio, my Team Explorer window showed the repos in the new location.
table td
{
table-layout:fixed;
width:20px;
overflow:hidden;
word-wrap:break-word;
}
You could cast it to DECIMAL and specify the scale to be 2 digits
So, something like
DECLARE @i AS FLOAT = 2
SELECT @i / 3
SELECT CAST(@i / 3 AS DECIMAL(18,2))
I would however recomend that this be done in the UI/Report layer, as this will cuase loss of precision.
Formatting (in my opinion) should happen on the UI/Report/Display level.
Adding my own experience for those who are experiencing this in the future. My specific error was
Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'
It turns out that this was actually because I had reach the maximum number of open files on my system. It had nothing to do with failed connections, or even a DNS error as indicated.
This solution comes from my personal experience. We used several Amazon S3 buckets and one server for redirecting non-www
to www
domain names to match S3 "Host" header policy.
I used the following configuration for nginx server:
server {
listen 80;
server_name ~^(?!www\.)(?<domain>.+)$;
return 301 $scheme://www.$domain$request_uri;
}
This matches all domain names pointed to the server starting with whatever but www.
and redirects to www.<domain>
. In the same manner you can do opposite redirect from www
to non-www
.
What about a new end point > /api/members/count which just calls Members.Count() and returns the result
It is always encouraged in C++ that you have one class per header file, see this discussion in SO [1].
GManNickG answer's tells why this happen. But the best way to solve this is to put User
class in one header file (User.h
) and MyMessageBox
class in another header file (MyMessageBox.h
). Then in your User.h
you include MyMessageBox.h
and in MyMessageBox.h
you include User.h
. Do not forget "include gaurds" [2] so that your code compiles successfully.
Unfortunately, you need to manually fire the change
event. And using the Event Constructor will be the best solution.
var select = document.querySelector('#sel'),_x000D_
input = document.querySelector('input[type="button"]');_x000D_
select.addEventListener('change',function(){_x000D_
alert('changed');_x000D_
});_x000D_
input.addEventListener('click',function(){_x000D_
select.value = 2;_x000D_
select.dispatchEvent(new Event('change'));_x000D_
});
_x000D_
<select id="sel" onchange='alert("changed")'>_x000D_
<option value='1'>One</option>_x000D_
<option value='2'>Two</option>_x000D_
<option value='3' selected>Three</option>_x000D_
</select>_x000D_
<input type="button" value="Change option to 2" />
_x000D_
And, of course, the Event
constructor is not supported in IE. So you may need to polyfill with this:
function Event( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
return evt;
}
Use the keyword size
instead of fontsize
.
It should be
Intent myIntent = new Intent(this, Katra_home.class);
startActivity(myIntent);
You have to use existing activity context to start new activity, new activity is not created yet, and you cannot use its context or call methods upon it.
not an enclosing class error is thrown because of your usage of this
keyword. this
is a reference to the current object — the object whose method or constructor is being called. With this
you can only refer to any member of the current object from within an instance method or a constructor.
Katra_home.this
is invalid construct
I've had this same problem, and I wrote a one-liner in shell to do it.
rm -rf $(mvn help:evaluate -Dexpression=settings.localRepository\
-Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -B \
-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn | grep -vF '[INFO]')/*
I did it as a one-liner because I wanted to have a Jenkins-project to simply run this whenever I needed, so I wouldn't have to log on to stuff, etc. If you allow yourself a shell-script for it, you can write it cleaner:
#!/usr/bin/env bash
REPOSITORY=$(mvn help:evaluate \
-Dexpression=settings.localRepository \
-Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn \
--batch-mode \
| grep -vF '[INFO]')
rm -rf $REPOSITORY/*
Should work, but I have not tested all of that script. (I've tested the first command, but not the whole script.) This approach has the downside of running a large complicated command first. It is idempotent, so you can test it out for yourself. The deletion is its own command afterwards, and this lets you try it all out and check that it does what you think it does, because you shouldn't trust deletion commands without verification. However, it is smart for one good reason: It's portable. It respects your settings.xml file. If you're running this command, and tell maven to use a specific xml file (the -s or --settings argument), this will still work. So you don't have to fiddle with making sure everything is the same everywhere.
It's a bit wieldy, but it's a decent way of doing business, IMO.
Look up \enlargethispage
in some LaTeX reference.
When both values are zero, then the change is zero.
If one of the values is zero, it's infinite (ambiguous), but I would set it to 100%.
Here is a C++ code (where v1
is the previous value (old), and v2
is new):
double result = 0;
if (v1 != 0 && v2 != 0) {
// If values are non-zero, use the standard formula.
result = (v2 / v1) - 1;
} else if (v1 == 0 || v2 == 0) {
// Change is zero when both values are zeros, otherwise it's 100%.
result = v1 == 0 && v2 == 0 ? 0 : 1;
}
result = v2 > v1 ? abs(result) : -abs(result);
// Note: To have format in hundreds, multiply the result by 100.
In my case the issue was due to incorrect build order. One project had an xcopy command on post-build events to copy files from bin folder to another folder. But because of incorrect dependencies new files were getting created in bin folder while xcopy is in progress.
In VS right click on the project where you have post-build events. Go to Build Dependencies > Project Dependencies and make sure its correct. Verify the project build order(next tab to dependencies) as well.
Update: AdoptOpenJDK has changed its name to Adoptium, as part of its move to the Eclipse Foundation.
Difference between OpenJDK and AdoptOpenJDK
The first provides source-code, the other provides builds of that source-code.
Adoptium of the Eclipse Foundation, formerly known as AdoptOpenJDK, is only one of several vendors distributing implementations of the Java platform. These include:
See this flowchart of mine to help guide you in picking a vendor for an implementation of the Java platform. Click/tap to zoom.
Another resource: This comparison matrix by Azul Systems is useful, and seems true and fair to my mind.
Here is a list of considerations and motivations to consider in choosing a vendor and implementation.
Some vendors offer you a choice of JIT technologies.
To understand more about this Java ecosystem, read Java Is Still Free
In such case look at gradle console
it will show the issue in detail with exact location which led to this compilation error.
In my case I was using Butterknife
in one of my class and I had auto-converted
that class to kotlin
using android studio's utility
Log in Gradle Console
Executing tasks: [:app:assembleDebug]
Configuration on demand is an incubating feature.
Configuration 'compile' in project ':app' is deprecated. Use 'implementation' instead.
registerResGeneratingTask is deprecated, use registerGeneratedFolders(FileCollection)
:app:buildInfoDebugLoader
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:checkDebugManifest UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:processDebugGoogleServices
Parsing json file: /Users/Downloads/myproject/app/google-services.json
:app:mergeDebugResources UP-TO-DATE
:app:createDebugCompatibleScreenManifests UP-TO-DATE
:app:processDebugManifest
:app:splitsDiscoveryTaskDebug UP-TO-DATE
:app:processDebugResources
:app:kaptGenerateStubsDebugKotlin
Using kotlin incremental compilation
:app:kaptDebugKotlin
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:10: error: @BindView fields must not be private or static. (com.myproject.util.ConfirmationDialog.imgConfirmationLogo)
e:
e: private android.widget.ImageView imgConfirmationLogo;
e: ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:13: error: @BindView fields must not be private or static. (com.myproject.util.ConfirmationDialog.txtConfirmationDialogTitle)
e:
e: private android.widget.TextView txtConfirmationDialogTitle;
e: ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:16: error: @BindView fields must not be private or static. (com.myproject.util.ConfirmationDialog.txtConfirmationDialogMessage)
e:
e: private android.widget.TextView txtConfirmationDialogMessage;
e: ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:19: error: @BindView fields must not be private or static. (com.myproject.util.ConfirmationDialog.txtViewPositive)
e:
e: private android.widget.TextView txtViewPositive;
e: ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ConfirmationDialog.java:22: error: @BindView fields must not be private or static. (com.pokkt.myproject.ConfirmationDialog.txtViewNegative)
e:
e: private android.widget.TextView txtViewNegative;
e: ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ExitDialog.java:10: error: @BindView fields must not be private or static. (com.myproject.util.ExitDialog.txtViewPositive)
e:
e: private android.widget.TextView txtViewPositive;
e: ^
e: /Users/Downloads/myproject/app/build/tmp/kapt3/stubs/debug/com/myproject/util/ExitDialog.java:13: error: @BindView fields must not be private or static. (com.myproject.util.ExitDialog.txtViewNegative)
e:
e: private android.widget.TextView txtViewNegative;
e: ^
e: java.lang.IllegalStateException: failed to analyze: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
at org.jetbrains.kotlin.analyzer.AnalysisResult.throwIfError(AnalysisResult.kt:57)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:144)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:167)
at org.jetbrains.kotlin.cli.jvm.K2JVMCompiler.doExecute(K2JVMCompiler.kt:55)
at org.jetbrains.kotlin.cli.common.CLICompiler.exec(CLICompiler.java:182)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.execCompiler(CompileServiceImpl.kt:397)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$execCompiler(CompileServiceImpl.kt:99)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:365)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1$2.invoke(CompileServiceImpl.kt:99)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$2$$special$$inlined$withValidClientOrSessionProxy$lambda$1.invoke(CompileServiceImpl.kt:798)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$2$$special$$inlined$withValidClientOrSessionProxy$lambda$1.invoke(CompileServiceImpl.kt:99)
at org.jetbrains.kotlin.daemon.common.DummyProfiler.withMeasure(PerfUtils.kt:137)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.checkedCompile(CompileServiceImpl.kt:825)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$checkedCompile(CompileServiceImpl.kt:99)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$2.invoke(CompileServiceImpl.kt:797)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$doCompile$2.invoke(CompileServiceImpl.kt:99)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.ifAlive(CompileServiceImpl.kt:1004)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.ifAlive$default(CompileServiceImpl.kt:865)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.doCompile(CompileServiceImpl.kt:791)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.access$doCompile(CompileServiceImpl.kt:99)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1.invoke(CompileServiceImpl.kt:364)
at org.jetbrains.kotlin.daemon.CompileServiceImpl$compile$1.invoke(CompileServiceImpl.kt:99)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.ifAlive(CompileServiceImpl.kt:1004)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.ifAlive$default(CompileServiceImpl.kt:865)
at org.jetbrains.kotlin.daemon.CompileServiceImpl.compile(CompileServiceImpl.kt:336)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:346)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.jetbrains.kotlin.kapt3.diagnostic.KaptError: Error while annotation processing
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing(annotationProcessing.kt:90)
at org.jetbrains.kotlin.kapt3.AnnotationProcessingKt.doAnnotationProcessing$default(annotationProcessing.kt:42)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.runAnnotationProcessing(Kapt3Extension.kt:205)
at org.jetbrains.kotlin.kapt3.AbstractKapt3Extension.analysisCompleted(Kapt3Extension.kt:166)
at org.jetbrains.kotlin.kapt3.ClasspathBasedKapt3Extension.analysisCompleted(Kapt3Extension.kt:82)
at org.jetbrains.kotlin.resolve.jvm.TopDownAnalyzerFacadeForJVM$analyzeFilesWithJavaIntegration$2.invoke(TopDownAnalyzerFacadeForJVM.kt:89)
at org.jetbrains.kotlin.resolve.jvm.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration(TopDownAnalyzerFacadeForJVM.kt:99)
at org.jetbrains.kotlin.resolve.jvm.TopDownAnalyzerFacadeForJVM.analyzeFilesWithJavaIntegration$default(TopDownAnalyzerFacadeForJVM.kt:76)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler$analyze$1.analyze(KotlinToJVMBytecodeCompiler.kt:365)
at org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport.analyzeAndReport(AnalyzerWithCompilerReport.kt:105)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.analyze(KotlinToJVMBytecodeCompiler.kt:354)
at org.jetbrains.kotlin.cli.jvm.compiler.KotlinToJVMBytecodeCompiler.compileModules(KotlinToJVMBytecodeCompiler.kt:139)
... 40 more
FAILED
:app:buildInfoGeneratorDebug
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:kaptDebugKotlin'.
> Internal compiler error. See log for more details
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED in 32s
16 actionable tasks: 7 executed, 9 up-to-date
As in my log it clearly shows issues are with declaration of variables with butterknife. So I looked into this issue and was able to solve it.
You want the mod operator.
The expression a Mod b is equivalent to the following formula:
a - (b * (a \ b))
Edited to add:
There are some special cases you may have to consider, because Excel is using floating point math (and returns a float
), which the VBA function returns an integer. Because of this, using mod
with floating-point numbers may require extra attention:
Excel's results may not correspond exactly with what you would predict; this is covered briefly here (see topmost answer) and at great length here.
As @André points out in the comments, negative numbers may round in the opposite direction from what you expect. The Fix()
function he suggests is explained here (MSDN).
I think this would work
moment().weekday(); //if today is thursday it will return 4
For me, using margin:15px;padding:10px 0 15px 23px;width:100%
, the result was this:
The solution for me was to use width:auto
instead of width:100%
. My new code was:
margin:15px;padding:10px 0 15px 23px;width:auto
. Then the element aligned properly:
You can use elevation property for Android if you don't mind the shadow.
{
elevation:1
}
For Spring 2.5, there's no @Primary
. The only way is to use @Qualifier
.
This way worked for me:
adding the path that you like:
export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add
checking: you can run 'export' cmd and check the output or you can check it using this cmd:
python -c "import sys; print(sys.path)"
If you don't want to install anything but do want to download an SVN or GIT repository, then you can use this: http://downloadsvn.codeplex.com/
I have nothing to do with this project, but I just used it now and it saved me a few minutes. Maybe it will help someone.
@hash{@array} = (1) x @array;
It's a hash slice, a list of values from the hash, so it gets the list-y @ in front.
From the docs:
If you're confused about why you use an '@' there on a hash slice instead of a '%', think of it like this. The type of bracket (square or curly) governs whether it's an array or a hash being looked at. On the other hand, the leading symbol ('$' or '@') on the array or hash indicates whether you are getting back a singular value (a scalar) or a plural one (a list).
I had the same question. I have tried all solutions provided above and none of them worked... But I have found a solution that works for me, and hopefully for others too.
<center>
![your image caption](image.png)
</center>
This code will center both the image and the caption. It is essential that you leave lines between <center>
, the image code, and </center>
, otherwise the image will be centered but the caption will disappear.
If you want your image to have a clickable link, you can embed things like
[![your image caption](image.png)](www.link_to_image.com)
However, the caption will no longer appear.
So if you want a clickable caption you will have to do it in two steps:
<center>
![](image.png)
[your image caption](www.link_to_image.com)
</center>
Same here, make sure there are empty lines in between each command ones. If you want both the image and the caption to be clickable, then combine the middle and the last codes above. I hope this helps a bit.
You can use
a.Except(b).Union(b.Except(a));
Or you can use
var difference = new HashSet(a);
difference.SymmetricExceptWith(b);
<td class="first"> <?php echo $proxy ?> </td>
is inside a literal string that you are echo
ing. End the string, or concatenate it correctly:
<td class="first">' . $proxy . '</td>
\r
is the ASCII Carriage Return (CR) character.
There are different newline conventions used by different operating systems. The most common ones are:
\r\n
);\n
);\r
).The \n\r
(LF+CR) looks unconventional.
edit: My reading of the Telnet RFC suggests that:
The sequence "CR LF", as defined, will cause the NVT to be positioned at the left margin of the next print line (as would, for example, the sequence "LF CR").
for s in `cmd`; do echo $s; done
If cmd has a large output:
cmd | xargs -L1 echo
There are three ways to save objects from your R session:
The save.image()
function will save all objects currently in your R session:
save.image(file="1.RData")
These objects can then be loaded back into a new R session using the load()
function:
load(file="1.RData")
If you want to save some, but not all objects, you can use the save()
function:
save(city, country, file="1.RData")
Again, these can be reloaded into another R session using the load()
function:
load(file="1.RData")
If you want to save a single object you can use the saveRDS()
function:
saveRDS(city, file="city.rds")
saveRDS(country, file="country.rds")
You can load these into your R session using the readRDS()
function, but you will need to assign the result into a the desired variable:
city <- readRDS("city.rds")
country <- readRDS("country.rds")
But this also means you can give these objects new variable names if needed (i.e. if those variables already exist in your new R session but contain different objects):
city_list <- readRDS("city.rds")
country_vector <- readRDS("country.rds")
Looks like the path you gave doesn't have any bootstrap files in them.
href="~/lib/bootstrap/dist/css/bootstrap.min.css"
Make sure the files exist over there , else point the files to the correct path, which should be in your case
href="~/node_modules/bootstrap/dist/css/bootstrap.min.css"
cPickle
comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle
, you can do this:
>>> import _pickle as cPickle
However, in 3.x, it's easier just to use pickle
.
No need to install anything. If something requires cPickle
in python 3.x, then that's probably a bug.
You should use the CameraUpdate
class to do (probably) all programmatic map movements.
To do this, first calculate the bounds of all the markers like so:
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();
Then obtain a movement description object by using the factory: CameraUpdateFactory
:
int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);
Finally move the map:
googleMap.moveCamera(cu);
Or if you want an animation:
googleMap.animateCamera(cu);
That's all :)
Clarification 1
Almost all movement methods require the Map
object to have passed the layout process. You can wait for this to happen using the addOnGlobalLayoutListener
construct. Details can be found in comments to this answer and remaining answers. You can also find a complete code for setting map extent using addOnGlobalLayoutListener
here.
Clarification 2
One comment notes that using this method for only one marker results in map zoom set to a "bizarre" zoom level (which I believe to be maximum zoom level available for given location). I think this is expected because:
LatLngBounds bounds
instance will have northeast
property equal to southwest
, meaning that the portion of area of the earth covered by this bounds
is exactly zero. (This is logical since a single marker has no area.)bounds
to CameraUpdateFactory.newLatLngBounds
you essentially request a calculation of such a zoom level that bounds
(having zero area) will cover the whole map view.Map
object doesn't support this value so it is clamped to a more reasonable maximum level allowed for given location.Another way to put it: how can Map
object know what zoom level should it choose for a single location? Maybe the optimal value should be 20 (if it represents a specific address). Or maybe 11 (if it represents a town). Or maybe 6 (if it represents a country). API isn't that smart and the decision is up to you.
So, you should simply check if markers
has only one location and if so, use one of:
CameraUpdate cu = CameraUpdateFactory.newLatLng(marker.getPosition())
- go to marker position, leave current zoom level intact.CameraUpdate cu = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), 12F)
- go to marker position, set zoom level to arbitrarily chosen value 12.When I'm working with csv
files, I often use the pandas library. It makes things like this very easy. For example:
import pandas as pd
a = pd.read_csv("filea.csv")
b = pd.read_csv("fileb.csv")
b = b.dropna(axis=1)
merged = a.merge(b, on='title')
merged.to_csv("output.csv", index=False)
Some explanation follows. First, we read in the csv files:
>>> a = pd.read_csv("filea.csv")
>>> b = pd.read_csv("fileb.csv")
>>> a
title stage jan feb
0 darn 3.001 0.421 0.532
1 ok 2.829 1.036 0.751
2 three 1.115 1.146 2.921
>>> b
title mar apr may jun Unnamed: 5
0 darn 0.631 1.321 0.951 1.7510 NaN
1 ok 1.001 0.247 2.456 0.3216 NaN
2 three 0.285 1.283 0.924 956.0000 NaN
and we see there's an extra column of data (note that the first line of fileb.csv
-- title,mar,apr,may,jun,
-- has an extra comma at the end). We can get rid of that easily enough:
>>> b = b.dropna(axis=1)
>>> b
title mar apr may jun
0 darn 0.631 1.321 0.951 1.7510
1 ok 1.001 0.247 2.456 0.3216
2 three 0.285 1.283 0.924 956.0000
Now we can merge a
and b
on the title column:
>>> merged = a.merge(b, on='title')
>>> merged
title stage jan feb mar apr may jun
0 darn 3.001 0.421 0.532 0.631 1.321 0.951 1.7510
1 ok 2.829 1.036 0.751 1.001 0.247 2.456 0.3216
2 three 1.115 1.146 2.921 0.285 1.283 0.924 956.0000
and finally write this out:
>>> merged.to_csv("output.csv", index=False)
producing:
title,stage,jan,feb,mar,apr,may,jun
darn,3.001,0.421,0.532,0.631,1.321,0.951,1.751
ok,2.829,1.036,0.751,1.001,0.247,2.456,0.3216
three,1.115,1.146,2.921,0.285,1.283,0.924,956.0
Similar to unutbu above, you could also use applymap
as follows:
import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
index=['foo','bar','baz','quux'],
columns=['cost'])
df = df.applymap("${0:.2f}".format)
You can try the display:inline-block and :after.Like this:
<ul>
<li><a href="">I would like this text centered vertically</a></li>
</ul>
li a {
width: 300px;
height: 100px;
margin: auto 0;
display: inline-block;
vertical-align: middle;
background: red;
}
li a:after {
content:"";
display: inline-block;
width: 1px solid transparent;
height: 100%;
vertical-align: middle;
}
Please view the demo.
git checkout branch1
git fetch origin
git rebase -p origin/mainbranch
If there are merge conflicts, fix them. Then, continue the rebase process by running: git rebase –-continue
after the fixing you can commit and push your local branch to remote branch
git push origin branch1
Windows -> Preferences -> Java Compiler
Open eclipse.ini
in the installation directory, and observe the line with text:
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.0.200.v20090519 then it is 64 bit.
If it would be plugins/org.eclipse.equinox.launcher.win32.win32.x86_32_1.0.200.v20090519 then it is 32 bit.
Complete solution for mysql current month and current year, which makes use of indexing properly as well :)
-- Current month
SELECT id, timestampfield
FROM table1
WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY)
AND timestampfield <= LAST_DAY(CURRENT_DATE);
-- Current year
SELECT id, timestampfield
FROM table1
WHERE timestampfield >= DATE_SUB(CURRENT_DATE, INTERVAL DAYOFYEAR(CURRENT_DATE)-1 DAY)
AND timestampfield <= LAST_DAY(CURRENT_DATE);
This does it in text.
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>_x000D_
_x000D_
<script type="text/javascript">_x000D_
var timeleft = 10;_x000D_
var downloadTimer = setInterval(function(){_x000D_
timeleft--;_x000D_
document.getElementById("countdowntimer").textContent = timeleft;_x000D_
if(timeleft <= 0)_x000D_
clearInterval(downloadTimer);_x000D_
},1000);_x000D_
</script>
_x000D_
I recommend using https://www.npmjs.com/package/express-es6-template-engine - extremely lightwave and blazingly fast template engine. The name is a bit misleading as it can work without expressjs too.
The basics required to integrate express-es6-template-engine
in your app are pretty simple and quite straight forward to implement:
const express = require('express'),_x000D_
es6Renderer = require('express-es6-template-engine'),_x000D_
app = express();_x000D_
_x000D_
app.engine('html', es6Renderer);_x000D_
app.set('views', 'views');_x000D_
app.set('view engine', 'html');_x000D_
_x000D_
app.get('/', function(req, res) {_x000D_
res.render('index', {locals: {title: 'Welcome!'}});_x000D_
});_x000D_
_x000D_
app.listen(3000);
_x000D_
index.html
file locate inside your 'views' directory:
<!DOCTYPE html>
<html>
<body>
<h1>${title}</h1>
</body>
</html>
It holds stuff like class definitions, string pool, etc. I guess you could call it meta-data.
It can be done by using ecapture First, run
pip install ecapture
Then in a new python script type:
from ecapture import ecapture as ec
ec.capture(0,"test","img.jpg")
More information from thislink
Just another solution using underscore.js:
_.extend({}, obj1, obj2);
The min-width
property does not work correctly in Internet Explorer, which is most likely the cause of your problems.
Read info and a brilliant script that fixes many IE CSS problems.
@AnsgarWiechers - it's not my experience that querying everything and then pruning the result is more efficient when you're doing a targeted search of known accounts. Although, yes, it is also more efficient to select just the properties you need to return.
The below examples are based on a domain in the range of 20,000 account objects.
measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st }
...
Seconds : 16
Milliseconds : 208
measure-command {$userlist | get-aduser -Properties DisplayName,st}
...
Seconds : 3
Milliseconds : 496
In the second example, $userlist contains 368 account names (just strings, not pre-fetched account objects).
Note that if I include the where
clause per your suggestion to prune to the actually desired results, it's even more expensive.
measure-command {Get-ADUser -Filter '*' -Properties DisplayName,st |where {$userlist -Contains $_.samaccountname } }
...
Seconds : 17
Milliseconds : 876
Indexed attributes seem to have similar performance (I tried just returning displayName
).
Even if I return all user account properties in my set, it's more efficient. (Adding a select statement to the below brings it down by a half-second).
measure-command {$userlist | get-aduser -Properties *}
...
Seconds : 12
Milliseconds : 75
I can't find a good document that was written in ye olde days about AD queries to link to, but you're hitting every account in your search scope to return the properties. This discusses the basics of doing effective AD queries - scoping and filtering: https://msdn.microsoft.com/en-us/library/ms808539.aspx#efficientadapps_topic01
When your search scope is "*", you're still building a (big) list of the objects and iterating through each one. An LDAP search filter is always more efficient to build the list first (or a narrow search base, which is again building a smaller list to query).
Just use memcpy.
If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.
strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
try this
input[type='text']
{
background:red !important;
}
Use this code it will work OK. You shall click on TextBox1 and then go to event and select Keyup and double click on it. You wil then get the lines for the SUB.
Private Sub TextBox1_KeyUp(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyUp
If e.KeyCode = Keys.Enter Then
MsgBox("Fel lösenord")
End If
End Sub
CREATE ROLE blog WITH
LOGIN
SUPERUSER
INHERIT
CREATEDB
CREATEROLE
REPLICATION;
COMMENT ON ROLE blog IS 'Test';
You need to use the scrollTop
property.
document.getElementById('box').scrollTop
I am using Mac and the issue is solved by deleting github record from keychain access app: Here is what i did:
Above steps are copied from @spyar for the ease.
You can try to use the following methods, if you're using HoneyComb Sdk(API Level 11).
view.setX(float x);
Parameter x is the visual x position of this view.
view.setY(float y);
Parameter y is the visual y position of this view.
I hope it will be helpful to you. :)
If its SQL Server you can do it on the column properties within design view
Try this?:
ALTER TABLE dbo.TableName
ADD CONSTRAINT DF_TableName_ColumnName
DEFAULT '01/01/2000' FOR ColumnName
Many answers here are rather old,
thanks to the pointer from @Simplans (https://stackoverflow.com/a/37759871/417747) and the home page...
What worked for me (Ubuntu bionic):
sudo apt-get install python3-lxml
(+ sudo apt-get install libxml2-dev libxslt1-dev
I installed before it, but not sure if that's the requirement still)
the tutorial of how to build NodeJS for Android https://github.com/dna2github/dna2oslab/tree/master/android/build
there are several versions v0.12, v4, v6, v7
It is easy to run compiled binary on Android; for example run compiled Nginx: https://github.com/dna2github/dna2mtgol/tree/master/fileShare
You just need to modify code to replace Nginx to NodeJS; it is better if using Android Service to run node js server on the backend.
In Notepad++ :
<option value value='1' >A
<option value value='2' >B
<option value value='3' >C
<option value value='4' >D
Find what: (.*)(>)(.)
Replace with: \3
Replace All
A
B
C
D
You can loop through all of the checkboxes by writing $(':checkbox').each(...)
.
If I understand your question correctly, you're looking for the following code:
var str = "";
$(':checkbox').each(function() {
str += this.checked ? "1," : "0,";
});
str = str.substr(0, str.length - 1); //Remove the trailing comma
This code will loop through all of the checkboxes and add either 1,
or 0,
to a string.
Without storing a new procedure you can use a code block and execute to obtain a table of occurences. You can filter results by schema, table or column name.
DO $$
DECLARE
value int := 0;
sql text := 'The constructed select statement';
rec1 record;
rec2 record;
BEGIN
DROP TABLE IF EXISTS _x;
CREATE TEMPORARY TABLE _x (
schema_name text,
table_name text,
column_name text,
found text
);
FOR rec1 IN
SELECT table_schema, table_name, column_name
FROM information_schema.columns
WHERE table_name <> '_x'
AND UPPER(column_name) LIKE UPPER('%%')
AND table_schema <> 'pg_catalog'
AND table_schema <> 'information_schema'
AND data_type IN ('character varying', 'text', 'character', 'char', 'varchar')
LOOP
sql := concat('SELECT ', rec1."column_name", ' AS "found" FROM ',rec1."table_schema" , '.',rec1."table_name" , ' WHERE UPPER(',rec1."column_name" , ') LIKE UPPER(''','%my_substring_to_find_goes_here%' , ''')');
RAISE NOTICE '%', sql;
BEGIN
FOR rec2 IN EXECUTE sql LOOP
RAISE NOTICE '%', sql;
INSERT INTO _x VALUES (rec1."table_schema", rec1."table_name", rec1."column_name", rec2."found");
END LOOP;
EXCEPTION WHEN OTHERS THEN
END;
END LOOP;
END; $$;
SELECT * FROM _x;
The following is not exactly the same but similar, I was searching for a snippet to add a call to the interface method, but found this question, so I decided to add this snippet for those who were searching for it like me and found this question:
public class MyClass
{
//... class code goes here
public interface DataLoadFinishedListener {
public void onDataLoadFinishedListener(int data_type);
}
private DataLoadFinishedListener m_lDataLoadFinished;
public void setDataLoadFinishedListener(DataLoadFinishedListener dlf){
this.m_lDataLoadFinished = dlf;
}
private void someOtherMethodOfMyClass()
{
m_lDataLoadFinished.onDataLoadFinishedListener(1);
}
}
Usage is as follows:
myClassObj.setDataLoadFinishedListener(new MyClass.DataLoadFinishedListener() {
@Override
public void onDataLoadFinishedListener(int data_type) {
}
});
This will work:
OnLoad="document.myform.mytextfield.focus();"
The use of CultureInfo class worked for me, I hope help you.
string value = "1200.00";
CultureInfo culture = new CultureInfo("en-US");
decimal result = Convert.ToDecimal(value, culture);
To count the number of a specific filetype in a folder. The example is to count mp3 files on F: drive.
( Get-ChildItme F: -Filter *.mp3 - Recurse | measure ).Count
Tested in 6.2.3, but should work >4.
The problem is in the Eclipse Maven support, the related question is here.
Under Eclipse, the java.home
variable is set to the JRE that was used to start Eclipse, not the build JRE. The default system JRE from C:\Program Files
doesn't include the JDK so tools.jar
is not being found.
To fix the issue you need to start Eclipse using the JRE from the JDK by adding something like this to eclipse.ini
(before -vmargs
!):
-vm
C:/<your_path_to_jdk170>/jre/bin/server/jvm.dll
Then refresh the Maven dependencies (Alt-F5) (Just refreshing the project isn't sufficient).
Works for primitives and immutable classes like String
, Wrapper classes Character, Byte.
int i=0,j=2
String s1,s2
s1 = s2 = "java rocks"
For mutable classes
Reference r1 = Reference r2 = Reference r3 = new Object();`
Three references + one object are created. All references point to the same object and your program will misbehave.
Quick and clean solution (linux tested) (After fatidic February 27, 2014)
Uninstall npm
npm rm npm -g
Install npm (new URL is www.npmjs.org instead npmjs.org)
curl https://www.npmjs.org/install.sh | sh
Tip: how to install node.js in linux https://stackoverflow.com/a/22099363/333061
Set up a button click listener and call the debugger;
Example
$("#myBtn").click(function() {
debugger;
});
Demo
Resources on debugging in JavaScript
Hey, we just did a global find-replace, changing Required=" to jRequired=". Then you just change it in the jquery code as well (jquery_helper.js -> Function ValidateControls). Now our validation continues as before and Chrome leaves us alone! :)
The T
doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.
The Z
stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).
Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime()
method. You could have used Q
or M
or Monty Python
and the method would have returned them unchanged as well; the method only looks for patterns starting with %
to replace those with information from the datetime
object.
this is how you do it with ActionLIstener
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class MyWind extends JFrame{
public MyWind() {
initialize();
}
private void initialize() {
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JTextField field = new JTextField();
field.setSize(200, 50);
field.setText(" ");
JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
comboBox.addItem("item1");
comboBox.addItem("item2");
//
// Create an ActionListener for the JComboBox component.
//
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//
// Get the source of the component, which is our combo
// box.
//
JComboBox comboBox = (JComboBox) event.getSource();
Object selected = comboBox.getSelectedItem();
if(selected.toString().equals("item1"))
field.setText("30");
else if(selected.toString().equals("item2"))
field.setText("40");
}
});
getContentPane().add(comboBox);
getContentPane().add(field);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyWind().setVisible(true);
}
});
}
}
You're declaring (some of) your event handlers incorrectly:
$('.menuOption').click(function( event ){ // <---- "event" parameter here
event.preventDefault();
var categories = $(this).attr('rel');
$('.pages').hide();
$(categories).fadeIn();
});
You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.
edit — to clarify: you have to provide some parameter name; using event
makes it clear what you intend, but you can call it e
or cupcake
or anything else.
Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.
In my case, for jboss 6.3
I had to change JAVA_OPTS
in file jboss-eap-6.3\bin\standalone.conf.bat
and set following values -Xmx8g -Xms8g -Xmn3080m
for jvm to take 8gb space.
To get the ASCII code of a character, you can use the ord()
function.
Here is an example code:
value = input("Your value here: ")
list=[ord(ch) for ch in value]
print(list)
Output:
Your value here: qwerty
[113, 119, 101, 114, 116, 121]
What I usually do is that I create a double image with both states, acting like kind of a two-frame film which I then use with as background for the original element so that the element has width / height set in pixels, resulting in showing only one half of the image. Then what the hover state defines is basically "move the film to show the other frame".
For example, imagine that the image has to be a gray Tux, that we need to change to colorful Tux on hover. And the "hosting" element is a span with id "tuxie".
The minimal code:
<style>
#tuxie {
width: 25px; height: 25px;
background: url('images/tuxie.png') no-repeat left top;
}
#tuxie:hover { background-position: -25px 0px }
</style>
<div id="tuxie" />
and the image:
Advantages are:
By putting both frames in one file, it's ensured that they are loaded at once. This avoids the ugly glitch on slower connections when the other frame never loads immediately, so first hover never works properly.
It may be easier to manage your images this way since "paired" frames are never confused.
With smart use of Javascript or CSS selector, one can extend this and include even more frames in one file.
In theory you could put even multiple buttons in single file and govern their display by coordinates, although such approach could get quickly out of hand.
Note that this is built with background
CSS property, so if you really need to use with <img />
s, you must not set the src
property since that overlaps the background. (Come to think that clever use of transparency here could lead to interesting results, but probably very dependent on quality of image as well as of the engine.).
In your broadcast receiver you could access a view via inflation a root layout from XML resource and then find all your views from this root layout with findViewByid():
View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);
Now you can access your views via 'view' and cast them to your view type:
myImage = (ImageView) view.findViewById(R.id.my_image);
As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below
git ls-files -z | xargs -0 rm
git checkout -- .
or one line
git ls-files -z | xargs -0 rm ; git checkout -- .
I use it all the time and haven't found any down sides yet!
For some further explanation, the -z
appends a null character onto the end of each entry output by ls-files
, and the -0
tells xargs
to delimit the output it was receiving by those null characters.
Remember that there is a difference between whether the query works and whether it works efficiently! A LINQ statement gets converted to T-SQL when the target of the statement is SQL Server, so you need to think about the T-SQL that would be produced.
Using String.Equals will most likely (I am guessing) bring back all of the rows from SQL Server and then do the comparison in .NET, because it is a .NET expression that cannot be translated into T-SQL.
In other words using an expression will increase your data access and remove your ability to make use of indexes. It will work on small tables and you won't notice the difference. On a large table it could perform very badly.
That's one of the problems that exists with LINQ; people no longer think about how the statements they write will be fulfilled.
In this case there isn't a way to do what you want without using an expression - not even in T-SQL. Therefore you may not be able to do this more efficiently. Even the T-SQL answer given above (using variables with collation) will most likely result in indexes being ignored, but if it is a big table then it is worth running the statement and looking at the execution plan to see if an index was used.
Consider process like a unit of ownership or what resources are needed by a task. A Process can have resources like memory space, specific input/output, specific files, and priority etc.
A thread is a dispatchable unit of execution or in simple words the progress through a sequence of instructions
It seems that you have forgotten to add your state server address in the config file.
<sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />
#Single line
'''
multi-line
comment
'''
"""
also,
multi-line comment
"""
Have you tried QCoreApplication::applicationDirPath()
qDebug() << "App path : " << qApp->applicationDirPath();
DailyJS has a good tutorial (long series of 24 posts) that walks you through all the aspects of building a notepad app (including all the possible extras).
Heres an overview of the tutorial: http://dailyjs.com/2010/11/01/node-tutorial/
And heres a link to all the posts: http://dailyjs.com/tags.html#nodepad
To convert a string back into a double, try the following
String s = "10.1";
Double d = Double.parseDouble(s);
The parseDouble method will achieve the desired effect, and so will the Double.valueOf() method.
I've done pablo solution and I always had the error (MVC4)
The view 'Error' or its master was not found or no view engine supports the searched location.
To get rid of this, remove the line
filters.Add(new HandleErrorAttribute());
in FilterConfig.cs
If you use addInterceptor method for add HttpLoggingInterceptor, it won't be logging the things that added by other interceptors applied later than HttpLoggingInterceptor.
For example: If you have two interceptors "HttpLoggingInterceptor" and "AuthInterceptor", and HttpLoggingInterceptor applied first, then you can't view the http-params or headers which set by AuthInterceptor.
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addNetworkInterceptor(logging)
.addInterceptor(new AuthInterceptor());
I solved it, via using addNetworkInterceptor method.
Inside controller inject Request object. So if you want to access request body inside controller method 'foo' do the following:
public function foo(Request $request){
$bodyContent = $request->getContent();
}
$('#loginBtn').click(function(e) {
e.preventDefault(); /// it should not have this code or else it wont continue
//....
});
ES6 introduces computed property names, which allows you to do
let a = 'key'
let myObj = {[a]: 10};
// output will be {key:10}
Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.
First the actual accounts:
LocalService account (preferred)
A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.
NT AUTHORITY\LocalService
HKEY_USERS\S-1-5-19
)
Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).
NT AUTHORITY\NetworkService
MANGO$
) to remote serversHKEY_USERS\S-1-5-20
)NETWORK SERVICE
into the Select User or Group dialog
LocalSystem account (dangerous, don't use!)
Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)
.\LocalSystem
(can also use LocalSystem
or ComputerName\LocalSystem
)HKCU
represents the default user)MANGO$
) to remote servers
Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService
can still access the internet.
The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).
It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.
In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).
In Windows Server 2003 you cannot run a scheduled task as
NT_AUTHORITY\LocalService
(aka the Local Service account), or NT AUTHORITY\NetworkService
(aka the Network Service account). That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.
A service running as NetworkService
presents the machine credentials on the network. This means that if your computer was called mango
, it would present as the machine account MANGO$
:
onclick event to call a function
<strike> <input type="button" value="NEXT" onclick="document.write('<?php //call a function here ex- 'fun();' ?>');" /> </strike>
it will surely help you
it take a little more time than normal but wait it will work
Excel typically saves a csv file as ANSI encoding instead of utf8.
One option to correct the file is to use Notepad or Notepad++:
git checkout foo/bar.txt
did you tried that? (without a HEAD keyword)
I usually revert my changes this way.
In MySQL if You don't want to change the collation and want to perform case sensitive search then just use binary keyword like this:
SELECT * FROM table_name WHERE binary username=@search_parameter and binary password=@search_parameter
The #
means that it matches the id
of an element. The .
signifies the class name:
<div id="myRedText">This will be red.</div>
<div class="blueText">this will be blue.</div>
#myRedText {
color: red;
}
.blueText {
color: blue;
}
Note that in a HTML document, the id attribute must be unique, so if you have more than one element needing a specific style, you should use a class name.
In CMake you could use find_package
to find libraries you need. There usually is a FindBoost.cmake
along with your CMake installation.
As far as I remember, it will be installed to /usr/share/cmake/Modules/
along with other find-scripts for common libraries. You could just check the documentation in that file for more information about how it works.
An example out of my head:
FIND_PACKAGE( Boost 1.40 COMPONENTS program_options REQUIRED )
INCLUDE_DIRECTORIES( ${Boost_INCLUDE_DIR} )
ADD_EXECUTABLE( anyExecutable myMain.cpp )
TARGET_LINK_LIBRARIES( anyExecutable LINK_PUBLIC ${Boost_LIBRARIES} )
I hope this code helps.
Here's a responsive way of doing it with jQuery.
$(window).resize(function () {
$('#YourRelativeDiv').css('margin-top', $('#YourFixedDiv').height());
});
The line that starts or ends the here-doc probably has some non-printable or whitespace characters (for example, carriage return) which means that the second "EOF" does not match the first, and doesn't end the here-doc like it should. This is a very common error, and difficult to detect with just a text editor. You can make non-printable characters visible for example with cat
:
cat -A myfile.sh
Once you see the output from cat -A
the solution will be obvious: remove the offending characters.