I had issues including toolbar in a RelativeLayout, try with LinearLayout. If you want to overlay the toolbar, try with:
<RelativeLayout>
<LinearLayout>
--INCLUDE tOOLBAR--
</LinearLayout>
<Button></Button>
</RelativeLayout>
I don't understand why but it works for me.
Multiple parameters can be given like below,
@RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
, @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
//logic
}
Scaling an image with CSS is not quite possible, but a similar effect can be achieved in the following manner, though.
Use this markup:
<div id="background">
<img src="img.jpg" class="stretch" alt="" />
</div>
with the following CSS:
#background {
width: 100%;
height: 100%;
position: absolute;
left: 0px;
top: 0px;
z-index: 0;
}
.stretch {
width:100%;
height:100%;
}
and you should be done!
In order to scale the image to be "full bleed" and maintain the aspect ratio, you can do this instead:
.stretch { min-width:100%; min-height:100%; width:auto; height:auto; }
It works out quite nicely! If one dimension is cropped, however, it will be cropped on only one side of the image, rather than being evenly cropped on both sides (and centered). I've tested it in Firefox, Webkit, and Internet Explorer 8.
HTTP/2 supports queries multiplexing, headers compression, priority and more intelligent packet streaming management. This results in reduced latency and accelerates content download on modern web pages.
I'm late to the game here, but this is how I am doing it, I spent a while hunting for a solution I was satisified with; this produces an UPDATE
statement ONLY for the fields that are changed, as you explicitly define what they are through a "white list" concept which is more secure to prevent web form injection anyway.
An excerpt from my ISession data repository:
public bool Update<T>(T item, params string[] changedPropertyNames) where T
: class, new()
{
_context.Set<T>().Attach(item);
foreach (var propertyName in changedPropertyNames)
{
// If we can't find the property, this line wil throw an exception,
//which is good as we want to know about it
_context.Entry(item).Property(propertyName).IsModified = true;
}
return true;
}
This could be wrapped in a try..catch if you so wished, but I personally like my caller to know about the exceptions in this scenario.
It would be called in something like this fashion (for me, this was via an ASP.NET Web API):
if (!session.Update(franchiseViewModel.Franchise, new[]
{
"Name",
"StartDate"
}))
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
hey guys i think what you are looking for is this one using select command. With this you can specify a RANGE GREATER THAN(>) OR LESSER THAN(<) IN MySQL WITH THIS:::::
select* from <**TABLE NAME**> where year(**COLUMN NAME**) > **DATE** OR YEAR(COLUMN NAME )< **DATE**;
FOR EXAMPLE:
select name, BIRTH from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+------------+
| name | BIRTH |
+----------+------------+
| bowser | 1979-09-11 |
| chirpy | 1998-09-11 |
| whistler | 1999-09-09 |
+----------+------------+
FOR SIMPLE RANGE LIKE USE ONLY GREATER THAN / LESSER THAN
mysql> select COLUMN NAME from <TABLE NAME> where year(COLUMN NAME)> 1996;
FOR EXAMPLE mysql>
select name from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+
| name |
+----------+
| bowser |
| chirpy |
| whistler |
+----------+
3 rows in set (0.00 sec)
You could try the FLOOR function like this:
SELECT FLOOR(columnName), moreColumns, etc
FROM myTable
WHERE ...
You could also try the FORMAT function, provided you know the decimal places can be omitted:
SELECT FORMAT(columnName,0), moreColumns, etc
FROM myTable
WHERE ...
You could combine the two functions
SELECT FORMAT(FLOOR(columnName),0), moreColumns, etc
FROM myTable
WHERE ...
Find root build.gradle
file and add google maven repo inside allprojects
tag
repositories {
mavenLocal()
mavenCentral()
maven { // <-- Add this
url 'https://maven.google.com/'
name 'Google'
}
}
It's better to use specific version instead of variable version
compile 'com.android.support:appcompat-v7:27.0.0'
If you're using Android Plugin for Gradle 3.0.0 or latter version
repositories {
mavenLocal()
mavenCentral()
google() //---> Add this
}
and inject dependency in this way :
implementation 'com.android.support:appcompat-v7:27.0.0'
pathlib
module (python's object-oriented filesystem paths)Just for kicks, this is perhaps the latest pythonic version of the solution.
from pathlib import Path
path = Path(f'{player}.txt')
path.touch() # default exists_ok=True
with path.open('a') as highscore:
highscore.write(f'Username:{player}')
@dfa answer is great, so I took it a step farther to make it possible to test blocks of ouput.
First I created TestHelper
with a method captureOutput
that accepts the annoymous class CaptureTest
. The captureOutput method does the work of setting and tearing down the output streams. When the implementation of CaptureOutput
's test
method is called, it has access to the output generate for the test block.
Source for TestHelper:
public class TestHelper {
public static void captureOutput( CaptureTest test ) throws Exception {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
ByteArrayOutputStream errContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
test.test( outContent, errContent );
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.out)));
}
}
abstract class CaptureTest {
public abstract void test( ByteArrayOutputStream outContent, ByteArrayOutputStream errContent ) throws Exception;
}
Note that TestHelper and CaptureTest are defined in the same file.
Then in your test, you can import the static captureOutput. Here is an example using JUnit:
// imports for junit
import static package.to.TestHelper.*;
public class SimpleTest {
@Test
public void testOutput() throws Exception {
captureOutput( new CaptureTest() {
@Override
public void test(ByteArrayOutputStream outContent, ByteArrayOutputStream errContent) throws Exception {
// code that writes to System.out
assertEquals( "the expected output\n", outContent.toString() );
}
});
}
I've found that this error is also generated if the document is empty. In this case it's also because there is no root element - but the error message "Extra content and the end of the document" is misleading in this situation.
Combine both. The Date-Time-Picker does support picking time, too.
You just have to change the Format-Property and maybe the CustomFormat-Property.
The reason your code fails is because post()
will start an asynchronous request to the server. What that means for you is that post()
returns immediately, not after the request completes, like you are expecting.
What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,
var it_works = false;
$.ajax({
url: 'some_file.php',
async: false, # makes request synchronous
success: function() {
it_works = true;
}
});
alert(it_works);
Annotation that binds a method parameter or method return value to a named model attribute, exposed to a web view.
public String add(@ModelAttribute("specified") Model model) {
...
}
Something like:
items = [
['Anne', 'a'],
['Bob', 'b'],
['Henry', 'b'],
['Andrew', 'd'],
['Jason', 'c'],
['Thomas', 'b']
]
sorting = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
result = []
sorting.forEach(function(key) {
var found = false;
items = items.filter(function(item) {
if(!found && item[1] == key) {
result.push(item);
found = true;
return false;
} else
return true;
})
})
result.forEach(function(item) {
document.writeln(item[0]) /// Bob Jason Henry Thomas Andrew
})
Here's a shorter code, but it destroys the sorting
array:
result = items.map(function(item) {
var n = sorting.indexOf(item[1]);
sorting[n] = '';
return [n, item]
}).sort().map(function(j) { return j[1] })
The best way is to use the ng-options
directive on the select
element.
Controller
function Ctrl($scope) {
// sort options
$scope.products = [{
value: 'prod_1',
label: 'Product 1'
}, {
value: 'prod_2',
label: 'Product 2'
}];
}
HTML
<select ng-model="selected_product"
ng-options="product as product.label for product in products">
</select>
This will bind the selected product
object to the ng-model
property - selected_product
. After that you can use this:
<p>Ordered by: {{selected_product.label}}</p>
jsFiddle: http://jsfiddle.net/bmleite/2qfSB/
benefit.indexOf(map4)
It either returns an index or -1 if the items is not found.
I strongly recommend wrapping the map in some object and use generics if possible.
In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...
If the command sha256sum is not available (on Mac OS X v10.9 (Mavericks) for example), you can use:
echo -n "foobar" | shasum -a 256
Something that works for me. Enjoy.
Excel.Application excelApplication = new Excel.Application() // start excel and turn off msg boxes
{
DisplayAlerts = false,
Visible = false
};
Excel.Workbook workBook = excelApplication.Workbooks.Open(targetFile);
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Worksheets[1];
var rDT = workSheet.Range(workSheet.Cells[monthYearNameRow, monthYearNameCol], workSheet.Cells[monthYearNameRow, maxTableColumnIndex]);
rDT.Merge();
rDT.Value = monthName + " " + year;
var reportDateRowStyle = workBook.Styles.Add("ReportDateRowStyle");
reportDateRowStyle.HorizontalAlignment = XlHAlign.xlHAlignCenter;
reportDateRowStyle.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
reportDateRowStyle.Font.Bold = true;
reportDateRowStyle.Font.Size = 14;
rDT.Style = reportDateRowStyle;
If you still have problems with Eclipse finding your files, you might try the following:
Verify the default working directory by printing the following in your main:
System.out.println("Working dir: " + System.getProperty("user.dir"));
For (1) above, I put the following debugging code around the specific file I was trying to access:
File imageFile = new File(source);
System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
if (!imageFile.exists()) {
System.out.println("file " + imageFile + " does not exist");
}
image = ImageIO.read(imageFile);
For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).
Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.
If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html
If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.
You are dropping it, then creating it, then trying to create it again by using SELECT INTO
. Change to:
DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))
INSERT INTO #TMPGUARDIAN
SELECT LAST_NAME,FRST_NAME
FROM TBL_PEOPLE
In MS SQL Server you can create a table without a CREATE TABLE
statement by using SELECT INTO
SQL> SELECT TO_CHAR(date '1982-03-09', 'DAY') day FROM dual;
DAY
---------
TUESDAY
SQL> SELECT TO_CHAR(date '1982-03-09', 'DY') day FROM dual;
DAY
---
TUE
SQL> SELECT TO_CHAR(date '1982-03-09', 'Dy') day FROM dual;
DAY
---
Tue
(Note that the queries use ANSI date literals, which follow the ISO-8601 date standard and avoid date format ambiguity.)
Working with Intellij, because I don't know how to set keyboard shortcut to mvn spring-boot:run -Dspring.profiles.active=dev
, I have to do this:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<jvmArguments>
-Dspring.profiles.active=dev
</jvmArguments>
</configuration>
</plugin>
As an alternative to @Mark Byers' approach, you can use while True
:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Go with this
body {
padding:0px;
margin:0px;
}
Android locked down GET_ACCOUNTS
recently so some of the answers did not work for me. I got this working on Android 7.0 with the caveat that your users have to endure a permission dialog.
AndroidManifest.xml
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
MainActivity.java
package com.example.patrick.app2;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.accounts.AccountManager;
import android.accounts.Account;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.*;
public class MainActivity extends AppCompatActivity {
final static int requestcode = 4; //arbitrary constant less than 2^16
private static String getEmailId(Context context) {
AccountManager accountManager = AccountManager.get(context);
Account[] accounts = accountManager.getAccountsByType("com.google");
Account account;
if (accounts.length > 0) {
account = accounts[0];
} else {
return "length is zero";
}
return account.name;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case requestcode:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
String emailAddr = getEmailId(getApplicationContext());
ShowMessage(emailAddr);
} else {
ShowMessage("Permission Denied");
}
}
}
public void ShowMessage(String email)
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage(email);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = getApplicationContext();
if ( ContextCompat.checkSelfPermission( context, android.Manifest.permission.GET_ACCOUNTS )
!= PackageManager.PERMISSION_GRANTED )
{
ActivityCompat.requestPermissions( this, new String[]
{ android.Manifest.permission.GET_ACCOUNTS },requestcode );
}
else
{
String possibleEmail = getEmailId(getApplicationContext());
ShowMessage(possibleEmail);
}
}
}
__VA_ARGS__
is the standard way to do it. Don't use compiler-specific hacks if you don't have to.
I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.
If you need not equal object condition use cross join sequences:
var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]
<textarea rows="4" cols="50"></textarea>
It is equivalent to:
textarea {
height: 4em;
width: 50em;
}
where 1em is equivalent to the current font size, thus make the text area 50 chars wide. see here.
<script type="text/javascript">
$(document).ready(function(){
$('.laravel').click(function(){
var val = $(this).is(":checked");
$('#category').submit();
});
});
<form action="{{route('directory')}}" method="post" id="category">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input name="category" value="{{$name->id}}" class="laravel" type="checkbox">{{$name->name}}
</form>
Here's an answer in Kotlin and androidX
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager
class DeactivatedViewPager @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : ViewPager(context, attrs) {
var isPagingEnabled = true
override fun onTouchEvent(ev: MotionEvent?): Boolean {
return isPagingEnabled && super.onTouchEvent(ev)
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
return isPagingEnabled && super.onInterceptTouchEvent(ev)
}
}
I would set up a Subversion repository. By doing it this way, individual developers can choose whether to use Subversion clients or Git clients (with git-svn
). Using git-svn
doesn't give you all the benefits of a full Git solution, but it does give individual developers a great deal of control over their own workflow.
I believe it will be a relatively short time before Git works just as well on Windows as it does on Unix and Mac OS X (since you asked).
Subversion has excellent tools for Windows, such as TortoiseSVN for Explorer integration and AnkhSVN for Visual Studio integration.
Move the cursor to the method name. Right click and select References > Project or References > Workspace from the pop-up menu.
Assuming you have GNU find:
find . -size +10000k -printf '%s %f\n'
If you want a constant width for the size field, you can do something like:
find . -size +10000k -printf '%10s %f\n'
Note that -size +1000k
selects files of at least 10,240,000 bytes (k
is 1024, not 1000). You said in a comment that you want files bigger than 1M; if that's 1024*1024 bytes, then this:
find . -size +1M ...
will do the trick -- except that it will also print the size and name of files that are exactly 1024*1024 bytes. If that matters, you could use:
find . -size +1048575c ...
You need to decide just what criterion you want.
You do not need {{}}
in when conditions. What you are searching for is:
- fail: msg="unsupported version"
when: version not in acceptable_versions
If the values came from another table, you might want to use
UPDATE table1 t1
SET (col1, col2) = (
SELECT col3, col4
FROM table2 t2
WHERE t1.col8=t2.col9
)
Example:
UPDATE table1
SET (col1, col2, col3) =(
(SELECT MIN (ship_charge), MAX (ship_charge) FROM orders),
'07/01/2007'
)
WHERE col4 = 1001;
If I want something like sed, then I usually just call sed
itself using the sh library.
from sh import sed
sed(['-i', 's/^# deb/deb/', '/etc/apt/sources.list'])
Sure, there are downsides. Like maybe the locally installed version of sed
isn't the same as the one you tested with. In my cases, this kind of thing can be easily handled at another layer (like by examining the target environment beforehand, or deploying in a docker image with a known version of sed).
Since you're using JPA, use the Lob
annotation (and optionally the Column
annotation). Here is what the JPA specification says about it:
9.1.19 Lob Annotation
A
Lob
annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use theLob
annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with theBasic
annotation. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property, and except for string and character-based types defaults to Blob.
So declare something like this:
@Lob
@Column(name="CONTENT", length=512)
private String content;
I have inherited a desktop app that makes calls to a series of Web Services on IIS. The web services (also) have to be able to run timed processes, independently (without having the client on). Hence they all have timers. The web service timers were shutting down (memory leak?) so we set the Idle time out to 0 and timers stay on.
-webkit-padding-start: 0;
will remove padding added by webkit engine
You're referencing a DOM element when doing something like $('#lastName')
. That's an element with id
attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject
is in the same scope as the variable declarations) -
var formObject = {
formObject: [
{
firstName:firstName, // no need to quote variable names
lastName:lastName
},
{
phoneNumber:phoneNumber,
address:address
}
]
};
This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.
An interesting way to see null in java in my opinion is to see it as something that DOES NOT denote an absence of information but simply as a literal value that can be assigned to a reference of any type. If you think about it if it denoted absence of information then for a1==a2 to be true doesn't make sense (in case they were both assigned a value of null) as they could really could be pointing to ANY object (we simply don't know what objects they should be pointing to)... By the way null == null returns true in java. If java e.g. would be like SQL:1999 then null==null would return unknown (a boolean value in SQL:1999 can take three values : true,false and unknown but in practise unknown is implemented as null in real systems)... http://en.wikipedia.org/wiki/SQL
There is no difference between the %i
and %d
format specifiers for printf
. We can see this by going to the draft C99 standard section 7.19.6.1
The fprintf function which also covers printf
with respect to format specifiers and it says in paragraph 8:
The conversion specifiers and their meanings are:
and includes the following bullet:
d,i The int argument is converted to signed decimal in the style [-]dddd. The precision specifies the minimum number of digits to appear; if the value being converted can be represented in fewer digits, it is expanded with leading zeros. The default precision is 1. The result of converting a zero value with a precision of zero is no characters.
On the other hand for scanf
there is a difference, %d
assume base 10 while %i
auto detects the base. We can see this by going to section 7.19.6.2
The fscanf function which covers scanf
with respect to format specifier, in paragraph 12 it says:
The conversion specifiers and their meanings are:
and includes the following:
d Matches an optionally signed decimal integer, whose format is the same as expected for the subject sequence of the strtol function with the value 10 for the base argument. The corresponding argument shall be a pointer to signed integer. i Matches an optionally signed integer, whose format is the same as expected for the subject sequence of the strtol function with the value 0 for the base argument. The corresponding argument shall be a pointer to signed integer.
The answer is: It depends.
Although base64-images are larger, there a few conditions where base64 is the better choice.
Size of base64-images
Base64 uses 64 different characters and this is 2^6. So base64 stores 6bit per 8bit character. So the proportion is 6/8 from unconverted data to base64 data. This is no exact calculation, but a rough estimate.
Example:
An 48kb image needs around 64kb as base64 converted image.
Calculation: (48 / 6) * 8 = 64
Simple CLI calculator on Linux systems:
$ cat /dev/urandom|head -c 48000|base64|wc -c
64843
Or using an image:
$ cat my.png|base64|wc -c
Base64-images and websites
This question is much more difficult to answer. Generally speaking, as larger the image as less sense using base64. But consider the following points:
Without jquery:
First of all, on your tab-able elements, add class="tabable"
this will let us select them later.
(Do not forget the "." class selector prefix in the code below)
var lastTabIndex = 10;
function OnFocusOut()
{
var currentElement = $get(currentElementId); // ID set by OnFOcusIn
var curIndex = currentElement.tabIndex; //get current elements tab index
if(curIndex == lastTabIndex) { //if we are on the last tabindex, go back to the beginning
curIndex = 0;
}
var tabbables = document.querySelectorAll(".tabable"); //get all tabable elements
for(var i=0; i<tabbables.length; i++) { //loop through each element
if(tabbables[i].tabIndex == (curIndex+1)) { //check the tabindex to see if it's the element we want
tabbables[i].focus(); //if it's the one we want, focus it and exit the loop
break;
}
}
}
$memberId =$_SESSION['TWILLO']['Id'];
$QueryServer=mysql_query("select * from smtp_server where memberId='".$memberId."'");
$data = array();
while($ser=mysql_fetch_assoc($QueryServer))
{
$data[$ser['Id']] =array('ServerName','ServerPort','Server_limit','email','password','status');
}
I have also faced the problem. In the php file, I have written following code where there was some space before php start tag
<?php
namespace App\Controller;
when I remove that space, it solved.
A clean way to do this using modern JavaScript is as follows:
const array = [
{ name: "something", value: "something" },
{ name: "somethingElse", value: "something else" },
];
const newObject = Object.assign({}, ...array.map(item => ({ [item.name]: item.value })));
// >> { something: "something", somethingElse: "something else" }
The explanation from Scott Meyers in Effective C++ might help understand when to use them:
Public inheritance should model "is-a relationship," whereas private inheritance should be used for "is-implemented-in-terms-of" - so you don't have to adhere to the interface of the superclass, you're just reusing the implementation.
Create you menu options the normal way see code below and add a global reference within the class to the menu
Menu mMenu; // global reference within the class
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tcktdetails, menu);
mMenu=menu; // assign the menu to the new menu item you just created
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_cancelticket) {
cancelTicket();
return true;
}
return super.onOptionsItemSelected(item);
}
Now you can toggle your menu by running this code with a button or within a function
if(mMenu != null) {
mMenu.findItem(R.id.action_cancelticket).setVisible(false);
}
let's say you write your script.rb
script. put:
#!/usr/bin/env ruby
as the first line and do a chmod +x script.rb
Please ensure that you have following import. Ofcourse other standard imports
import org.springframework.core.io.FileSystemResource
void uploadzipFiles(String token) {
RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)
def zipFile = new File("testdata.zip")
def Id = "001G00000"
MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
form.add("id", id)
form.add('file',new FileSystemResource(zipFile))
def urld ='''http://URL''';
def resp = rest.post(urld) {
header('X-Auth-Token', clientSecret)
contentType "multipart/form-data"
body(form)
}
println "resp::"+resp
println "resp::"+resp.text
println "resp::"+resp.headers
println "resp::"+resp.body
println "resp::"+resp.status
}
Using regexp: \S will match non whitespace character:anything but not a space, tab or new line. If your string has a single character which is not a space, tab or new line, then it's not empty. Therefore you just need to search for one character: \S
JavaScript:
function checkvalue() {
var mystring = document.getElementById('myString').value;
if(!mystring.match(/\S/)) {
alert ('Empty value is not allowed');
return false;
} else {
alert("correct input");
return true;
}
}
HTML:
<form onsubmit="return checkvalue(this)">
<input name="myString" type="text" value='' id="myString">
<input type="submit" value="check value" />
</form>
The way that Magento themes handle actual url's is as such (in view partials - phtml files):
echo $this->getSkinUrl('images/logo.png');
If you need the actual base path on disk to the image directory use:
echo Mage::getBaseDir('skin');
Some more base directory types are available in this great blog post:
You can make the .navbar
fixed width, then set it's left and right margin to auto
.
.navbar{
width: 80%;
margin: 0 auto;
}?
I finally got it:
ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));
Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:
"android_sdk"\platforms\"android_api_level"\data\res\drawable-hdpi\ic_menu_refresh.png
@media (max-width: @iphone-screen) {
background-attachment:inherit;
background-size:cover;
-webkit-background-size:cover;
}
I noticed something else about your coding.... look
INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')
in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be
'0',
you put
0,
lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)
UPDATE.....
I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol
For a Progressive Web App I wrote a script to easily load javascript files async on demand. Scripts are only loaded once. So you can call loadScript as often as you want for the same file. It wouldn't be loaded twice. This script requires JQuery to work.
For example:
loadScript("js/myscript.js").then(function(){
// Do whatever you want to do after script load
});
or when used in an async function:
await loadScript("js/myscript.js");
// Do whatever you want to do after script load
In your case you may execute this after document ready:
$(document).ready(async function() {
await loadScript("js/myscript.js");
// Do whatever you want to do after script is ready
});
Function for loadScript:
function loadScript(src) {
return new Promise(function (resolve, reject) {
if ($("script[src='" + src + "']").length === 0) {
var script = document.createElement('script');
script.onload = function () {
resolve();
};
script.onerror = function () {
reject();
};
script.src = src;
document.body.appendChild(script);
} else {
resolve();
}
});
}
Benefit of this way:
To resolve this problem, you just need to add the abs resource path to your project build file, just like below:
sourceSets {
main {
res.srcDirs = ['src/main/res','../../ActionBarSherlock/actionbarsherlock/res']
}
}
So, I again compile without any errors.
In addition other guys answer, its Easy to get property value of any object by use Extension method like:
public static class Helper
{
public static object GetPropertyValue(this object T, string PropName)
{
return T.GetType().GetProperty(PropName) == null ? null : T.GetType().GetProperty(PropName).GetValue(T, null);
}
}
Usage is:
Car foo = new Car();
var balbal = foo.GetPropertyValue("Make");
Use git add -A
, this will include the deleted files.
Note: use git rm
for certain files.
I used jsPDF and html-to-image.
You can check out the code on the below git repo.
If you like, you can drop a star there??
While it is not free (but $39), FireDaemon has worked so well for me I have to recommend it. It will run your batch file but has loads of additional and very useful functionality such as scheduling, service up monitoring, GUI or XML based install of services, dependencies, environmental variables and log management.
I started out using FireDaemon to launch JBoss application servers (run.bat) but shortly after realized that the richness of the FireDaemon configuration abilities allowed me to ditch the batch file and recreate the intent of its commands in the FireDaemon service definition.
There's also a SUPER FireDaemon called Trinity which you might want to look at if you have a large number of Windows servers on which to manage this service (or technically, any service).
See the following methods:
~ : Changes the case of current character
guu : Change current line from upper to lower.
gUU : Change current LINE from lower to upper.
guw : Change to end of current WORD from upper to lower.
guaw : Change all of current WORD to lower.
gUw : Change to end of current WORD from lower to upper.
gUaw : Change all of current WORD to upper.
g~~ : Invert case to entire line
g~w : Invert case to current WORD
guG : Change to lowercase until the end of document.
I suppose C# and Java produce equal byte arrays. If you have non-ASCII characters, it's not enough to add an additional 0. My example contains a few special characters:
var str = "Hell ö € O ";
var bytes = [];
var charCode;
for (var i = 0; i < str.length; ++i)
{
charCode = str.charCodeAt(i);
bytes.push((charCode & 0xFF00) >> 8);
bytes.push(charCode & 0xFF);
}
alert(bytes.join(' '));
// 0 72 0 101 0 108 0 108 0 32 0 246 0 32 32 172 0 32 3 169 0 32 216 52 221 30
I don't know if C# places BOM (Byte Order Marks), but if using UTF-16, Java String.getBytes
adds following bytes: 254 255.
String s = "Hell ö € O ";
// now add a character outside the BMP (Basic Multilingual Plane)
// we take the violin-symbol (U+1D11E) MUSICAL SYMBOL G CLEF
s += new String(Character.toChars(0x1D11E));
// surrogate codepoints are: d834, dd1e, so one could also write "\ud834\udd1e"
byte[] bytes = s.getBytes("UTF-16");
for (byte aByte : bytes) {
System.out.print((0xFF & aByte) + " ");
}
// 254 255 0 72 0 101 0 108 0 108 0 32 0 246 0 32 32 172 0 32 3 169 0 32 216 52 221 30
Edit:
Added a special character (U+1D11E) MUSICAL SYMBOL G CLEF (outside BPM, so taking not only 2 bytes in UTF-16, but 4.
Current JavaScript versions use "UCS-2" internally, so this symbol takes the space of 2 normal characters.
I'm not sure but when using charCodeAt
it seems we get exactly the surrogate codepoints also used in UTF-16, so non-BPM characters are handled correctly.
This problem is absolutely non-trivial. It might depend on the used JavaScript versions and engines. So if you want reliable solutions, you should have a look at:
A quick suggestion is Arrow
pip install arrow
>>> import arrow
>>> arrow.now().date()
datetime.date(2019, 6, 28)
>>> arrow.now().shift(months=6).date()
datetime.date(2019, 12, 28)
The closest you can do (except for your base-interface approach) is "where T : class
", meaning reference-type. There is no syntax to mean "any interface".
This ("where T : class
") is used, for example, in WCF to limit clients to service contracts (interfaces).
The problem comes because of an interesting clash of new C++ features and what you're trying to do. First, let's take a look at the push_back
signature:
void push_back(const T&)
It's expecting a reference to an object of type T
. Under the old system of initialization, such a member exists. For example, the following code compiles just fine:
#include <vector>
class Foo {
public:
static const int MEMBER;
};
const int Foo::MEMBER = 1;
int main(){
std::vector<int> v;
v.push_back( Foo::MEMBER ); // undefined reference to `Foo::MEMBER'
v.push_back( (int) Foo::MEMBER ); // OK
return 0;
}
This is because there is an actual object somewhere that has that value stored in it. If, however, you switch to the new method of specifying static const members, like you have above, Foo::MEMBER
is no longer an object. It is a constant, somewhat akin to:
#define MEMBER 1
But without the headaches of a preprocessor macro (and with type safety). That means that the vector, which is expecting a reference, can't get one.
I've tried all the above, but nothing seems to work as expected. After a little research I found that e.relatedTarget is the html just before the mouse exits the window.
So ... I've end up with this:
document.body.addEventListener('mouseout', function(e) {
if (e.relatedTarget === document.querySelector('html')) {
console.log('We\'re OUT !');
}
});
Please let me know if you find any issues or improvements !
2019 Update
(as user1084282 found out)
document.body.addEventListener('mouseout', function(e) {
if (!e.relatedTarget && !e.toElement) {
console.log('We\'re OUT !');
}
});
have a look at http://au.php.net/reserved.variables
I think the variable you are looking for is: $_SERVER["DOCUMENT_ROOT"]
You may also consider the following solution:
let sum = options.set0.concat(options.set1);
const codeHTML = '<ol>' + sum.reduce((html, item) => {
return html + "<li>" + item + "</li>";
}, "") + '</ol>';
document.querySelector("#list").innerHTML = codeHTML;
Dealing with markup in floats is a non trivial task. In the English/American notation you format one thousand plus 46*10-2
:
1,000.46
But in Germany you would change comma and point:
1.000,46
This makes it really hard guessing the right number in multi-language applications.
I strongly suggest using Zend_Measure
of the Zend Framework for this task. This component will parse the string to a float by the users language.
Find last time of update on a table
SELECT
tbl.name
,ius.last_user_update
,ius.user_updates
,ius.last_user_seek
,ius.last_user_scan
,ius.last_user_lookup
,ius.user_seeks
,ius.user_scans
,ius.user_lookups
FROM
sys.dm_db_index_usage_stats ius INNER JOIN
sys.tables tbl ON (tbl.OBJECT_ID = ius.OBJECT_ID)
WHERE ius.database_id = DB_ID()
http://www.sqlserver-dba.com/2012/10/sql-server-find-last-time-of-update-on-a-table.html
For the first one remove the spaces. Whitespace matters for the set command.
set guifont=Monaco:h20
For the second one it should be (the h specifies the height)
set guifont=Monospace:h20
My recommendation for setting the font is to do (if your version supports it)
set guifont=*
This will pop up a menu that allows you to select the font. After selecting the font, type
set guifont?
To show what the current guifont is set to. After that copy that line into your vimrc or gvimrc. If there are spaces in the font add a \
to escape the space.
set guifont=Monospace\ 20
Using boolean algebra, it is easy to show that:
A xor B = (not A and B) or (A and not B)
A B | f = notA and B | g = A and notB | f or g | A xor B
----+----------------+----------------+--------+--------
0 0 | 0 | 0 | 0 | 0
0 1 | 1 | 0 | 1 | 1
1 0 | 0 | 1 | 1 | 1
1 1 | 0 | 0 | 0 | 0
C99 defines bool, true
and false
in stdbool.h
.
I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .
It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .
... and a lot of other examples as well ...
Installing maven in Amazon Linux / redhat
--> sudo wget http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo -O /etc/yum.repos.d/epel-apache-maven.repo
--> sudo sed -i s/\$releasever/6/g /etc/yum.repos.d/epel-apache-maven.repo
-->sudo yum install -y apache-maven
--> mvn --version
Output looks like
Apache Maven 3.5.2 (138edd61fd100ec658bfa2d307c43b76940a5d7d; 2017-10-18T07:58:13Z) Maven home: /usr/share/apache-maven Java version: 1.8.0_171, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.amzn2.x86_64/jre Default locale: en_US, platform encoding: UTF-8 OS name: "linux", version: "4.14.47-64.38.amzn2.x86_64", arch: "amd64", family: "unix"
*If its thrown error related to java please follow the below step to update java 8 *
Installing java 8 in amazon linux/redhat
--> yum search java | grep openjdk
--> yum install java-1.8.0-openjdk-headless.x86_64
--> yum install java-1.8.0-openjdk-devel.x86_64
--> update-alternatives --config java #pick java 1.8
and press 1
--> update-alternatives --config javac #pick java 1.8
and press 2
Thank You
In my case it is because the server is giving http error occasionally. So basically once in a while my script gets the response like this rahter than the expected response:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<h1>502 Bad Gateway</h1>
<p>The proxy server received an invalid response from an upstream server.<hr/>Powered by Tengine</body>
</html>
Clearly this is not in json format and trying to call .json()
will yield JSONDecodeError: Expecting value: line 1 column 1 (char 0)
You can print the exact response that causes this error to better debug.
For example if you are using requests
and then simply print the .text
field (before you call .json()
) would do.
As an alternate option, if you have the Sqlite Database Browser and are more inclined to a GUI solution, you can edit the sqlite_sequence table where field name is the name of your table. Double click the cell for the field seq and change the value to 0 in the dialogue box that pops up.
If you want to bind an event like 'click' for all the elements having same class in the rendered DOM element then you can set up an event listener by using following parts of the code in components.ts file.
import { Component, OnInit, Renderer, ElementRef} from '@angular/core';
constructor( elementRef: ElementRef, renderer: Renderer) {
dragulaService.drop.subscribe((value) => {
this.onDrop(value.slice(1));
});
}
public onDrop(args) {
let [e, el] = args;
this.toggleClassComTitle(e,'checked');
}
public toggleClassComTitle(el: any, name: string) {
el.querySelectorAll('.com-item-title-anchor').forEach( function ( item ) {
item.addEventListener('click', function(event) {
console.log("item-clicked");
});
});
}
I don't know why all the answers over here are so confusing. I found a quite simpler one. Use a css class for the asp:menu, say, mainMenu and all the menu items under this will be "a tags" when rendered into HTML. So you just have to provide :hover property to those "a tags" in your CSS. See below for the example:
<asp:Menu ID="mnuMain" Orientation="Horizontal" runat="server" Font-Bold="True" Width="100%" CssClass="mainMenu">
<Items>
<asp:MenuItem Text="Home"></asp:MenuItem>
<asp:MenuItem Text="About Us"></asp:MenuItem>
</Items>
</asp:Menu>
And in the CSS, write:
.mainMenu { background:#900; }
.mainMenu a { color:#fff; }
.mainMenu a:hover { background:#c00; color:#ff9; }
I hope this helps. :)
The font sizes in your question are an example of what ratio each header should be in comparison to each other, rather than what size they should be themselves (in pixels).
So in response to your question "Is there a 'best practice' for these for mobile phones? - say iphone screen size?", yes there probably is - but you might find what someone says is "best practice" does not work for your layout.
However, to help get you on the right track, this article about building responsive layouts provides a good example of how to calculate the base font-size
in pixels in relation to device screen sizes.
The suggested font-sizes for screen resolutions suggested from that article are as follows:
@media (min-width: 858px) {
html {
font-size: 12px;
}
}
@media (min-width: 780px) {
html {
font-size: 11px;
}
}
@media (min-width: 702px) {
html {
font-size: 10px;
}
}
@media (min-width: 724px) {
html {
font-size: 9px;
}
}
@media (max-width: 623px) {
html {
font-size: 8px;
}
}
Here's a short and sweet JavaScript function to fetch the session ID:
function session_id() {
return /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
}
Or if you prefer a variable, here's a simple one-liner:
var session_id = /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
Should match the session ID cookie for PHP, JSP, .NET, and I suppose various other server-side processors as well.
public class B3PassingExcelDataBase {
@Test()
//Import the data::row start at 3 and column at 1:
public static void imortingData () throws IOException {
FileInputStream file=new FileInputStream("/Users/Downloads/Book2.xlsx");
XSSFWorkbook book=new XSSFWorkbook(file);
XSSFSheet sheet=book.getSheet("Sheet1");
int rowNum=sheet.getLastRowNum();
System.out.println(rowNum);
//get the row and value and assigned to variable to use in application
for (int r=3;r<rowNum;r++) {
// Rows stays same but column num changes and this is for only one person. It iterate for other.
XSSFRow currentRow=sheet.getRow(r);
String fName=currentRow.getCell(1).toString();
String lName=currentRow.getCell(2).toString();
String phone=currentRow.getCell(3).toString();
String email=currentRow.getCell(4).toString()
//passing the data
yogen.findElement(By.name("firstName")).sendKeys(fName); ;
yogen.findElement(By.name("lastName")).sendKeys(lName); ;
yogen.findElement(By.name("phone")).sendKeys(phone); ;
}
yogen.close();
}
}
Open index.php
in www
folder and set
$suppress_localhost = false;
This will prepend http://localhost/
to your project links
Just use an <a>
by itself, set it to display: block;
and set width
and height
. Get rid of the <span>
and <div>
. This is the semantic way to do it. There is no need to wrap things in <divs>
(or any element) for layout. That is what CSS is for.
Demo: http://jsfiddle.net/ThinkingStiff/89Enq/
HTML:
<a id="music" href="Music.html">Music I Like</a>
CSS:
#music {
background-color: black;
color: white;
display: block;
height: 40px;
line-height: 40px;
text-decoration: none;
width: 100px;
text-align: center;
}
Output:
In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().
When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that
Yes you can, with public static members on an outer public class, like so:
public class Foo {
public static class FooChild extends Z {
String foo;
}
public static class ZeeChild extends Z {
}
}
and another file that references the above:
public class Bar {
public static void main(String[] args){
Foo.FooChild f = new Foo.FooChild();
System.out.println(f);
}
}
put them in the same folder. Compile with:
javac folder/*.java
and run with:
java -cp folder Bar
There are a few things interacting here:
docker run your_image arg1 arg2
will replace the value of CMD
with arg1 arg2
. That's a full replacement of the CMD, not appending more values to it. This is why you often see docker run some_image /bin/bash
to run a bash shell in the container.
When you have both an ENTRYPOINT and a CMD value defined, docker starts the container by concatenating the two and running that concatenated command. So if you define your entrypoint to be file.sh
, you can now run the container with additional args that will be passed as args to file.sh
.
Entrypoints and Commands in docker have two syntaxes, a string syntax that will launch a shell, and a json syntax that will perform an exec. The shell is useful to handle things like IO redirection, chaining multiple commands together (with things like &&
), variable substitution, etc. However, that shell gets in the way with signal handling (if you've ever seen a 10 second delay to stop a container, this is often the cause) and with concatenating an entrypoint and command together. If you define your entrypoint as a string, it would run /bin/sh -c "file.sh"
, which alone is fine. But if you have a command defined as a string too, you'll see something like /bin/sh -c "file.sh" /bin/sh -c "arg1 arg2"
as the command being launched inside your container, not so good. See the table here for more on how these two options interact
The shell -c
option only takes a single argument. Everything after that would get passed as $1
, $2
, etc, to that single argument, but not into an embedded shell script unless you explicitly passed the args. I.e. /bin/sh -c "file.sh $1 $2" "arg1" "arg2"
would work, but /bin/sh -c "file.sh" "arg1" "arg2"
would not since file.sh
would be called with no args.
Putting that all together, the common design is:
FROM ubuntu:14.04
COPY ./file.sh /
RUN chmod 755 /file.sh
# Note the json syntax on this next line is strict, double quotes, and any syntax
# error will result in a shell being used to run the line.
ENTRYPOINT ["file.sh"]
And you then run that with:
docker run your_image arg1 arg2
There's a fair bit more detail on this at:
The following is acceptable as well:
@GetMapping(path = { "/{pathVariable1}/{pathVariable1}/somePath",
"/fixedPath/{some-name}/{some-id}/fixed" },
produces = "application/json")
Same can be applied to @RequestMapping
as well
No, they aren't the same algorithm. For starters, the LINQ OrderBy
is documented as stable (i.e. if two items have the same Name
, they'll appear in their original order).
It also depends on whether you buffer the query vs iterate it several times (LINQ-to-Objects, unless you buffer the result, will re-order per foreach
).
For the OrderBy
query, I would also be tempted to use:
OrderBy(n => n.Name, StringComparer.{yourchoice}IgnoreCase);
(for {yourchoice}
one of CurrentCulture
, Ordinal
or InvariantCulture
).
This method uses Array.Sort, which uses the QuickSort algorithm. This implementation performs an unstable sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
This method performs a stable sort; that is, if the keys of two elements are equal, the order of the elements is preserved. In contrast, an unstable sort does not preserve the order of elements that have the same key. sort; that is, if two elements are equal, their order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal.
I'm sure this will be an unpopular answer, but it works...
ProducerDTO[] p = new ProducerDTO[1];
producersProcedureActive
.stream()
.filter(producer -> producer.getPod().equals(pod))
.findFirst()
.ifPresent(producer -> {producersProcedureActive.remove(producer); p[0] = producer;}
p[0]
will either hold the found element or be null.
The "trick" here is circumventing the "effectively final" problem by using an array reference that is effectively final, but setting its first element.
This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)
/* AUTHOR: MIKEQ
* DATE: 04/29/2016
* DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-)
* Added example of error check on salary input.
* TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2)
*/
import java.util.Scanner;
public class userInputVersion1 {
public static void main(String[] args) {
System.out.println("** Taking in User input **");
Scanner input = new Scanner(System.in);
System.out.println("Please enter your name : ");
String s = input.nextLine(); // getting a String value (full line)
//String s = input.next(); // getting a String value (issues with spaces in line)
System.out.println("Please enter your age : ");
int i = input.nextInt(); // getting an integer
// version with Fault Tolerance:
System.out.println("Please enter your salary : ");
while (!input.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
input.next();
}
double d = input.nextDouble(); // need to check the data type?
System.out.printf("\nName %s" +
"\nAge: %d" +
"\nSalary: %f\n", s, i, d);
// close the scanner
System.out.println("Closing Scanner...");
input.close();
System.out.println("Scanner Closed.");
}
}
I too liked Jordan's answer and implemented it myself. I only needed to abbreviations so in case someone else needs the same:
public static IEnumerable<SelectListItem> GetStatesList()
{
IList<SelectListItem> states = new List<SelectListItem>
{
new SelectListItem() {Text="AL", Value="AL"},
new SelectListItem() { Text="AK", Value="AK"},
new SelectListItem() { Text="AZ", Value="AZ"},
new SelectListItem() { Text="AR", Value="AR"},
new SelectListItem() { Text="CA", Value="CA"},
new SelectListItem() { Text="CO", Value="CO"},
new SelectListItem() { Text="CT", Value="CT"},
new SelectListItem() { Text="DC", Value="DC"},
new SelectListItem() { Text="DE", Value="DE"},
new SelectListItem() { Text="FL", Value="FL"},
new SelectListItem() { Text="GA", Value="GA"},
new SelectListItem() { Text="HI", Value="HI"},
new SelectListItem() { Text="ID", Value="ID"},
new SelectListItem() { Text="IL", Value="IL"},
new SelectListItem() { Text="IN", Value="IN"},
new SelectListItem() { Text="IA", Value="IA"},
new SelectListItem() { Text="KS", Value="KS"},
new SelectListItem() { Text="KY", Value="KY"},
new SelectListItem() { Text="LA", Value="LA"},
new SelectListItem() { Text="ME", Value="ME"},
new SelectListItem() { Text="MD", Value="MD"},
new SelectListItem() { Text="MA", Value="MA"},
new SelectListItem() { Text="MI", Value="MI"},
new SelectListItem() { Text="MN", Value="MN"},
new SelectListItem() { Text="MS", Value="MS"},
new SelectListItem() { Text="MO", Value="MO"},
new SelectListItem() { Text="MT", Value="MT"},
new SelectListItem() { Text="NE", Value="NE"},
new SelectListItem() { Text="NV", Value="NV"},
new SelectListItem() { Text="NH", Value="NH"},
new SelectListItem() { Text="NJ", Value="NJ"},
new SelectListItem() { Text="NM", Value="NM"},
new SelectListItem() { Text="NY", Value="NY"},
new SelectListItem() { Text="NC", Value="NC"},
new SelectListItem() { Text="ND", Value="ND"},
new SelectListItem() { Text="OH", Value="OH"},
new SelectListItem() { Text="OK", Value="OK"},
new SelectListItem() { Text="OR", Value="OR"},
new SelectListItem() { Text="PA", Value="PA"},
new SelectListItem() { Text="PR", Value="PR"},
new SelectListItem() { Text="RI", Value="RI"},
new SelectListItem() { Text="SC", Value="SC"},
new SelectListItem() { Text="SD", Value="SD"},
new SelectListItem() { Text="TN", Value="TN"},
new SelectListItem() { Text="TX", Value="TX"},
new SelectListItem() { Text="UT", Value="UT"},
new SelectListItem() { Text="VT", Value="VT"},
new SelectListItem() { Text="VA", Value="VA"},
new SelectListItem() { Text="WA", Value="WA"},
new SelectListItem() { Text="WV", Value="WV"},
new SelectListItem() { Text="WI", Value="WI"},
new SelectListItem() { Text="WY", Value="WY"}
};
return states;
}
This is a quick solution in case you want to convert more columns of your pandas.DataFrame
from float to integer considering also the case that you can have NaN values.
cols = ['col_1', 'col_2', 'col_3', 'col_4']
for col in cols:
df[col] = df[col].apply(lambda x: int(x) if x == x else "")
I tried with else x)
and else None)
, but the result is still having the float number, so I used else ""
.
The second method would almost certainly be the fastest way to test whether a null-terminated string is empty, since it involves one read and one comparison. There's certainly nothing wrong with this approach in this case, so you may as well use it.
The third method doesn't check whether a character array is empty; it ensures that a character array is empty.
It really depends on where your JavaScript code is located.
The problem is probably caused by the DOM not being loaded when the line
var systemStatus = document.getElementById("system-status");
is executed. You could try calling this in an onload event, or ideally use a DOM ready type event from a JavaScript framework.
Use Reflection:
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine("Name: " + property.Name + ", Value: " + property.GetValue(obj, null));
}
for Excel - what tools/reference item must be added to gain access to BindingFlags, as there is no "System.Reflection" entry in the list
Edit: You can also specify a BindingFlags value to type.GetProperties()
:
BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
PropertyInfo[] properties = type.GetProperties(flags);
That will restrict the returned properties to public instance properties (excluding static properties, protected properties, etc).
You don't need to specify BindingFlags.GetProperty
, you use that when calling type.InvokeMember()
to get the value of a property.
Here's a little "coup de pouce"
Public Class DataGridViewRHEx
Inherits DataGridView
Protected Overrides Function CreateRowsInstance() As System.Windows.Forms.DataGridViewRowCollection
Dim dgvRowCollec As DataGridViewRowCollection = MyBase.CreateRowsInstance()
AddHandler dgvRowCollec.CollectionChanged, AddressOf dvgRCChanged
Return dgvRowCollec
End Function
Private Sub dvgRCChanged(sender As Object, e As System.ComponentModel.CollectionChangeEventArgs)
If e.Action = System.ComponentModel.CollectionChangeAction.Add Then
Dim dgvRow As DataGridViewRow = e.Element
dgvRow.DefaultHeaderCellType = GetType(DataGridViewRowHeaderCellEx)
End If
End Sub
End Class
Public Class DataGridViewRowHeaderCellEx
Inherits DataGridViewRowHeaderCell
Protected Overrides Sub Paint(graphics As System.Drawing.Graphics, clipBounds As System.Drawing.Rectangle, cellBounds As System.Drawing.Rectangle, rowIndex As Integer, dataGridViewElementState As System.Windows.Forms.DataGridViewElementStates, value As Object, formattedValue As Object, errorText As String, cellStyle As System.Windows.Forms.DataGridViewCellStyle, advancedBorderStyle As System.Windows.Forms.DataGridViewAdvancedBorderStyle, paintParts As System.Windows.Forms.DataGridViewPaintParts)
If Not Me.OwningRow.DataBoundItem Is Nothing Then
If TypeOf Me.OwningRow.DataBoundItem Is DataRowView Then
End If
End If
'HERE YOU CAN USE DATAGRIDROW TAG TO PAINT STRING
formattedValue = CStr(Me.DataGridView.Rows(rowIndex).Tag)
MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts)
End Sub
End Class
AFAIK there is no possibility beside from using keys or expect if you are using the command line version ssh
. But there are library bindings for the most programming languages like C, python, php, ... . You could write a program in such a language. This way it would be possible to pass the password automatically. But note this is of course a security problem as the password will be stored in plain text in that program
ANSI (aka Windows-1252/WinLatin1) is a character encoding of the Latin alphabet, fairly similar to ISO-8859-1. You may want to take a look of it at Wikipedia.
SELECT
Q.DateInQuarter,
D.[Year],
Quarter = D.Year + '-Q'
+ Convert(varchar(1), ((Q.DateInQuarter % 10000 - 100) / 300 + 1))
FROM
dbo.QuarterDates Q
CROSS APPLY (
VALUES (Convert(varchar(4), Q.DateInQuarter / 10000))
) D ([Year])
;
Included with git — Run git gui
from the command line, and the Windows msysgit installer adds it to the Start menu.
Git GUI can do a majority of what you'd need to do with git. Including stage changes, configure git and repositories, push changes, create/checkout/delete branches, merge, and many other things.
One of my favourite features is the "stage line" and "stage hunk" shortcuts in the right-click menu, which lets you commit specific parts of a file. You can achieve the same via git add -i
, but I find it easier to use.
It isn't the prettiest application, but it works on almost all platforms (being based upon Tcl/Tk)
Also included with git. It is a git history viewer, and lets you visualise a repository's history (including branches, when they are created, and merged). You can view and search commits.
Goes together nicely with git-gui.
Mac OS X application. Mainly an equivalent of git log
, but has some integration with github (like the "Network view").
Looks pretty, and fits with Mac OS X. You can search repositories. The biggest critisism of Gitnub is that it shows history in a linear fashion (a single branch at a time) - it doesn't visualise branching and merging, which can be important with git, although this is a planned improvement.
Download links, change log and screenshots | git repository
Intends to be a "gitk clone for OS X".
It can visualise non-linear branching history, perform commits, view and search commits, and it has some other nice features like being able to "Quicklook" any file in any revision (press space in the file-list view), export any file (via drag and drop).
It is far better integrated into OS X than git-gui
/gitk
, and is fast and stable even with exceptionally large repositories.
The original git repository pieter has not updated recently (over a year at time of writing). A more actively maintained branch is available at brotherbard/gitx - it adds "sidebar, fetch, pull, push, add remote, merge, cherry-pick, rebase, clone, clone to"
Download | Screenshots | git repository | brotherbard fork | laullon fork
From the homepage:
SmartGit is a front-end for the distributed version control system Git and runs on Windows, Mac OS X and Linux. SmartGit is intended for developers who prefer a graphical user interface over a command line client, to be even more productive with Git — the most powerful DVCS today.
You can download it from their website.
TortoiseSVN Git version for Windows users.
It is porting TortoiseSVN to TortoiseGit The latest release 1.2.1.0 This release can complete regular task, such commit, show log, diff two version, create branch and tag, Create patch and so on. See ReleaseNotes for detail. Welcome to contribute this project.
QGit is a git GUI viewer built on Qt/C++.
With qgit you will be able to browse revisions history, view patch content and changed files, graphically following different development branches.
gitg is a git repository viewer targeting gtk+/GNOME. One of its main objectives is to provide a more unified user experience for git frontends across multiple desktops. It does this not be writing a cross-platform application, but by close collaboration with similar clients for other operating systems (like GitX for OS X).
Gitbox is a Mac OS X graphical interface for Git version control system. In a single window you see branches, history and working directory status.
Everyday operations are easy: stage and unstage changes with a checkbox. Commit, pull, merge and push with a single click. Double-click a change to show a diff with FileMerge.app.
The Gity website doesn't have much information, but from the screenshots on there it appears to be a feature rich open source OS X git gui.
Meld is a visual diff and merge tool. You can compare two or three files and edit them in place (diffs update dynamically). You can compare two or three folders and launch file comparisons. You can browse and view a working copy from popular version control systems such such as CVS, Subversion, Bazaar-ng and Mercurial [and Git].
A Git GUIfor OSX by Steve Dekorte.
At a glance, see which remote branches have changes to pull and local repos have changes to push. The git ops of add, commit, push, pull, tag and reset are supported as well as visual diffs and visual browsing of project hieracy that highlights local changes and additions.
Free for 1 repository, $25 for more.
Focuses on making Git easy to use. Features a native Cocoa (mac-like) UI, fast repository browsing, cloning, push/pull, branching/merging, visual diff, remote branches, easy access to the Terminal, and more.
By making the most commonly used Git actions intuitive and easy to perform, Sprout (formerly GitMac) makes Git user-friendly. Compatible with most Git workflows, Sprout is great for designers and developers, team collaboration and advanced and novice users alike.
A feature-rich Git GUI for Mac OSX. 30-day free trial, $59USD for a single-user license.
EGit is an Eclipse Team provider for the Git version control system. Git is a distributed SCM, which means every developer has a full copy of all history of every revision of the code, making queries against the history very fast and versatile.
The EGit project is implementing Eclipse tooling on top of the JGit Java implementation of Git.
Open Source for Windows - installs everything you need to work with Git in a single package, easy to use.
Git Extensions is a toolkit to make working with Git on Windows more intuitive. The shell extension will intergrate in Windows Explorer and presents a context menu on files and directories. There is also a Visual Studio plugin to use git from Visual Studio.
Big thanks to dbr for elaborating on the git gui stuff.
SourceTree is a free Mac client for Git, Mercurial and SVN. Built by Atlassian, the folks behind BitBucket, it seems to work equally well with any VC system, which allows you to master a single tool for use with all of your projects, however they're version-controlled. Feature-packed, and FREE.
Expert-Ready & Feature-packed for both novice and advanced users:
Review outgoing and incoming changesets. Cherry-pick between branches. Patch handling, rebase, stash / shelve and much more.
You actually don't have access to filesystem (for example reading and writing local files), however, due to HTML5 File Api specification, there are some file properties that you do have access to, and the file size is one of them.
For the HTML below
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/
Old browsers support
Be aware that old browsers will return a null
value for the previous this.files
call, so accessing this.files[0]
will raise an exception and you should check for File API support before using it
Another option would be to use Angular's built-in pub-sub architecture in order to notify your directive to focus. Similar to the other approaches, but it's then not directly tied to a property, and is instead listening in on it's scope for a particular key.
Directive:
angular.module("app").directive("focusOn", function($timeout) {
return {
restrict: "A",
link: function(scope, element, attrs) {
scope.$on(attrs.focusOn, function(e) {
$timeout((function() {
element[0].focus();
}), 10);
});
}
};
});
HTML:
<input type="text" name="text_input" ng-model="ctrl.model" focus-on="focusTextInput" />
Controller:
//Assume this is within your controller
//And you've hit the point where you want to focus the input:
$scope.$broadcast("focusTextInput");
I agree with Justin, and the WhiteSpace CHAR can be referenced using ASCII codes here Character number 32 represents a white space, Therefore:
string.Empty.PadRight(totalLength, (char)32);
An alternative approach: Create all spaces manually within a custom method and call it:
private static string GetSpaces(int totalLength)
{
string result = string.Empty;
for (int i = 0; i < totalLength; i++)
{
result += " ";
}
return result;
}
And call it in your code to create white spaces: GetSpaces(14);
You can use
.floatybox {
display: inline-block;
width: 123px;
}
If you only need to support browsers that have support for inline blocks. Inline blocks can have width, but are inline, like button elements.
Oh, and you might wnat to add vertical-align: top on the elements to make sure things line up
Virtual base classes, used in virtual inheritance, is a way of preventing multiple "instances" of a given class appearing in an inheritance hierarchy when using multiple inheritance.
Consider the following scenario:
class A { public: void Foo() {} };
class B : public A {};
class C : public A {};
class D : public B, public C {};
The above class hierarchy results in the "dreaded diamond" which looks like this:
A
/ \
B C
\ /
D
An instance of D will be made up of B, which includes A, and C which also includes A. So you have two "instances" (for want of a better expression) of A.
When you have this scenario, you have the possibility of ambiguity. What happens when you do this:
D d;
d.Foo(); // is this B's Foo() or C's Foo() ??
Virtual inheritance is there to solve this problem. When you specify virtual when inheriting your classes, you're telling the compiler that you only want a single instance.
class A { public: void Foo() {} };
class B : public virtual A {};
class C : public virtual A {};
class D : public B, public C {};
This means that there is only one "instance" of A included in the hierarchy. Hence
D d;
d.Foo(); // no longer ambiguous
This is a mini summary. For more information, have a read of this and this. A good example is also available here.
change "localhost" to your real con ip addr
because it's to mysql_connect()
Although the accepted answer works fine, since v0.21.0rc1 it gives a warning
UserWarning: Pandas doesn't allow columns to be created via a new attribute name
Instead, one can do
df[["X", "A", "B", "C"]].plot(x="X", kind="bar")
If your table is quite big better not use the statement:
alter table goods add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;
because it makes a copy of all data in a temporary table, alter table and then copies it back. Better do it manually. Rename your table:
rename table goods to goods_old;
create new table with primary key and all necessary indexes:
create table goods (
id int(10) unsigned not null AUTO_INCREMENT
... other columns ...
primary key (id)
);
move all data from the old table into new, disabling keys and indexes to speed up copying:
-- USE THIS FOR MyISAM TABLES:
SET UNIQUE_CHECKS=0;
ALTER TABLE goods DISABLE KEYS;
INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old;
ALTER TABLE goods ENABLE KEYS;
SET UNIQUE_CHECKS=1;
-- USE THIS FOR InnoDB TABLES:
SET AUTOCOMMIT = 0; SET UNIQUE_CHECKS=0; SET FOREIGN_KEY_CHECKS=0;
INSERT INTO goods (... your column names ...) SELECT ... your column names FROM goods_old;
SET FOREIGN_KEY_CHECKS=1; SET UNIQUE_CHECKS=1; COMMIT; SET AUTOCOMMIT = 1;
It takes 2 000 seconds to add PK to a table with ~200 mln rows.
If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.
If you don't want word wrap, assign the CSS style white-space: nowrap
to the cells.
Speed Up Gradle Build In Android Studio 3.2.1
Ever feel like you are waiting for the builds to complete in Android Studio for minutes? Me too. And it’s a pretty annoying. Fortunately, there are a few ways that you can use to improve this. Android uses Gradle for building. The latest version is 4.6 has a huge performance boost over previous versions (see Release notes for details).
Step 1: Update Gradle version An easier way to accomplish this is to go to: Open Module Settings (your project) > Project Structure
UPDATE
Change to Gradle version: 4.6 and Change to Android Plugin Version: 3.2.1
Download Gradle Release distributive from https://services.gradle.org/distributions/gradle-4.6-all.zip And copy it to the Gradle folder:
Last step is to add your discribution in Settings > Gradle
Don’t forget to click Apply to save changes.
Step 2: Enable Offline mode, Gradle daemon and parallel build for the project Offline mode tells Gradle to ignore update-to-date checks. Gradle asks for dependencies everytime and having this option makes it just uses what is already on the machine for dependencies. Go to Gradle from android studio Setting and click in Offline work box.
The next step is to enable the Gradle daemon and parallel build for your project. Parallel builds will cause your projects with multiple modules (multi-project builds in Gradle) to be built in parallel, which should make large or modular projects build faster.
These settings could enabled by modifiing a file named gradle.properties in Gradle scripts directory(i.e., ~/.gradle/gradle.properties).Some of these options (e.g. Complie modules in parallel) are available from Android Studio and also enabled there by default, but putting them in the gradle.properties file will enabled them when building from the terminal and also making sure that your colleagues will use the same settings. But if you’re working on a team, sometimes you can’t commit this stuff.
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit org.gradle.parallel=true
# When set to true the Gradle daemon is used to run the build. For local developer builds this is our favorite property.
# The developer environment is optimized for speed and feedback so we nearly always run Gradle jobs with the daemon.
org.gradle.daemon=true
Using the daemon will make your builds startup faster as it won’t have to start up the entire Gradle application every time. The Gradle Daemon is not enabled by default, but it’s recommend always enabling it for developers’ machines (but leaving it disabled for continuous integration servers). FAQ about this mode could be found here https://docs.gradle.org/current/userguide/gradle_daemon.html. The parallel builds setting could be unsafe for some projects. The requirement is that all your modules must be decoupled or your build could fail (see http://gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects for details).
Step 3: Enable incremental dexign and tweak memory settings You can speed up your builds by turning on incremental dexing. In your module’s build file:
Add this option to your android block:
dexOptions {
incremental true
}
In that dexOptions block you can also specify the heap size for the dex process, for example:
dexOptions {
incremental true
javaMaxHeapSize "12g"
}
Where “12g” is 12GB of memory. Additional information about this could be found here google.github.io/android-gradle-dsl/current/ You can also configure Gradle parameters in the settings file, e.g. increase the max heap size in case you have a large project:
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
See all list of parameters here: https://docs.gradle.org/current/userguide/userguide_single.html#sec:gradle_configuration_properties for details.
Step 4: Disable Antivirus Consider to exclude project and cache files from antivirus scanning. This is obviously a trade off with security. But if you switch between branches a lot, then antivirus will rescan files before allowing gradle process to use it, which slows build time (in particular Android Studio sync project with gradle files and indexing tasks). Measure build time and process CPU with and without antivirus enabled to see if it is related. I hope this helps. Leave a comment if you have any question or some other tips for improving the build performance.
As dav_i says, in order to keep the file in repo and yet removing it from changes without creating an extra commit you can use:
git update-index --assume-unchanged filename
Usually you make the thing you don't want duplicates of unique, and allow the database itself to refuse the insert.
Otherwise, you can use INSERT INTO, see How to avoid duplicates in INSERT INTO SELECT query in SQL Server?
The documentation (https://angular.io/guide/template-syntax#!#star-template) gives the following example. Say we have template code like this:
<hero-detail *ngIf="currentHero" [hero]="currentHero"></hero-detail>
Before it will be rendered, it will be "de-sugared". That is, the asterix notation will be transcribed to the notation:
<template [ngIf]="currentHero">
<hero-detail [hero]="currentHero"></hero-detail>
</template>
If 'currentHero' is truthy this will be rendered as
<hero-detail> [...] </hero-detail>
But what if you want an conditional output like this:
<h1>Title</h1><br>
<p>text</p>
.. and you don't want the output be wrapped in a container.
You could write the de-sugared version directly like so:
<template [ngIf]="showContent">
<h1>Title</h1>
<p>text</p><br>
</template>
And this will work fine. However, now we need ngIf to have brackets [] instead of an asterix *, and this is confusing (https://github.com/angular/angular.io/issues/2303)
For that reason a different notation was created, like so:
<ng-container *ngIf="showContent"><br>
<h1>Title</h1><br>
<p>text</p><br>
</ng-container>
Both versions will produce the same results (only the h1 and p tag will be rendered). The second one is preferred because you can use *ngIf like always.
//use css
.blue {
background-color:blue !important;
}
.blue th {
color:white !important;
}
//html
<table class="table blue">.....</table>
Bringing this question up to date by providing this answer.
appdmg
is a simple, easy-to-use, open-source command line program that creates dmg-files from a simple json specification. Take a look at the readme at the official website:
https://github.com/LinusU/node-appdmg
Quick example:
Install appdmg
npm install -g appdmg
Write a json file (spec.json
)
{
"title": "Test Title",
"background": "background.png",
"icon-size": 80,
"contents": [
{ "x": 192, "y": 344, "type": "file", "path": "TestApp.app" },
{ "x": 448, "y": 344, "type": "link", "path": "/Applications" }
]
}
Run program
appdmg spec.json test.dmg
(disclaimer. I'm the creator of appdmg)
No -P needed; -E is sufficient:
grep -E '(^|\s)abc(\s|$)'
or even without -E:
grep '\(^\|\s\)abc\(\s\|$\)'
checkout Simple. its a pretty simple embeddable server with built in support for quite a variety of operations. I particularly love its threading model..
Amazing!
I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.
select CONVERT(bigint,'60') as seconds
and it returns
60
I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas
element. I was struggling for at least an hour and I did not get it to save the image correctly on my server.
Once I set the
contentType
option of my jQuery ajax call to application/x-www-form-urlencoded
everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.
Maybe that helps someone!
Synchronous solution :
void DisplayProcessStatus(Process process)
{
process.Refresh(); // Important
if(process.HasExited)
{
Console.WriteLine("Exited.");
}
else
{
Console.WriteLine("Running.");
}
}
Asynchronous solution:
void RegisterProcessExit(Process process)
{
// NOTE there will be a race condition with the caller here
// how to fix it is left as an exercise
process.Exited += process_Exited;
}
static void process_Exited(object sender, EventArgs e)
{
Console.WriteLine("Process has exited.");
}
call concat
and pass param axis=1
to concatenate column-wise:
In [5]:
pd.concat([df_a,df_b], axis=1)
Out[5]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
There is a useful guide to the various methods of merging, joining and concatenating online.
For example, as you have no clashing columns you can merge
and use the indices as they have the same number of rows:
In [6]:
df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
And for the same reasons as above a simple join
works too:
In [7]:
df_a.join(df_b)
Out[7]:
AAseq Biorep Techrep Treatment mz AAseq1 Biorep1 Techrep1 \
0 ELVISLIVES A 1 C 500.0 ELVISLIVES A 1
1 ELVISLIVES A 1 C 500.5 ELVISLIVES A 1
2 ELVISLIVES A 1 C 501.0 ELVISLIVES A 1
Treatment1 inte1
0 C 1100
1 C 1050
2 C 1010
Your key is a string and your value is an int. Your code won't work because it cannot look up the random int you pass. Also, please provide full code
layout.xml
<Button
android:id="@+id/buttonBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="finishActivity"
android:text="Back" />
Activity.java
public void finishActivity(View v){
finish();
}
Related:
With socket.emit you can register custom event like that:
server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
client:
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
Socket.send does the same, but you don't register to 'news' but to message:
server:
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.send('hi');
});
client:
var socket = io.connect('http://localhost');
socket.on('message', function (message) {
console.log(message);
});
You don't really need a sub-select:
SELECT a, COUNT(*) AS b,
SUM( CASE WHEN c = 'const' THEN 1 ELSE 0 END ) as d,
from t group by a order by b desc
You can use plain javascript, this will call your_func once, after 5 seconds:
setTimeout(function() { your_func(); }, 5000);
If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)
There is also a plugin I've used once. It has oneTime
and everyTime
methods.
The trim method should work great for you.
http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/lang/String.html#trim()
Returns a copy of the string, with leading and trailing whitespace omitted. If this String object represents an empty character sequence, or the first and last characters of character sequence represented by this String object both have codes greater than '\u0020' (the space character), then a reference to this String object is returned.
Otherwise, if there is no character with a code greater than '\u0020' in the string, then a new String object representing an empty string is created and returned.
Otherwise, let k be the index of the first character in the string whose code is greater than '\u0020', and let m be the index of the last character in the string whose code is greater than '\u0020'. A new String object is created, representing the substring of this string that begins with the character at index k and ends with the character at index m-that is, the result of this.substring(k, m+1).
This method may be used to trim whitespace from the beginning and end of a string; in fact, it trims all ASCII control characters as well.
Returns: A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.leading or trailing white space.
You could trim and then compare to an empty string or possibly check the length for 0.
You can use the fingerprintJS2 library, it helps a lot with calculating a browser fingerprint.
By the way, on Panopticlick you can see how unique this usually is.
Set it with a px value. Changing the code like below should work
el.css('marginLeft', mrg + 'px');
Almost what I wanted @Ralph, but here is the best answer. It'll solve your code problems:
To solve these problems, and meet all my requirements, I've adapted the code from here. I've cleaned it a little to make it more readable.
Option Explicit
Sub ExportAsCSV()
Dim MyFileName As String
Dim CurrentWB As Workbook, TempWB As Workbook
Set CurrentWB = ActiveWorkbook
ActiveWorkbook.ActiveSheet.UsedRange.Copy
Set TempWB = Application.Workbooks.Add(1)
With TempWB.Sheets(1).Range("A1")
.PasteSpecial xlPasteValues
.PasteSpecial xlPasteFormats
End With
Dim Change below to "- 4" to become compatible with .xls files
MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"
Application.DisplayAlerts = False
TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
TempWB.Close SaveChanges:=False
Application.DisplayAlerts = True
End Sub
There are still some small thing with the code above that you should notice:
.Close
and DisplayAlerts=True
should be in a finally clause, but I don't know how to do it in VBA- 5
to - 4
when setting MyFileName.Edit: put Local:=True
to save with my locale CSV delimiter.
I have had this same problem with the x64 version installation. It relates (in my case at least) to the dexplore.exe installation. I uninstalled dexplore, reinstalled it, did a heap of registry changes, etc. as per various blogs and SDKs all to no avail. What finally fixed it for me was editing this registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows\Installer\DisableBrowse
I changed the value to 0. Once the SDK had installed (quite happily this time) I set the value back to 1.
What alerted me to the possible error was the following in the SDK setup log:
12:19:42 PM Friday, 8 January 2010: SFX C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\SFX\dexplore.exe installation started with log file C:\TEMP\Microsoft Windows SDK for Windows 7_dd2d9383-116d-441f-85b3-7c16aeb3568e_SFX.log
12:19:47 PM Friday, 8 January 2010: C:\Program Files\Microsoft SDKs\Windows\v7.0\Setup\SFX\dexplore.exe installation failed with return code 1625
And this in the dexplore installation logfile:
MSI (s) (E4:7C) [12:19:46:680]: Machine policy value 'DisableBrowse' is 1
MSI (s) (E4:7C) [12:19:46:680]: Adding new sources is not allowed.
MSI (s) (E4:7C) [12:19:46:680]: Warning: rejected attempt to add new source 'c:\eb66d60e4283bfc2986755fa\' (product: {6753B40C-0FBD-3BED-8A9D-0ACAC2DCD85D})
MSI (s) (E4:7C) [12:19:46:680]: MSI_LUA: Elevation prompt disabled for silent installs
MSI (s) (E4:7C) [12:19:46:680]: Note: 1: 1729
MSI (s) (E4:7C) [12:19:46:680]: Product: Microsoft Document Explorer 2008 -- Configuration failed.
I hope this is of assistance in your situation.
I need exactly this requirement during my Travis job but with multiple values. I start with this solution but when calling multiple time this is very slow (I need 5 expresions).
I wrote a simple maven plugin to extract pom.xml's values into .sh file.
https://github.com/famaridon/ci-tools-maven-plugin
mvn com.famaridon:ci-tools-maven-plugin:0.0.1-SNAPSHOT:environment -Dexpressions=project.artifactId,project.version,project.groupId,project.build.sourceEncoding
Will produce that:
#!/usr/bin/env bash
CI_TOOLS_PROJECT_ARTIFACTID='ci-tools-maven-plugin';
CI_TOOLS_PROJECT_VERSION='0.0.1-SNAPSHOT';
CI_TOOLS_PROJECT_GROUPID='com.famaridon';
CI_TOOLS_PROJECT_BUILD_SOURCEENCODING='UTF-8';
now you can simply source the file
source .target/ci-tools-env.sh
Have fun.
<div class="container">
<div class="row justify-content-center">
<div class="col-3 text-center">
Center text goes here
</div>
</div>
</div>
I have used justify-content-center
class instead of mx-auto
as in this answer.
Key class:
@Embeddable
@Access (AccessType.FIELD)
public class EntryKey implements Serializable {
public EntryKey() {
}
public EntryKey(final Long id, final Long version) {
this.id = id;
this.version = version;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion() {
return this.version;
}
public void setVersion(Long version) {
this.version = version;
}
public boolean equals(Object other) {
if (this == other)
return true;
if (!(other instanceof EntryKey))
return false;
EntryKey castOther = (EntryKey) other;
return id.equals(castOther.id) && version.equals(castOther.version);
}
public int hashCode() {
final int prime = 31;
int hash = 17;
hash = hash * prime + this.id.hashCode();
hash = hash * prime + this.version.hashCode();
return hash;
}
@Column (name = "ID")
private Long id;
@Column (name = "VERSION")
private Long operatorId;
}
Entity class:
@Entity
@Table (name = "YOUR_TABLE_NAME")
public class Entry implements Serializable {
@EmbeddedId
public EntryKey getKey() {
return this.key;
}
public void setKey(EntryKey id) {
this.id = id;
}
...
private EntryKey key;
...
}
How can I duplicate it with another Version?
You can detach entity which retrieved from provider, change the key of Entry and then persist it as a new entity.
require
for installed gemsrequire_relative
for local filesrequire
uses your $LOAD_PATH
to find the files.
require_relative
uses the current location of the file using the statement
Require relies on you having installed (e.g. gem install [package]
) a package somewhere on your system for that functionality.
When using require
you can use the "./
" format for a file in the current directory, e.g. require "./my_file"
but that is not a common or recommended practice and you should use require_relative
instead.
This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use
require_relative '../../../filename'
(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).
Note that require_relative
uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative
path "stable" as it always be relative to the file requiring it in the same way.
I use []
.
The problem is that omega
in your case is matrix
of dimensions 1 * 1
. You should convert it to a vector if you wish to multiply t(X) %*% X
by a scalar (that is omega
)
In particular, you'll have to replace this line:
omega = rgamma(1,a0,1) / L0
with:
omega = as.vector(rgamma(1,a0,1) / L0)
everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.)
or c(t(.))
. Both are equivalent.
Here's the modified code that should work:
gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1,
a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
m0 = c(m01, m02)
C0 = matrix(nrow = 2, ncol = 2)
C0[1,1] = 1 / k01
C0[1,2] = 0
C0[2,1] = 0
C0[2,2] = 1 / k02
beta = mvrnorm(1,m0,C0)
omega = as.vector(rgamma(1,a0,1) / L0)
draws = matrix(ncol = 3,nrow = ndraw)
it = -nburn
while (it < ndraw) {
it = it + 1
C1 = solve(solve(C0) + omega * t(X) %*% X)
m1 = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
beta = mvrnorm(1, m1, C1)
a1 = a0 + n / 2
L1 = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2
omega = as.vector(rgamma(1, a1, 1) / L1)
if (it > 0) {
draws[it,1] = beta[1]
draws[it,2] = beta[2]
draws[it,3] = omega
}
}
return(draws)
}
mysql> GRANT ALL ON *.* to root@'192.168.1.%' IDENTIFIED BY 'your-root-password';
The wildcard character is a "%" instead of an "*"
You should use 'zip' function. Here is an example how your own zip function can look like
def custom_zip(seq1, seq2):
it1 = iter(seq1)
it2 = iter(seq2)
while True:
yield next(it1), next(it2)
Now, with EF Core you can convert data type transparently in your AppDbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// i.e. Store TimeSpan as string (custom)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(
timeSpan => timeSpan.ToString(), // To DB
timeSpanString => TimeSpan.Parse(timeSpanString) // From DB
);
// i.e. Store TimeSpan as string (using TimeSpanToStringConverter)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(new TimeSpanToStringConverter());
// i.e. Store TimeSpan as number of ticks (custom)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(
timeSpan => timeSpan.Ticks, // To DB
timeSpanString => TimeSpan.FromTicks(timeSpanString) // From DB
);
// i.e. Store TimeSpan as number of ticks (using TimeSpanToTicksConverter)
modelBuilder
.Entity<YourClass>()
.Property(x => x.YourTimeSpan)
.HasConversion(new TimeSpanToTicksConverter());
}
There's at least 2 ways of solve it:
1) chart.update()
2) Delete existing chart using chart.destroy() and create new chart object.
This article might be helpful with changing fonts.
From the article:
The commands to change font attributes are illustrated by the following example:
\fontencoding{T1}
\fontfamily{garamond}
\fontseries{m}
\fontshape{it}
\fontsize{12}{15}
\selectfont
This series of commands set the current font to medium weight italic garamond 12pt type with 15pt leading in the T1 encoding scheme, and the \selectfont command causes LaTeX to look in its mapping scheme for a metric corresponding to these attributes.
<li><a href="@Url.Action( "View", "Controller" )"><i class='fa fa-user'></i><span>Users View</span></a></li>
To display an icon with the link
Try modifying your global.asax file (simple add a space somewhere) and re-run. this will force the built in webserver to refresh and recompile the global.asax file.
Also do a clean and rebuild - should fix the problem
As others have already mentioned, HTML 4 requires the <style>
tag to be placed in the <head>
section (even though most browsers allow <style>
tags within the body
).
However, HTML 5 includes the scoped
attribute (see update below), which allows you to create style sheets that are scoped within the parent element of the <style>
tag. This also enables you to place <style>
tags within the <body>
element:
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="scoped-content">
<style type="text/css" scoped>
h1 { color: red; }
</style>
<h1>Hello</h1>
</div>
<h1>
World
</h1>
</body>
</html>
If you render the above code in an HTML-5 enabled browser that supports scoped
, you will see the limited scope of the style sheet.
There's just one major caveat...
At the time I'm writing this answer (May, 2013) almost no mainstream browser currently supports the scoped
attribute. (Although apparently developer builds of Chromium support it.)
HOWEVER, there is an interesting implication of the scoped
attribute that pertains to this question. It means that future browsers are mandated via the standard to allow <style>
elements within the <body>
(as long as the <style>
elements are scoped.)
So, given that:
scoped
attribute<style>
tags within the <body>
<style>
tags within the <body>
...then there is literally no harm * in placing <style>
tags within the body, as long as you future proof them with a scoped
attribute. The only problem is that current browsers won't actually limit the scope of the stylesheet - they'll apply it to the whole document. But the point is that, for all practical purposes, you can include <style>
tags within the <body>
provided that you:
scoped
attribute<body>
will not actually be scoped (because no mainstream browser support exists yet)
* except of course, for pissing off HTML validators...
Finally, regarding the common (but subjective) claim that embedding CSS within HTML is poor practice, it should be noted that the whole point of the scoped
attribute is to accommodate typical modern development frameworks that allow developers to import chunks of HTML as modules or syndicated content. It is very convenient to have embedded CSS that only applies to a particular chunk of HTML, in order to develop encapsulated, modular components with specific stylings.
Update as of Feb 2019, according to the Mozilla documentation, the scoped
attribute is deprecated. Chrome stopped supporting it in version 36 (2014) and Firefox in version 62 (2018). In both cases, the feature had to be explicitly enabled by the user in the browsers' settings. No other major browser ever supported it.
Here's an easier way:
sudo apt-get install maven
More details are here.
Usually, best is to see a character in his context.
Here is the full list of Unicode chars, and how your browser currently displays them. I am seeing this list evolving, browser versions after others.
This list is obtained by iteration in decimal of the html entities unicode table, it may take some seconds, but is very useful to me in many cases.
By hovering quickly a given char you will get the dec and hex and the shortcuts to generate it with a keyboard.
var i = 0
do document.write("<a title='(Linux|Hex): [CTRL+SHIFT]+u"+(i).toString(16)+"\nHtml entity: &# "+i+";\n&#x"+(i).toString(16)+";\n(Win|Dec): [ALT]+"+i+"' onmouseover='this.focus()' onclick='this.href=\"//google.com/?q=\"+this.innerHTML' style='cursor:pointer' target='new'>"+"&#"+i+";</a>"),i++
while (i<136690)
window.stop()
// From https://codepen.io/Nico_KraZhtest/pen/mWzXqy
_x000D_
The same snippet as a bookmarklet:
javascript:void%20!function(){var%20t=0;do{document.write(%22%3Ca%20title='(Linux|Hex):%20[CTRL+SHIFT]+u%22+t.toString(16)+%22\nHtml%20entity:%20%26%23%20%22+t+%22;\n%26%23x%22+t.toString(16)+%22;\n(Win|Dec):%20[ALT]+%22+t+%22'%20onmouseover='this.focus()'%20onclick='this.href=\%22https://google.com/%3Fq=\%22+this.innerHTML'%20style='cursor:pointer'%20target='new'%3E%26%23%22+t+%22;%3C/a%3E%22),t++}while(t%3C136690);window.stop()}();
To generate that list from php:
for ($x = 0; $x < 136690; $x++) {
echo html_entity_decode('&#'.$x.';',ENT_NOQUOTES,'UTF-8');
}
To generate that list into the console, using php:
php -r 'for ($x = 0; $x < 136690; $x++) { echo html_entity_decode("&#".$x.";",ENT_NOQUOTES,"UTF-8");}'
Here is a plain text extract, of arrows, some are coming with unicode 10.0. http://unicode.org/versions/Unicode10.0.0/
Unicode 10.0 adds 8,518 characters, for a total of 136,690 characters.
???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
Hey, did you notice the plain html <details>
element has a drop down arrow? This is sometimes all what we need.
<details>
<summary>Morning</summary>
<p>Hello world!</p>
</details>
<details>
<summary>Evening</summary>
<p>How sweat?</p>
</details>
_x000D_
This is actually an area ripe for discussion, with many subtle techniques available. It is important that you select/develop a technique that meets your needs including: screen readers, images/css/scripting on/off combinations, seo, etc.
Here are some good resources to get started down the road of standardista image replacement techniques:
http://faq.css-standards.org/Image_Replacement
Knowledge of high level programming languages (C/C++, Java, PHP, Python, Perl, etc.) would suggest to the layman that Bourne Again Shell (Bash) functions should work like they do in those other languages.
Instead, Bash functions work like shell commands and expect arguments to be passed to them in the same way one might pass an option to a shell command (e.g. ls -l
). In effect, function arguments in Bash are treated as positional parameters ($1, $2..$9, ${10}, ${11}
, and so on). This is no surprise considering how getopts
works. Do not use parentheses to call a function in Bash.
(Note: I happen to be working on OpenSolaris at the moment.)
# Bash style declaration for all you PHP/JavaScript junkies. :-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
function backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# sh style declaration for the purist in you. ;-)
# $1 is the directory to archive
# $2 is the name of the tar and zipped file when all is done.
backupWebRoot ()
{
tar -cvf - "$1" | zip -n .jpg:.gif:.png "$2" - 2>> $errorlog &&
echo -e "\nTarball created!\n"
}
# In the actual shell script
# $0 $1 $2
backupWebRoot ~/public/www/ webSite.tar.zip
Want to use names for variables? Just do something this.
local filename=$1 # The keyword declare can be used, but local is semantically more specific.
Be careful, though. If an argument to a function has a space in it, you may want to do this instead! Otherwise, $1
might not be what you think it is.
local filename="$1" # Just to be on the safe side. Although, if $1 was an integer, then what? Is that even possible? Humm.
Want to pass an array to a function?
callingSomeFunction "${someArray[@]}" # Expands to all array elements.
Inside the function, handle the arguments like this.
function callingSomeFunction ()
{
for value in "$@" # You want to use "$@" here, not "$*" !!!!!
do
:
done
}
Need to pass a value and an array, but still use "$@" inside the function?
function linearSearch ()
{
local myVar="$1"
shift 1 # Removes $1 from the parameter list
for value in "$@" # Represents the remaining parameters.
do
if [[ $value == $myVar ]]
then
echo -e "Found it!\t... after a while."
return 0
fi
done
return 1
}
linearSearch $someStringValue "${someArray[@]}"
Now you can use export_text.
from sklearn.tree import export_text
r = export_text(loan_tree, feature_names=(list(X_train.columns)))
print(r)
A complete example from [sklearn][1]
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.tree import export_text
iris = load_iris()
X = iris['data']
y = iris['target']
decision_tree = DecisionTreeClassifier(random_state=0, max_depth=2)
decision_tree = decision_tree.fit(X, y)
r = export_text(decision_tree, feature_names=iris['feature_names'])
print(r)
I give up!
Since there is no way to change the color of the input with autocomplete I decide to disable all of them with jQuery for webkit browsers. Like this:
if (/webkit/.test(navigator.userAgent.toLowerCase())) {
$('[autocomplete="on"]').each(function() {
$(this).attr('autocomplete', 'off');
});
}
I think it would help your comprehension if you think of connect()
and listen()
as counterparts, rather than connect()
and bind()
. The reason for this is that you can call or omit bind()
before either, although it's rarely a good idea to call it before connect()
, or not to call it before listen()
.
If it helps to think in terms of servers and clients, it is listen()
which is the hallmark of the former, and connect()
the latter. bind()
can be found - or not found - on either.
If we assume our server and client are on different machines, it becomes easier to understand the various functions.
bind()
acts locally, which is to say it binds the end of the connection on the machine on which it is called, to the requested address and assigns the requested port to you. It does that irrespective of whether that machine will be a client or a server. connect()
initiates a connection to a server, which is to say it connects to the requested address and port on the server, from a client. That server will almost certainly have called bind()
prior to listen()
, in order for you to be able to know on which address and port to connect to it with using connect()
.
If you don't call bind()
, a port and address will be implicitly assigned and bound on the local machine for you when you call either connect()
(client) or listen()
(server). However, that's a side effect of both, not their purpose. A port assigned in this manner is ephemeral.
An important point here is that the client does not need to be bound, because clients connect to servers, and so the server will know the address and port of the client even though you are using an ephemeral port, rather than binding to something specific. On the other hand, although the server could call listen()
without calling bind()
, in that scenario they would need to discover their assigned ephemeral port, and communicate that to any client that it wants to connect to it.
I assume as you mention connect()
you're interested in TCP, but this also carries over to UDP, where not calling bind()
before the first sendto()
(UDP is connection-less) also causes a port and address to be implicitly assigned and bound. One function you cannot call without binding is recvfrom()
, which will return an error, because without an assigned port and bound address, there is nothing to receive from (or too much, depending on how you interpret the absence of a binding).
I wrote a package named Pretty Slice. You can use it to visualize slices, and their backing arrays, etc.
package main
import pretty "github.com/inancgumus/prettyslice"
func main() {
nums := []int{1, 9, 5, 6, 4, 8}
odds := nums[:3]
evens := nums[3:]
nums[1], nums[3] = 9, 6
pretty.Show("nums", nums)
pretty.Show("odds : nums[:3]", odds)
pretty.Show("evens: nums[3:]", evens)
}
This code is going produce and output like this one:
For more details, please read: https://github.com/inancgumus/prettyslice
As mentioned here, this feature is not currently supported.
For this example you will need to create your own type, that would be an array. Then you create a bigger array which elements are of type you have just created.
To run my example you will need to fill columns A and B in Sheet1 with some values. Then run test(). It will read first two rows and add the values to the BigArr. Then it will check how many rows of data you have and read them all, from the place it has stopped reading, i.e., 3rd row.
Tested in Excel 2007.
Option Explicit
Private Type SmallArr
Elt() As Variant
End Type
Sub test()
Dim x As Long, max_row As Long, y As Long
'' Define big array as an array of small arrays
Dim BigArr() As SmallArr
y = 2
ReDim Preserve BigArr(0 To y)
For x = 0 To y
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Write what has been read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
'' Get the number of the last not empty row
max_row = Range("A" & Rows.Count).End(xlUp).Row
'' Change the size of the big array
ReDim Preserve BigArr(0 To max_row)
Debug.Print "new size of BigArr with old data = " & UBound(BigArr)
'' Check haven't we lost any data
For x = 0 To y
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
For x = y To max_row
'' We have to change the size of each Elt,
'' because there are some new for,
'' which the size has not been set, yet.
ReDim Preserve BigArr(x).Elt(0 To 1)
'' Take some test values
BigArr(x).Elt(0) = Cells(x + 1, 1).Value
BigArr(x).Elt(1) = Cells(x + 1, 2).Value
Next x
'' Check what we have read
Debug.Print "BigArr size = " & UBound(BigArr) + 1
For x = 0 To UBound(BigArr)
Debug.Print BigArr(x).Elt(0) & " | " & BigArr(x).Elt(1)
Next x
End Sub
Use CopyOnWriteArrayList
and if you want to remove it, do the following:
for (Iterator<String> it = userList.iterator(); it.hasNext() ;)
{
if (wordsToRemove.contains(word))
{
it.remove();
}
}
Use this style sheet to get you started !
.tooltip{
position:absolute;
z-index:1020;
display:block;
visibility:visible;
padding:5px;
font-size:11px;
opacity:0;
filter:alpha(opacity=0)
}
.tooltip.in{
opacity:.8;
filter:alpha(opacity=80)
}
.tooltip.top{
margin-top:-2px
}
.tooltip.right{
margin-left:2px
}
.tooltip.bottom{
margin-top:2px
}
.tooltip.left{
margin-left:-2px
}
.tooltip.top .tooltip-arrow{
bottom:0;
left:50%;
margin-left:-5px;
border-left:5px solid transparent;
border-right:5px solid transparent;
border-top:5px solid #000
}
.tooltip.left .tooltip-arrow{
top:50%;
right:0;
margin-top:-5px;
border-top:5px solid transparent;
border-bottom:5px solid transparent;
border-left:5px solid #000
}
.tooltip.bottom .tooltip-arrow{
top:0;
left:50%;
margin-left:-5px;
border-left:5px solid transparent;
border-right:5px solid transparent;
border-bottom:5px solid #000
}
.tooltip.right .tooltip-arrow{
top:50%;
left:0;
margin-top:-5px;
border-top:5px solid transparent;
border-bottom:5px solid transparent;
border-right:5px solid #000
}
.tooltip-inner{
max-width:200px;
padding:3px 8px;
color:#fff;
text-align:center;
text-decoration:none;
background-color:#000;
-webkit-border-radius:4px;
-moz-border-radius:4px;
border-radius:4px
}
.tooltip-arrow{
position:absolute;
width:0;
height:0
}
ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);
I have always found it difficult to remember all the keys; so I keep the below notes handy, hope they help someone! Let me know if it can be improved.
Key: An attribute or combination of attributes that uniquely identify an entity/record in a relational table.
PK: A single key that is unique and not-null. It is one of the candidate keys.
Foreign Key: FK is a key in one table (child) that uniquely identifies a row of another table (parent). A FK is not-unique in the child table. It is a candidate key in the parent table. Referential integrity is maintained as the value in FK is present as a value in PK in parent table else it is NULL.
Unique Key: A unique key that may or may not be NULL
Natural key: PK in OLTP. It may be a PK in OLAP.
Surrogate Key: It is the Surrogate PK in OLAP acting as the substitute of the PK in OLTP. Artificial key generated internally in OLAP.
Composite Key: PK made up of multiple attributes
SuperKey: A key that can be uniquely used to identify a database record, that may contain extra attributes that are not necessary to uniquely identify records.
Candidate Key: A candidate key can be uniquely used to identify a database record without any extraneous data. They are Not Null and unique. It is a minimal super-key.
Alternate Key: A candidate key that is not the primary key is called an alternate key.
Candidate Key/s with Extraneous data: Consider that can be used to identify a record in the Employee table but candidate key alone is sufficient for this task. So becomes the extraneous data.
Note that the PK, Foreign Key, Unique Key, Natural key, Surrogate Key, Composite Key are defined as Database objects; where the Natural key is a PK in the OLTP and could be a PK in the target OLAP. For the rest of the keys, it's up to the DB designer/architect to decide whether unique/not-null/referential integrity constraints need to enforced or not.
Below I have tried to use set theory to simplify the representation of the membership of the keys w.r.t. each other.
key = { All of the below keys }
PK = { PK }
Foreign Key = { Key with Not Null constraint }
Unique Key = { {Candidate Key/s}, {attributes containing NULL} }
Natural key = { PK }
Surrogate Key = { PK }
Composite Key = { PK }
Super Key = { {Candidate Key/s}, {Candidate Key/s with Extraneous data} }
Candidate Key = { PK, {Alternate Key/s} }
Alternate Key = { {Candidate Keys} - PK }
Candidate Key/s with Extraneous data = { }
I have summarized it below:
Notes: an-overview-of-the-database-keys-primary-key-composite-key-surrogate-key-et-al
sudo apt-get install nodejs
installs nodejs
sudo apt-get install npm
installs npm
sudo npm install bower -g
installs bower via npm
$('div#imageContainer').click(function () {
$('div#imageContainerimg').attr('src', 'YOUR NEW IMAGE URL HERE');
});
You can give both user name and PASSSWORD on the command line itself.
psql "dbname='urDbName' user='yourUserName' password='yourPasswd' host='yourHost'" -f yourFileName.sql
While you could try these settings in config file
<system.web>
<httpRuntime requestPathInvalidCharacters="" requestValidationMode="2.0" />
<pages validateRequest="false" />
</system.web>
I would avoid using characters like '&' in URL path replacing them with underscores.
This is the great description and step-by-step instruction how to create and manage master and slave (gcc and g++) alternatives.
Shortly it's:
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 60 --slave /usr/bin/g++ g++ /usr/bin/g++-4.6
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.7 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.7
sudo update-alternatives --config gcc
List(1,2,3) :+ 4
Results in List[Int] = List(1, 2, 3, 4)
Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).
git config --global --unset http.proxy
Here's my current implementation:
$.liveClickHold = function(selector, fn) {
$(selector).live("mousedown", function(evt) {
var $this = $(this).data("mousedown", true);
setTimeout(function() {
if ($this.data("mousedown") === true) {
fn(evt);
}
}, 500);
});
$(selector).live("mouseup", function(evt) {
$(this).data("mousedown", false);
});
}
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
"SQL Server Reporting Service" was causing issues in my system, after stopping it, Apache started working fine
Updated to use your newly provided data:
The solutions using the original data may be found at the end of this answer.
Using your new data:
DECLARE @T TABLE( [contract] INT, project INT, activity INT )
INSERT INTO @T VALUES( 1000, 8000, 10 )
INSERT INTO @T VALUES( 1000, 8000, 20 )
INSERT INTO @T VALUES( 1000, 8001, 10 )
INSERT INTO @T VALUES( 2000, 9000, 49 )
INSERT INTO @T VALUES( 2000, 9001, 49 )
INSERT INTO @T VALUES( 3000, 9000, 79 )
INSERT INTO @T VALUES( 3000, 9000, 78 )
SELECT DISTINCT [contract], activity FROM @T AS A WHERE
(SELECT COUNT( DISTINCT activity )
FROM @T AS B WHERE B.[contract] = A.[contract]) = 1
returns: 2000, 49
Solutions using original data
WARNING: The following solutions use the data previously given in the question and may not make sense for the current question. I have left them attached for completeness only.
SELECT Col1, Count( col1 ) AS count FROM table
GROUP BY col1
HAVING count > 1
This should get you a list of all the values in col1 that are not distinct. You can place this in a table var or temp table and join against it.
Here is an example using a sub-query:
DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )
INSERT INTO @t VALUES( 'A', 'B', 'C' );
INSERT INTO @t VALUES( 'D', 'E', 'F' );
INSERT INTO @t VALUES( 'A', 'J', 'K' );
INSERT INTO @t VALUES( 'G', 'H', 'H' );
SELECT * FROM @t
SELECT col1, col2 FROM @t WHERE col1 NOT IN
(SELECT col1 FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) > 1)
This returns:
D E
G H
And another method that users a temp table and join:
DECLARE @t TABLE( col1 VARCHAR(1), col2 VARCHAR(1), col3 VARCHAR(1) )
INSERT INTO @t VALUES( 'A', 'B', 'C' );
INSERT INTO @t VALUES( 'D', 'E', 'F' );
INSERT INTO @t VALUES( 'A', 'J', 'K' );
INSERT INTO @t VALUES( 'G', 'H', 'H' );
SELECT * FROM @t
DROP TABLE #temp_table
SELECT col1 INTO #temp_table
FROM @t AS t GROUP BY col1 HAVING COUNT( col1 ) = 1
SELECT t.col1, t.col2 FROM @t AS t
INNER JOIN #temp_table AS tt ON t.col1 = tt.col1
Also returns:
D E
G H
If it fits your requirements, you can use bcp on the command line if you do this frequently or want to build it into a production process.
Here's a link describing the configuration.
I had the same issue.
Only after I changed in php.ini variable
display_errors = Off
to
display_errors = On
Phpadmin started working.. crazy....
Extending the best answer for finding floating point numbers
String str="2.53GHz";
String decimal_values= str.replaceAll("[^0-9\\.]", "");
System.out.println(decimal_values);
The default value for a GUID is empty. (eg: 00000000-0000-0000-0000-000000000000)
This can be invoked using Guid.Empty
or new Guid()
If you want a new GUID, you use Guid.NewGuid()
Below worked for me:
When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/
Hi you can use icon as SVG and set colors. See this code
/*_x000D_
* declare map and places as a global variable_x000D_
*/_x000D_
var map;_x000D_
var places = [_x000D_
['Place 1', "<h1>Title 1</h1>", -0.690542, -76.174856,"red"],_x000D_
['Place 2', "<h1>Title 2</h1>", -5.028249, -57.659052,"blue"],_x000D_
['Place 3', "<h1>Title 3</h1>", -0.028249, -77.757507,"green"],_x000D_
['Place 4', "<h1>Title 4</h1>", -0.800101286, -76.78747820,"orange"],_x000D_
['Place 5', "<h1>Title 5</h1>", -0.950198, -78.959302,"#FF33AA"]_x000D_
];_x000D_
/*_x000D_
* use google maps api built-in mechanism to attach dom events_x000D_
*/_x000D_
google.maps.event.addDomListener(window, "load", function () {_x000D_
_x000D_
/*_x000D_
* create map_x000D_
*/_x000D_
var map = new google.maps.Map(document.getElementById("map_div"), {_x000D_
mapTypeId: google.maps.MapTypeId.ROADMAP,_x000D_
});_x000D_
_x000D_
/*_x000D_
* create infowindow (which will be used by markers)_x000D_
*/_x000D_
var infoWindow = new google.maps.InfoWindow();_x000D_
/*_x000D_
* create bounds (which will be used auto zoom map)_x000D_
*/_x000D_
var bounds = new google.maps.LatLngBounds();_x000D_
_x000D_
/*_x000D_
* marker creater function (acts as a closure for html parameter)_x000D_
*/_x000D_
function createMarker(options, html) {_x000D_
var marker = new google.maps.Marker(options);_x000D_
bounds.extend(options.position);_x000D_
if (html) {_x000D_
google.maps.event.addListener(marker, "click", function () {_x000D_
infoWindow.setContent(html);_x000D_
infoWindow.open(options.map, this);_x000D_
map.setZoom(map.getZoom() + 1)_x000D_
map.setCenter(marker.getPosition());_x000D_
});_x000D_
}_x000D_
return marker;_x000D_
}_x000D_
_x000D_
/*_x000D_
* add markers to map_x000D_
*/_x000D_
for (var i = 0; i < places.length; i++) {_x000D_
var point = places[i];_x000D_
createMarker({_x000D_
position: new google.maps.LatLng(point[2], point[3]),_x000D_
map: map,_x000D_
icon: {_x000D_
path: "M27.648 -41.399q0 -3.816 -2.7 -6.516t-6.516 -2.7 -6.516 2.7 -2.7 6.516 2.7 6.516 6.516 2.7 6.516 -2.7 2.7 -6.516zm9.216 0q0 3.924 -1.188 6.444l-13.104 27.864q-0.576 1.188 -1.71 1.872t-2.43 0.684 -2.43 -0.684 -1.674 -1.872l-13.14 -27.864q-1.188 -2.52 -1.188 -6.444 0 -7.632 5.4 -13.032t13.032 -5.4 13.032 5.4 5.4 13.032z",_x000D_
scale: 0.6,_x000D_
strokeWeight: 0.2,_x000D_
strokeColor: 'black',_x000D_
strokeOpacity: 1,_x000D_
fillColor: point[4],_x000D_
fillOpacity: 0.85,_x000D_
},_x000D_
}, point[1]);_x000D_
};_x000D_
map.fitBounds(bounds);_x000D_
});
_x000D_
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3"></script>_x000D_
<div id="map_div" style="height: 400px;"></div>
_x000D_
You can use Spannable
to apply effects to your TextView
:
Here is my example for colouring just the first part of a TextView
text (while allowing you to set the color dynamically rather than hard coding it into a String as with the HTML example!)
mTextView.setText("Red text is here", BufferType.SPANNABLE);
Spannable span = (Spannable) mTextView.getText();
span.setSpan(new ForegroundColorSpan(0xFFFF0000), 0, "Red".length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
In this example you can replace 0xFFFF0000 with a getResources().getColor(R.color.red)
Let's make a Go 1-compatible list of all the ways to read and write files in Go.
Because file API has changed recently and most other answers don't work with Go 1. They also miss bufio
which is important IMHO.
In the following examples I copy a file by reading from it and writing to the destination file.
Start with the basics
package main
import (
"io"
"os"
)
func main() {
// open input file
fi, err := os.Open("input.txt")
if err != nil {
panic(err)
}
// close fi on exit and check for its returned error
defer func() {
if err := fi.Close(); err != nil {
panic(err)
}
}()
// open output file
fo, err := os.Create("output.txt")
if err != nil {
panic(err)
}
// close fo on exit and check for its returned error
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
// make a buffer to keep chunks that are read
buf := make([]byte, 1024)
for {
// read a chunk
n, err := fi.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if n == 0 {
break
}
// write a chunk
if _, err := fo.Write(buf[:n]); err != nil {
panic(err)
}
}
}
Here I used os.Open
and os.Create
which are convenient wrappers around os.OpenFile
. We usually don't need to call OpenFile
directly.
Notice treating EOF. Read
tries to fill buf
on each call, and returns io.EOF
as error if it reaches end of file in doing so. In this case buf
will still hold data. Consequent calls to Read
returns zero as the number of bytes read and same io.EOF
as error. Any other error will lead to a panic.
Using bufio
package main
import (
"bufio"
"io"
"os"
)
func main() {
// open input file
fi, err := os.Open("input.txt")
if err != nil {
panic(err)
}
// close fi on exit and check for its returned error
defer func() {
if err := fi.Close(); err != nil {
panic(err)
}
}()
// make a read buffer
r := bufio.NewReader(fi)
// open output file
fo, err := os.Create("output.txt")
if err != nil {
panic(err)
}
// close fo on exit and check for its returned error
defer func() {
if err := fo.Close(); err != nil {
panic(err)
}
}()
// make a write buffer
w := bufio.NewWriter(fo)
// make a buffer to keep chunks that are read
buf := make([]byte, 1024)
for {
// read a chunk
n, err := r.Read(buf)
if err != nil && err != io.EOF {
panic(err)
}
if n == 0 {
break
}
// write a chunk
if _, err := w.Write(buf[:n]); err != nil {
panic(err)
}
}
if err = w.Flush(); err != nil {
panic(err)
}
}
bufio
is just acting as a buffer here, because we don't have much to do with data. In most other situations (specially with text files) bufio
is very useful by giving us a nice API for reading and writing easily and flexibly, while it handles buffering behind the scenes.
Note: The following code is for older Go versions (Go 1.15 and before). Things have changed. For the new way, take a look at this answer.
Using ioutil
package main
import (
"io/ioutil"
)
func main() {
// read the whole file at once
b, err := ioutil.ReadFile("input.txt")
if err != nil {
panic(err)
}
// write the whole body at once
err = ioutil.WriteFile("output.txt", b, 0644)
if err != nil {
panic(err)
}
}
Easy as pie! But use it only if you're sure you're not dealing with big files.
The copy
command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.
Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).
I tried a variation of your command as follows in SQL*Plus (with no errors):
copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;
After I executed the above statement, I also truncate the new_emp table and executed this command:
copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;
With SQL Developer, you could do the following to perform a similar approach to copying objects:
On the tool bar, select Tools>Database copy.
Identify source and destination connections with the copy options you would like.
For object type, select table(s).
The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).
It is a build target that is not a filename.
Recommended Sanity Check - Make sure to add the form-control
class to your inputs.
If you have bootstrap css loaded on your page, but your inputs don't have the
class="form-control"
then placeholder CSS selector won't apply to them.
Example markup from the docs:
I know this didn't apply to the OP's markup but as I missed this at first and spent a little bit of effort trying to debug it, I'm posting this answer to help others.
That's what ln
is documented to do when the target already exists and is a directory. If you want /etc/nginx
to be a symlink rather than contain a symlink, you had better not create it as a directory first!
In case you don't want/need to post:
@Html.ActionLink("link caption", "actionName", new { Model.Page }) // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);
[HttpGet]
public ActionResult actionName(int reportID)
{
Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)
Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.
If you need by several params:
$ids = [1,2,3,4];
$not_ids = [5,6,7,8];
DB::table('table')->whereIn('id', $ids)
->whereNotIn('id', $not_ids)
->where('status', 1)
->get();
You are triggering the event before the event is even bound.
Just move the triggering
of the event to after attaching the event.
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
Also it's possible to use attribute [FromHeader] for web methods parameters (or properties in a Model class) which should be sent in custom headers. Something like this:
[HttpGet]
public ActionResult Products([FromHeader(Name = "User-Identity")]string userIdentity)
At least it works fine for ASP.NET Core 2.1 and Swashbuckle.AspNetCore 2.5.0.
You may also use the .jquery property as described here: http://api.jquery.com/jquery-2/
var a = { what: "A regular JS object" },
b = $('body');
if ( a.jquery ) { // falsy, since it's undefined
alert(' a is a jQuery object! ');
}
if ( b.jquery ) { // truthy, since it's a string
alert(' b is a jQuery object! ');
}
This should handle issue:
SPOOL_FILE=${LOG_DIR}/${LOG_FILE_NAME}.spool
SQLPLUS_OUTPUT=`sqlplus -s "$SFDC_WE_CORE" <<EOF
SET HEAD OFF
SET AUTOPRINT OFF
SET TERMOUT OFF
SET SERVEROUTPUT ON
SPOOL ${SPOOL_FILE}
WHENEVER SQLERROR EXIT SQL.SQLCODE
DECLARE
BEGIN
foooo
--rollback;
END;
/
EOF`
RC=$?
if [[ $RC != 0 ]] ; then
echo " RDBMS exit code : $RC " | tee -a ${LOG_FILE}
cat ${SPOOL_FILE} | tee -a ${LOG_FILE}
cat ${LOG_FILE} | mail -s "Script ${INIT_EXE} failed on $SFDC_ENV" $SUPPORT_LIST
exit 3
fi