If you dont want to hard-code the cell addresses you can use the ROW()
function.
eg: =AVERAGE(INDIRECT("A" & ROW()), INDIRECT("C" & ROW()))
Its probably not the best way to do it though! Using Auto-Fill and static columns like @JaiGovindani suggests would be much better.
canvas.addEventListener('click', function(event) {
click++;
if(click == 50) {
this.removeEventListener('click',arguments.callee,false);
}
Should do it.
The solution I use is the following:
<input list="answers" id="answer">
<datalist id="answers">
<option data-value="42" value="The answer">
</datalist>
Then access the value to be sent to the server using JavaScript like this:
var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;
Hope it helps.
I used this for getting Date and Time in a fragment.
private Handler mHandler = new Handler(Looper.getMainLooper());
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_head_screen, container, false);
dateTextView = root.findViewById(R.id.dateView);
hourTv = root.findViewById(R.id.hourView);
Thread thread = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
mHandler.post(new Runnable() {
@Override
public void run() {
//Calendario para obtener fecha & hora
Date currentTime = Calendar.getInstance().getTime();
SimpleDateFormat date_sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat hour_sdf = new SimpleDateFormat("HH:mm a");
String currentDate = date_sdf.format(currentTime);
String currentHour = hour_sdf.format(currentTime);
dateTextView.setText(currentDate);
hourTv.setText(currentHour);
}
});
}
} catch (InterruptedException e) {
Log.v("InterruptedException", e.getMessage());
}
}
};
}
I don't recommend storing passwords in a script, but this is a way to what you indicate:
use 5.010;
my %user_table = ( tom => '123!', frank => '321!' );
say ( $user_table{ $name } eq $password ? 'You have gained access.'
: 'Access denied!'
);
Any time you want to enforce an association like this, it's a good idea to think of a table, and the most common form of table in Perl is the hash.
Tagging this answer which helped me, might not answer the actual question
If you are using password instead of private key, please refer to this answer for tested working solution on Ubuntu 16.04.5 and 20.04.1
For those who landed here and are searching for a solution that merges N arrays AND also sums the values of identical keys found in the N arrays, I've written this function that works recursively as well. (See: https://gist.github.com/Nickology/f700e319cbafab5eaedc)
Example:
$a = array( "A" => "bob", "sum" => 10, "C" => array("x","y","z" => 50) );
$b = array( "A" => "max", "sum" => 12, "C" => array("x","y","z" => 45) );
$c = array( "A" => "tom", "sum" => 8, "C" => array("x","y","z" => 50, "w" => 1) );
print_r(array_merge_recursive_numeric($a,$b,$c));
Will result in:
Array
(
[A] => tom
[sum] => 30
[C] => Array
(
[0] => x
[1] => y
[z] => 145
[w] => 1
)
)
Here's the code:
<?php
/**
* array_merge_recursive_numeric function. Merges N arrays into one array AND sums the values of identical keys.
* WARNING: If keys have values of different types, the latter values replace the previous ones.
*
* Source: https://gist.github.com/Nickology/f700e319cbafab5eaedc
* @params N arrays (all parameters must be arrays)
* @author Nick Jouannem <[email protected]>
* @access public
* @return void
*/
function array_merge_recursive_numeric() {
// Gather all arrays
$arrays = func_get_args();
// If there's only one array, it's already merged
if (count($arrays)==1) {
return $arrays[0];
}
// Remove any items in $arrays that are NOT arrays
foreach($arrays as $key => $array) {
if (!is_array($array)) {
unset($arrays[$key]);
}
}
// We start by setting the first array as our final array.
// We will merge all other arrays with this one.
$final = array_shift($arrays);
foreach($arrays as $b) {
foreach($final as $key => $value) {
// If $key does not exist in $b, then it is unique and can be safely merged
if (!isset($b[$key])) {
$final[$key] = $value;
} else {
// If $key is present in $b, then we need to merge and sum numeric values in both
if ( is_numeric($value) && is_numeric($b[$key]) ) {
// If both values for these keys are numeric, we sum them
$final[$key] = $value + $b[$key];
} else if (is_array($value) && is_array($b[$key])) {
// If both values are arrays, we recursively call ourself
$final[$key] = array_merge_recursive_numeric($value, $b[$key]);
} else {
// If both keys exist but differ in type, then we cannot merge them.
// In this scenario, we will $b's value for $key is used
$final[$key] = $b[$key];
}
}
}
// Finally, we need to merge any keys that exist only in $b
foreach($b as $key => $value) {
if (!isset($final[$key])) {
$final[$key] = $value;
}
}
}
return $final;
}
?>
$(document).ready(function(){
var div=$('#header');
var start=$(div).offset().top;
$.event.add(window,'scroll',function(){
var p=$(window).scrollTop();
$(div).css('position',(p>start)?'fixed':'static');
$(div).css('top',(p>start)?'0px':'');
});
});
It works perfectly.
This is not a bug in your code. It is coming from .Net's Socket implementation. If you use the overloaded implementation of EndReceive as below you will not get this exception.
SocketError errorCode;
int nBytesRec = socket.EndReceive(ar, out errorCode);
if (errorCode != SocketError.Success)
{
nBytesRec = 0;
}
`CSS:
input#search{
background-image: url(bg.jpg);
background-repeat: no-repeat;
text-indent: 20px;
}
input#search:focus{
background-image:none;
}
HTML:
<input type="text" id="search" name="search" value="search" />`
Possible Solution
Swift provides distance() which measures the distance between start and end that can be used to create an NSRange:
let text = "Long paragraph saying something goes here!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)
text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
let start = distance(text.startIndex, substringRange.startIndex)
let length = distance(substringRange.startIndex, substringRange.endIndex)
let range = NSMakeRange(start, length)
// println("word: \(substring) - \(d1) to \(d2)")
if (substring == "saying") {
attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range)
}
})
there is a good library to use its called djagno-nomad, although not directly related to the question asked, thought of sharing this,
scenario: most of the time when switching to project, we feel like it should revert our changes that we did on this current branch, that's what exactly this library does, checkout below
As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:
WHILE EXISTS (SELECT 1
FROM YourTable
WHERE <yourCondition>)
DELETE TOP(10000) FROM YourTable
WHERE <yourCondition>
SELECT id, COUNT(id) FROM table1 GROUP BY id HAVING COUNT(id)>1;
I think this will work properly to search repeated values in a particular column.
If you are looking for a way to it without SQL you should be able to use delete_all.
Post.delete_all
or with a criteria
Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"
See here for more information.
The records are deleted without loading them first which makes it very fast but will break functionality like counter cache that depends on rails code to be executed upon deletion.
Have you tried :
hadoop dfs -rmr hdfs://host:port/Navi/MyDir\,\ Name
?
This question has been answered properly, but I would like to add my approach, it's not that different than what the others have mentioned.
I use different layouts pages to call different headers/footers, some call this layout, some call it template etc.
Edit core/Loader.php
and add your own function to load your layout, I called the function e.g.layout
.
Create your own template page and make it call header/footer
for you, I called it default.php
and put in a new directory e.g. view/layout/default.php
Call your own view page from your controller as you would normally. But instead of calling $this-load->view
use $this->load->layout
, layout function will call the default.php
and default.php
will call your header and footer.
1)
In core/Loader.php
under view() function I duplicated it and added mine
public function layout($view, $vars = array(), $return = FALSE)
{
$vars["display_page"] = $view;//will be called from the layout page
$layout = isset($vars["layout"]) ? $vars["layout"] : "default";
return $this->_ci_load(array('_ci_view' => "layouts/$layout", '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
2) Create layout folder and put default.php in it in view/layout/default.php
$this->load->view('parts/header');//or wherever your header is
$this->load->view($display_page);
$this->load->view('parts/footer');or wherever your footer is
3) From your controller, call your layout
$this->load->layout('projects');// will use 'view/layout/default.php' layout which in return will call header and footer as well.
To use another layout, include the new layout name in your $data
array
$data["layout"] = "full_width";
$this->load->layout('projects', $data);// will use full_width.php layout
and of course you must have your new layout in the layout directory as in:
view/layout/full_width.php
As simple as this !
var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);
You can apply the .toUpperCase() directly on String variables or as an attribute to text fields. Ex: -
String str;
TextView txt;
str.toUpperCase();// will change it to all upper case OR
txt.append(str.toUpperCase());
txt.setText(str.toUpperCase());
If you want to copy files and see a "progress" I suggest the script below in Batch that I used from another script as a base
I used a progress bar and a percentage while the script copies the game files Nuclear throne:
@echo off
title NTU Installer
setlocal EnableDelayedExpansion
@echo Iniciando instalacao...
if not exist "C:\NTU" (
md "C:\NTU
)
if not exist "C:\NTU\Profile" (
md "C:\NTU\Profile"
)
ping -n 5 localhost >nul
for %%f in (*.*) do set/a vb+=1
set "barra="
::loop da barra
for /l %%i in (1,1,70) do set "barra=!barra!Û"
rem barra vaiza para ser preenchida
set "resto="
rem loop da barra vazia
for /l %%i in (1,1,110) do set "resto=!resto!"
set i=0
rem carregameno de arquivos
for %%f in (*.*) do (
>>"log_ntu.css" (
copy "%%f" "C:\NTU">nul
echo Copiado:%%f
)
cls
set /a i+=1,percent=i*100/vb,barlen=70*percent/100
for %%a in (!barlen!) do echo !percent!%% /
[!barra:~0,%%a!%resto%]
echo Instalado:[%%f] / Complete:[!percent!%%/100%]
ping localhost -n 1.9 >nul
)
xcopy /e "Profile" "C:\NTU\Profile">"log_profile.css"
@echo Criando atalho na area de trabalho...
copy "NTU.lnk" "C:\Users\%username%\Desktop">nul
ping localhost -n 4 >nul
@echo Arquivos instalados!
pause
You may want to try self-closing floats, as detailed on http://www.sitepoint.com/simple-clearing-of-floats/
So perhaps try either overflow: auto
(usually works), or overflow: hidden
, as alex said.
Go to
Xcode menu > Preferences > Font & Color > Category
Double-click on Plain Text, a popup menu will come up. Change it from there.
I was facing such a problem, look at the picture below
and here is its HTML
<tr class="li1">
<td valign="top">1.</td>
<td colspan="5" valign="top">
<p>How to build e-book learning environment</p>
</td>
</tr>
so I fix it by changing valign Attribute in both td
tags to baseline
and it worked
hope this help you
Just Create New User for MySQL do not use root. there is a problem its security issue
sudo mysql -p -u root
Login into MySQL or MariaDB with root privileges
CREATE USER 'troy121'@'%' IDENTIFIED BY 'mypassword123';
login and create a new user
GRANT ALL PRIVILEGES ON *.* TO 'magento121121'@'%' WITH GRANT OPTION;
and grant privileges to access "." and "@" "%" any location not just only 'localhost'
exit;
if you want to see your privilege table SHOW GRANTS;
& Enjoy.
Try this:-
ALTER TABLE <TABLE NAME to be moved> MOVE TABLESPACE <destination TABLESPACE NAME>
Very nice suggestion from IVAN in comments so thought to add in my answer
Note: this will invalidate all table's indexes. So this command is usually followed by
alter index <owner>."<index_name>" rebuild;
This works.
public class TestButton {
public TestButton() {
JFrame f = new JFrame();
f.setSize(new Dimension(200,200));
JPanel p = new JPanel();
p.setLayout(new FlowLayout());
final JButton stop = new JButton("Stop");
final JButton start = new JButton("Start");
p.add(start);
p.add(stop);
f.getContentPane().add(p);
stop.setEnabled(false);
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(true);
stop.setEnabled(false);
}
});
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
start.setEnabled(false);
stop.setEnabled(true);
}
});
f.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
new TestButton();
}
}
If you're using node you can:
const fs = require('fs');
const { config } = JSON.parse(fs.readFileSync('../config.json', 'utf8')) // May be incorrect, haven't used fs in a long time
OR
const evaluation = require('../config.json');
// evaluation will then contain all props, so evaluation.config
// or you could use:
const { config } = require('../config.json');
Else:
// config.js
{
// json object here
}
// script.js
import { config } from '../config.js';
OR
import * from '../config.json'
Once you have markers on the map, you can retrieve the Lat/Long coordinates through the API and use this to set the map's center. You'll first just need to determine which marker you wish to center on - I'll leave that up to you.
// "marker" refers to the Marker object you wish to center on
var latLng = marker.getPosition(); // returns LatLng object
map.setCenter(latLng); // setCenter takes a LatLng object
Info windows are separate objects which are typically bound to a marker, so to open the info window you might do something like this (however it will depend on your code):
var infoWindow = marker.infoWindow; // retrieve the InfoWindow object
infoWindow.open(map); // Trigger the "open()" method
Hope this helps.
The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:
import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square')
plt.xlabel('x')
plt.ylabel('y')
plt.xticks(xi, x)
plt.title('compare')
plt.legend()
plt.show()
The quickest way is to switch default branch from master to another and you can remove master branch from the web interface.
That should help
df.groupby(['NFF', 'ABUSE']).size().unstack().plot(kind='bar', stacked=True)
Try a conditional group matching 50-99
or any string of three or more digits:
var r = /^(?:[5-9]\d|\d{3,})$/
$(document).ready(function() {
$("#aDateFrom").datepicker({
onSelect: function() {
//- get date from another datepicker without language dependencies
var minDate = $('#aDateFrom').datepicker('getDate');
$("#aDateTo").datepicker("change", { minDate: minDate });
}
});
$("#aDateTo").datepicker({
onSelect: function() {
//- get date from another datepicker without language dependencies
var maxDate = $('#aDateTo').datepicker('getDate');
$("#aDateFrom").datepicker("change", { maxDate: maxDate });
}
});
});
switch(position) {
case 0:
...
break;
case 1:
...
break;
default:
...
}
Did you mean that?
To mark a lambda async, simply prepend async
before its argument list:
// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
SQLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupName);
}));
Have you add a default route to this class?
public class RouteConfig {
public static void RegisterRoutes (RouteCollection routes) {`
//"HomePage" is the root view of your app
routes.MapRoute (
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new {
controller = "Home", action = "HomePage", id = UrlParameter.Optional
}
);
}
}
` After that in Global.asax.cs add this line to Application_Start() method:
RouteConfig.RegisterRoutes (RouteTable.Routes);
I had this problem after I made an upgrade from MVC4 to MVC5 following this post and I had that line commented for a reason that I've forgot.
Hope this helps!
Try using an array:
ObjectClass[] arrayName = SetOfObjects.toArray(new ObjectClass[setOfObjects.size()]);
Something like this:
var div = document.getElementById("result");_x000D_
_x000D_
var str = "{'a':1}";_x000D_
str = str.replace(/\'/g, '"');_x000D_
var parsed = JSON.parse(str);_x000D_
console.log(parsed);_x000D_
div.innerText = parsed.a;
_x000D_
<div id="result"></div>
_x000D_
@"string here
that is long you mean"
But be careful, because
@"string here
and space before this text
means the space is also a part of the string"
It also escapes things in the string
@"c:\\folder" // c:\\folder
@"c:\folder" // c:\folder
"c:\\folder" // c:\folder
Related
To get an iterable set:
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
You can convert hex to RGB:
string ccode = "#00FFFF00";
int argb = Int32.Parse(ccode.Replace("#", ""), NumberStyles.HexNumber);
Color clr = Color.FromArgb(argb);
Do you mean altering the table after it has been created? If so you need to use alter table, in particular:
ALTER TABLE tablename MODIFY COLUMN new-column-definition
e.g.
ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);
Java 7 and 8. Increment DOES change the reference, so it references to another Integer object. Look:
@Test
public void incInteger()
{
Integer i = 5;
Integer iOrig = i;
++i; // Same as i = i + 1;
Assert.assertEquals(6, i.intValue());
Assert.assertNotEquals(iOrig, i);
}
Integer by itself is still immutable.
Here is code
DatabaseMyHandler.class
public class DatabaseMyHandler extends SQLiteOpenHelper {
private SQLiteDatabase myDataBase;
private Context context = null;
private static String TABLE_NAME = "customer";
public static final String DATABASE_NAME = "Student.db";
public final static String DATABASE_PATH = "/data/data/com.pkgname/databases/";
public static final int DATABASE_VERSION = 2;
public DatabaseMyHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
try {
createDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
myDataBase = sqLiteDatabase;
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
//Check database already exists or not
private boolean checkDatabaseExists() {
boolean checkDB = false;
try {
String PATH = DATABASE_PATH + DATABASE_NAME;
File dbFile = new File(PATH);
checkDB = dbFile.exists();
} catch (SQLiteException e) {
}
return checkDB;
}
//Create a empty database on the system
public void createDatabase() throws IOException {
boolean dbExist = checkDatabaseExists();
if (dbExist) {
Log.v("DB Exists", "db exists");
}
boolean dbExist1 = checkDatabaseExists();
if (!dbExist1) {
this.getWritableDatabase();
try {
this.close();
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
//Copies your database from your local assets-folder to the just created empty database in the system folder
private void copyDataBase() throws IOException {
String outFileName = DATABASE_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
InputStream myInput = context.getAssets().open(DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
//Open Database
public void openDatabase() throws SQLException {
String PATH = DATABASE_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(PATH, null, SQLiteDatabase.OPEN_READWRITE);
}
//for insert data into database
public void insertCustomer(String customer_id, String email_id, String password, String description, int balance_amount) {
try {
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("customer_id", customer_id);
contentValues.put("email_id", email_id);
contentValues.put("password", password);
contentValues.put("description", description);
contentValues.put("balance_amount", balance_amount);
db.insert(TABLE_NAME, null, contentValues);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<ModelCreateCustomer> getLoginIdDetail(String email_id, String password) {
ArrayList<ModelCreateCustomer> result = new ArrayList<ModelCreateCustomer>();
//boolean flag = false;
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE email_id='" + email_id + "' AND password='" + password + "'";
try {
openDatabase();
Cursor cursor = myDataBase.rawQuery(selectQuery, null);
//cursor.moveToFirst();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
ModelCreateCustomer model = new ModelCreateCustomer();
model.setId(cursor.getInt(cursor.getColumnIndex("id")));
model.setCustomerId(cursor.getString(cursor.getColumnIndex("customer_id")));
model.setCustomerEmailId(cursor.getString(cursor.getColumnIndex("email_id")));
model.setCustomerPassword(cursor.getString(cursor.getColumnIndex("password")));
model.setCustomerDesription(cursor.getString(cursor.getColumnIndex("description")));
model.setCustomerBalanceAmount(cursor.getInt(cursor.getColumnIndex("balance_amount")));
result.add(model);
}
while (cursor.moveToNext());
}
Toast.makeText(context, "Login Successfully", Toast.LENGTH_SHORT).show();
}
// Log.e("Count", "" + cursor.getCount());
cursor.close();
myDataBase.close();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public void updateCustomer(String id, String email_id, String description, int balance_amount) {
try {
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("email_id", email_id);
contentValues.put("description", description);
contentValues.put("balance_amount", balance_amount);
db.update(TABLE_NAME, contentValues, "id=" + id, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Customer.class
public class Customer extends AppCompatActivity{
private DatabaseMyHandler mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer);
mydb = new DatabaseMyHandler(CreateCustomerActivity.this);
mydb.insertCustomer("1", "[email protected]", "123", "test", 100);
}
}
My understanding is that C++ allows static const members to be defined inside a class so long as it's an integer type.
You are sort of correct. You are allowed to initialize static const integrals in the class declaration but that is not a definition.
Interestingly, if I comment out the call to std::min, the code compiles and links just fine (even though test::N is also referenced on the previous line).
Any idea as to what's going on?
std::min takes its parameters by const reference. If it took them by value you'd not have this problem but since you need a reference you also need a definition.
Here's chapter/verse:
9.4.2/4 - If a static
data member is of const
integral or const
enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
See Chu's answer for a possible workaround.
Below are all what you want:
CTRL + M + M
CTRL + M + H
CTRL + M + O
CTRL + M + A
CTRL + M + X
CTRL + M + L
SELECT
obj.name AS FK_NAME,
sch.name AS [schema_name],
tab1.name AS [table],
col1.name AS [column],
tab2.name AS [referenced_table],
col2.name AS [referenced_column]
FROM
sys.foreign_key_columns fkc
INNER JOIN sys.objects obj
ON obj.object_id = fkc.constraint_object_id
INNER JOIN sys.tables tab1
ON tab1.object_id = fkc.parent_object_id
INNER JOIN sys.schemas sch
ON tab1.schema_id = sch.schema_id
INNER JOIN sys.columns col1
ON col1.column_id = parent_column_id AND col1.object_id = tab1.object_id
INNER JOIN sys.tables tab2
ON tab2.object_id = fkc.referenced_object_id
INNER JOIN sys.columns col2
ON col2.column_id = referenced_column_id
AND col2.object_id = tab2.object_id;
Just use axes.get_ylim()
, it is very similar to set_ylim
. From the docs:
get_ylim()
Get the y-axis range [bottom, top]
Refering to the very first question, I am looking into the same. The result I get, recording a macro, is, starting by selecting cell A76:
Sub find_last_row()
Range("A76").Select
Range(Selection, Selection.End(xlDown)).Select
End Sub
If it's a new project, I'd just drop the database, and create a new one with a proper charset:
CREATE DATABASE <dbname> CHARACTER SET utf8;
This might help a PHP developer out. The below functions will strip white space, remove comments, and concatenate of all your CSS files. Then insert it into a <style>
tag in the head before page load.
The function below will strip comments and minify the passed in css. It is paired in conjunction with the next function.
<?php
function minifyCSS($string)
{
// Minify CSS and strip comments
# Strips Comments
$string = preg_replace('!/\*.*?\*/!s','', $string);
$string = preg_replace('/\n\s*\n/',"\n", $string);
# Minifies
$string = preg_replace('/[\n\r \t]/',' ', $string);
$string = preg_replace('/ +/',' ', $string);
$string = preg_replace('/ ?([,:;{}]) ?/','$1',$string);
# Remove semicolon
$string = preg_replace('/;}/','}',$string);
# Return Minified CSS
return $string;
}
?>
You will call this function in the head of your document.
<?php
function concatenateCSS($cssFiles)
{
// Load all relevant css files
# concatenate all relevant css files
$css = '';
foreach ($cssFiles as $cssFile)
{
$css = $css . file_get_contents("$cssFile.css");
}
# minify all css
$css = minifyCSS($css);
echo "<style>$css</style>";
}
?>
Include the function concatenateCSS()
in your document head. Pass in an array with the names of your stylesheets with its path IE: css/styles.css
. You are not required to add the extension .css
as it is added automatically in the function above.
<head>
<title></title>
<?php
$stylesheets = array(
"bootstrap/css/bootstrap.min",
"css/owl-carousel.min",
"css/style"
);
concatenateCSS( $stylesheets );
?>
</head>
Presuming the autoincrement column in customer_data
is named Id
, you can do:
SELECT CONCAT(title,' ',forename,' ',surname) AS name *
FROM customer c
INNER JOIN customer_data d
ON c.customer_id=d.customer_id
WHERE name LIKE '%Smith%'
AND d.ID = (
Select Max(D2.Id)
From customer_data As D2
Where D2.customer_id = D.customer_id
)
LIMIT 10, 20
that scp command must be issued on the local command-line, for putty the command is pscp.
C:\something> pscp [email protected]:/dir/of/file.txt \local\dir\
Functionality is supposed to be broken in jQuery 1.5.
Since jQuery 1.5.1 you should use xhrFields param.
$.ajaxSetup({
type: "POST",
data: {},
dataType: 'json',
xhrFields: {
withCredentials: true
},
crossDomain: true
});
Docs: http://api.jquery.com/jQuery.ajax/
Reported bug: http://bugs.jquery.com/ticket/8146
JSX will evaluate JavaScript expressions in curly braces
In this case, this.props.removeTaskFunction(todo)
is invoked and the return value is assigned to onClick
What you have to provide for onClick
is a function. To do this, you can wrap the value in an anonymous function.
export const samepleComponent = ({todoTasks, removeTaskFunction}) => {
const taskNodes = todoTasks.map(todo => (
<div>
{todo.task}
<button type="submit" onClick={() => removeTaskFunction(todo)}>Submit</button>
</div>
);
return (
<div className="todo-task-list">
{taskNodes}
</div>
);
}
});
The answer to this question lies in how C# Controls work
Controls in Windows Forms are bound to a specific thread and are not thread safe. Therefore, if you are calling a control's method from a different thread, you must use one of the control's invoke methods to marshal the call to the proper thread. This property can be used to determine if you must call an invoke method, which can be useful if you do not know what thread owns a control.
Effectively, what Invoke does is ensure that the code you are calling occurs on the thread that the control "lives on" effectively preventing cross threaded exceptions.
From a historical perspective, in .Net 1.1, this was actually allowed. What it meant is that you could try and execute code on the "GUI" thread from any background thread and this would mostly work. Sometimes it would just cause your app to exit because you were effectively interrupting the GUI thread while it was doing something else. This is the Cross Threaded Exception - imagine trying to update a TextBox while the GUI is painting something else.
Effectively, you are interrupting a queue, which can have lots of unforeseen consequences. Invoke is effectively the "polite" way of getting what you want to do into that queue, and this rule was enforced from .Net 2.0 onward via a thrown InvalidOperationException.
To understand what is actually going on behind the scenes, and what is meant by "GUI Thread", it's useful to understand what a Message Pump or Message Loop is.
This is actually already answered in the question "What is a Message Pump" and is recommended reading for understanding the actual mechanism that you are tying into when interacting with controls.
Other reading you may find useful includes:
One of the cardinal rules of Windows GUI programming is that only the thread that created a control can access and/or modify its contents (except for a few documented exceptions). Try doing it from any other thread and you'll get unpredictable behavior ranging from deadlock, to exceptions to a half updated UI. The right way then to update a control from another thread is to post an appropriate message to the application message queue. When the message pump gets around to executing that message, the control will get updated, on the same thread that created it (remember, the message pump runs on the main thread).
and, for a more code heavy overview with a representative sample:
Invalid Cross-thread Operations
// the canonical form (C# consumer)
public delegate void ControlStringConsumer(Control control, string text); // defines a delegate type
public void SetText(Control control, string text) {
if (control.InvokeRequired) {
control.Invoke(new ControlStringConsumer(SetText), new object[]{control, text}); // invoking itself
} else {
control.Text=text; // the "functional part", executing only on the main thread
}
}
Once you have an appreciation for InvokeRequired, you may wish to consider using an extension method for wrapping these calls up. This is ably covered in the Stack Overflow question Cleaning Up Code Littered with Invoke Required.
There is also a further write up of what happened historically that may be of interest.
is so easy You can use [phpy - library for php][1] php file
<?php
require_once "vendor/autoload.php";
use app\core\App;
$app = new App();
$python = $app->python;
$output = $python->set(your python path)->send(data..)->gen();
var_dump($ouput);
python file:
import include.library.phpy as phpy
print(phpy.get_data(number of data , first = 1 , two =2 ...))
you can see also example in github page [1]: https://github.com/Raeen123/phpy
I think you can initialize the variables a value like -1
,
because if the int
type variables is not initialized it can't be used.
When you want to check if it is not the value you want you can check if it is -1
.
This solution is not very different from those above, but for me it works very well and i think it's clean.
I suggest to base64 encode the file server side (base64_encode(), if you are using PHP) and send the base64 encoded data to the client
On the client you do this:
let blob = this.dataURItoBlob(THE_MIME_TYPE + "," + response.file);
let uri = URL.createObjectURL(blob);
let link = document.createElement("a");
link.download = THE_FILE_NAME,
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
This code puts the encoded data in a link and simulates a click on the link, then it removes it.
Using ScrollView
is not very difficult. You can just add one to your layout and put whatever you want to scroll inside. ScrollView
only takes one child so if you want to put a few things inside then you should make the first thing be something like a LinearLayout
.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- things to scroll -->
</LinearLayout>
</ScrollView>
If you want to scroll things horizontally, then use a HorizontalScrollView
.
As is talked about in this post, sometimes you want the ScrollView
content to fill the screen. For example, if you had some buttons at the end of a readme. You want the buttons to always be at the end of the text and at bottom of the screen, even if the text doesn't scroll.
If the content scrolls, everything is fine. However, if the content is smaller than the size of the screen, the buttons are not at the bottom.
This can be solved with a combination of using fillViewPort
on the ScrollView
and using a layout weight on the content. Using fillViewPort
makes the ScrollView
fill the parent area. Setting the layout_weight
on one of the views in the LinearLayout
makes that view expand to fill any extra space.
Here is the XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"> <--- fillViewport
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textview"
android:layout_height="0dp" <---
android:layout_weight="1" <--- set layout_weight
android:layout_width="match_parent"
android:padding="6dp"
android:text="hello"/>
<LinearLayout
android:layout_height="wrap_content" <--- wrap_content
android:layout_width="match_parent"
android:background="@android:drawable/bottom_bar"
android:gravity="center_vertical">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Accept" />
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Refuse" />
</LinearLayout>
</LinearLayout>
</ScrollView>
The idea for this answer came from a previous answer that is now deleted (link for 10K users). The content of this answer is an update and adaptation of this post.
Regarding the error
'CREATE VIEW' must be the first statement in a query batch.
Microsoft SQL Server has a quirky reqirement that CREATE VIEW
be the only statement in a batch. This is also true of a few other statements, such as CREATE FUNCTION
. It is not true of CREATE TABLE
, so go figure …
The solution is to send your script to the server in small batches. One way to do this is to select a single statement and execute it. This is clearly inconvenient.
The more convenient solution is to get the client to send the script in small isolated batches.
The GO
keyword is not strictly an SQL command, which is why you can’t end it with a semicolon like real SQL commands. Instead it is an instruction to the client to break the script at this point and to send the portion as a batch.
As a result, you end up writing something like:
DROP VIEW IF EXISTS … ;
GO
CREATE VIEW … AS … ;
GO
None of the other database servers I have encountered (PostgreSQL, MySQL, Oracle, SQLite) have this quirk, so the requirement appears to be Microsoft Only.
In order to use two-way data binding for form inputs you need to import the FormsModule
package in your Angular module.
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule
]
EDIT
Since there are lot of duplicate questions with the same problem, I am enhancing this answer.
There are two possible reasons
Missing FormsModule
, hence Add this to your Module,
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [
FormsModule
]
Check the syntax/spelling of [(ngModel)]
in the input tag
Well I know this might be a big change or even not suitable for your project, but did you consider not performing the push until you already have the data? That way you only need to draw the view once and the user experience will also be better - the push will move in already loaded.
The way you do this is in the UITableView
didSelectRowAtIndexPath
you asynchronously ask for the data. Once you receive the response, you manually perform the segue and pass the data to your viewController in prepareForSegue
.
Meanwhile you may want to show some activity indicator, for simple loading indicator check https://github.com/jdg/MBProgressHUD
If using XML configuration you can use
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security">
<security:http>
<security:headers>
<security:frame-options disabled="true"></security:frame-options>
</security:headers>
</security:http>
</beans>
That is correct behaviour, it's up to you to create the contents for the 404 page.
The 404 header is used by spiders and download-managers to determine if the file exists.
(A page with a 404 header won't be indexed by google or other search-engines)
Normal users however don't look at http-headers and use the page as a normal page.
If you're using Joda-Time (and there are lots of good reasons to - a simple, intuitive API and thread-safety) then you can do this trivially:
(new LocalDate()).plusDays(5);
to give 5 days from today, for example.
EDIT: My current advice would be to now use the Java 8 date/time api
The definitive solution is to allow the InfoTech protocol to work in the intranet zone.
Add the following value to the registry and the problem should be solved:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\HTMLHelp\1.x\ItssRestrictions]
"MaxAllowedZone"=dword:00000001
More info here: http://support.microsoft.com/kb/896054
Obviously @Ian Ringrose
's central thesis that you should be using a library for this is the best single answer here (hence a +1), but for minimal throwaway or demo code here's a concrete illustration of @SLaks
's subtle comment on @Jon Skeet
's more granular (+1'd) answer:
public List<XXX> Load( <<args>> )
{
using ( var connection = CreateConnection() )
using ( var command = Create<<ListXXX>>Command( <<args>>, connection ) )
{
connection.Open();
using ( var reader = command.ExecuteReader() )
return reader.Cast<IDataRecord>()
.Select( x => new XXX( x.GetString( 0 ), x.GetString( 1 ) ) )
.ToList();
}
}
As in @Jon Skeet
's answer, the
.Select( x => new XXX( x.GetString( 0 ), x.GetString( 1 ) ) )
bit can be extracted into a helper (I like to dump them in the query class):
public static XXX FromDataRecord( this IDataRecord record)
{
return new XXX( record.GetString( 0 ), record.GetString( 1 ) );
}
and used as:
.Select( FromDataRecord )
UPDATE Mar 9 13: See also Some excellent further subtle coding techniques to split out the boilerplate in this answer
This has always been my approach to this little nuisance. Note the use of VirtualPathUtility.ToAbsolute(relativeUrl) allows the method to be declared as an extension in a static class.
/// <summary>
/// Converts the provided app-relative path into an absolute Url containing the
/// full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string ToAbsoluteUrl(this string relativeUrl) {
if (string.IsNullOrEmpty(relativeUrl))
return relativeUrl;
if (HttpContext.Current == null)
return relativeUrl;
if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");
var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}
$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10");
While most answers are a copy of SolutionYogi's answer, they all miss an important check to see if 'cell' is not null which will return an error if clicking on the headers. So, here is the answer with the check included:
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
// check if not null
if(!cell) return; // no errors!
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
The folder is part of the URL you set when you create request
: "ftp://www.contoso.com/test.htm"
. If you use "ftp://www.contoso.com/wibble/test.htm"
then the file will be uploaded to a folder named wibble
.
You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory
to make the wibble
folder if it doesn't already exist.
So bottom line is, is there a way to specify a jdk for a single invocation of maven?
Temporarily change the value of your JAVA_HOME
environment variable.
Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:
__init__
method are static elements; they belong to the class.__init__
method are elements of the object (self
); they don't belong to the class.You'll see it more clearly with some code:
class MyClass:
static_elem = 123
def __init__(self):
self.object_elem = 456
c1 = MyClass()
c2 = MyClass()
# Initial values of both elements
>>> print c1.static_elem, c1.object_elem
123 456
>>> print c2.static_elem, c2.object_elem
123 456
# Nothing new so far ...
# Let's try changing the static element
MyClass.static_elem = 999
>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456
# Now, let's try changing the object element
c1.object_elem = 888
>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456
As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.
export enum UserLevel {
Staff = 0,
Leader,
Manager,
}
export enum Gender {
None = "none",
Male = "male",
Female = "female",
}
Difference result in log:
log(Object.keys(Gender))
=>
[ 'None', 'Male', 'Female' ]
log(Object.keys(UserLevel))
=>
[ '0', '1', '2', 'Staff', 'Leader', 'Manager' ]
The solution, we need to remove key as a number.
export class Util {
static existValueInEnum(type: any, value: any): boolean {
return Object.keys(type).filter(k => isNaN(Number(k))).filter(k => type[k] === value).length > 0;
}
}
Usage
// For string value
if (!Util.existValueInEnum(Gender, "XYZ")) {
//todo
}
//For number value, remember cast to Number using Number(val)
if (!Util.existValueInEnum(UserLevel, 0)) {
//todo
}
You don't. The C++ standard has no concept of directories. It is up to the implementation to turn a string into a file handle. The contents of that string and what it maps to is OS dependent. Keep in mind that C++ can be used to write that OS, so it gets used at a level where asking how to iterate through a directory is not yet defined (because you are writing the directory management code).
Look at your OS API documentation for how to do this. If you need to be portable, you will have to have a bunch of #ifdefs for various OSes.
Process text to and from Unicode at the I/O boundaries of your program using open
with the encoding
parameter. Make sure to use the (hopefully documented) encoding of the file being read. The default encoding varies by OS (specifically, locale.getpreferredencoding(False)
is the encoding used), so I recommend always explicitly using the encoding
parameter for portability and clarity (Python 3 syntax below):
with open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with open(filename, 'w', encoding='utf8') as f:
f.write(text)
If still using Python 2 or for Python 2/3 compatibility, the io
module implements open
with the same semantics as Python 3's open
and exists in both versions:
import io
with io.open(filename, 'r', encoding='utf8') as f:
text = f.read()
# process Unicode text
with io.open(filename, 'w', encoding='utf8') as f:
f.write(text)
A double quote to the left of the text you want to comment.
Example:
" this is how a comment looks like in ~/.vimrc
just to update this, bootstrap v2 no longer conflicts with jquery ui
https://github.com/twbs/bootstrap/issues/171
Edit: as @Freshblood there are a few things that still conflict. However, as originally posted Twitter suggests that they are working on this and it largely works, specially compared to v1.
Use float-right
for block elements, or text-right
for inline elements:
<div class="row">
<div class="col">left</div>
<div class="col text-right">inline content needs to be right aligned</div>
</div>
<div class="row">
<div class="col">left</div>
<div class="col">
<div class="float-right">element needs to be right aligned</div>
</div>
</div>
http://www.codeply.com/go/oPTBdCw1JV
If float-right
is not working, remember that Bootstrap 4 is now flexbox, and many elements are display:flex
which can prevent float-right
from working.
In some cases, the utility classes like align-self-end
or ml-auto
work to right align elements that are inside a flexbox container like the Bootstrap 4 .row, Card or Nav. The ml-auto
(margin-left:auto) is used in a flexbox element to push elements to the right.
git pull origin master
will pull changes from the origin
remote, master
branch and merge them to the local checked-out branch.
git pull origin/master
will pull changes from the locally stored branch origin/master
and merge that to the local checked-out branch. The origin/master
branch is essentially a "cached copy" of what was last pulled from origin
, which is why it's called a remote branch in git parlance. This might be somewhat confusing.
You can see what branches are available with git branch
and git branch -r
to see the "remote branches".
You probably want to use the assets_base_urls
configuration.
framework:
templating:
assets_base_urls:
http: [http://www.website.com]
ssl: [https://www.website.com]
http://symfony.com/doc/current/reference/configuration/framework.html#assets
Note that the configuration is different since Symfony 2.7:
framework:
# ...
assets:
base_urls:
- 'http://cdn.example.com/'
Update
As of SDK rev 21 the Android Virtual Device Manager has an improved UI which resolves this issue. I have highlighted some of the more important configuration settings below:
If you notice that the soft (screen-based) main keys Back
, Home
, etc. are missing from your emulator you can set hw.mainKeys=no
to enable them.
Original answer
Even though the developer documentation says keyboard support is enabled by default it doesn't seem to be that way in SDK rev 20. I explicitly enabled keyboard support in my emulator's config.ini file and that worked!
Add: hw.keyboard=yes
To: ~/.android/avd/<emulator-device-name>.avd/config.ini
Similarly, add hw.dPad=yes
if you wish to use the arrow-keys to navigate the application list.
Reference: http://developer.android.com/tools/devices/managing-avds-cmdline.html#hardwareopts
On Mac OS and Linux you can edit all of your emulator configurations with one Terminal command:
for f in ~/.android/avd/*.avd/config.ini; do echo 'hw.keyboard=yes' >> "$f"; done
On a related note, if your tablet emulator is missing the BACK/HOME buttons, try selecting WXGA800 as the Built-in skin in the AVD editor:
Or by manually setting the skin in config.ini:
skin.name=WXGA800
skin.path=platforms/android-16/skins/WXGA800
(example is for API 16)
Child Component
Use this.$emit('event_name')
to send an event to the parent component.
Parent Component
In order to listen to that event in the parent component, we do v-on:event_name
and a method (ex. handleChange
) that we want to execute on that event occurs
Done :)
As mentioned by others here, that you could have two adb's running ... And to add to these answers from a Linux box perspective ( for the next newbie who is working from Linux );
Uninstall your distro's android-tools ( use zypper or yum etc )
# zypper -v rm android-tools
Find where your other adb is
# find /home -iname "*adb"|grep -i android
Say it was at ;
/home/developer/Android/Sdk/platform-tools/adb
Then Make a softlink to it in the /usr/bin folder
ln -s /home/developer/Android/Sdk/platform-tools/adb /usr/bin/adb
Then;
# adb start-server
Better late than never :)
I just came across this iSimulate which allows you to send Fake location to the app. The solution is NOT free.
> Q: How does iSimulate work?
> A: When added to your project, the iSimulate
> SDK library creates a listening server
> on your iPhone Simulator that waits
> for a connection from an iPhone/iPod
> running the iSimulate client. When
> such connection is established, the
> iSimulate client running on your
> iPhone/iPod captures all data from the
> accelerometer sensor, the touch
> events, the location and device ID and
> streams them to the server. The
> iSimulate SDK library then recreates
> all input events synthetically. This
> is entirely transparent to your
> application and does not interfere
> with your application's functionality.
Anyway, i am planning to get this. will update more soon!
A solution that works with IIS7 and upwards: Display custom error page when file upload exceeds allowed size in ASP.NET MVC
I was having two .sh scripts to start and stop the digital ocean servers that I wanted to run from the Windows 10. What I did is:
Now to run the script each time I just double-click the script
import chai from 'chai';
const arr1 = [2, 1];
const arr2 = [2, 1];
chai.expect(arr1).to.eql(arr2); // Will pass. `eql` is data compare instead of object compare.
How about using mysql to generate the uuid for you?
$conn = new mysqli($servername, $username, $password, $dbname, $port);
$query = 'SELECT UUID()';
echo $conn->query($query)->fetch_row()[0];
For a search routine you should look to use Find
, AutoFilter
or variant array approaches. Range loops are nomally too slow, worse again if they use Select
The code below will look for the strText variable in a user selected range, it then adds any matches to a range variable rng2
which you can then further process
Option Explicit
Const strText As String = "%"
Sub ColSearch_DelRows()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim cel1 As Range
Dim cel2 As Range
Dim strFirstAddress As String
Dim lAppCalc As Long
'Get working range from user
On Error Resume Next
Set rng1 = Application.InputBox("Please select range to search for " & strText, "User range selection", Selection.Address(0, 0), , , , , 8)
On Error GoTo 0
If rng1 Is Nothing Then Exit Sub
With Application
lAppCalc = .Calculation
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Set cel1 = rng1.Find(strText, , xlValues, xlPart, xlByRows, , False)
'A range variable - rng2 - is used to store the range of cells that contain the string being searched for
If Not cel1 Is Nothing Then
Set rng2 = cel1
strFirstAddress = cel1.Address
Do
Set cel1 = rng1.FindNext(cel1)
Set rng2 = Union(rng2, cel1)
Loop While strFirstAddress <> cel1.Address
End If
If Not rng2 Is Nothing Then
For Each cel2 In rng2
Debug.Print cel2.Address & " contained " & strText
Next
Else
MsgBox "No " & strText
End If
With Application
.ScreenUpdating = True
.Calculation = lAppCalc
End With
End Sub
Perhaps the following, then your calculator can use arbitrary number base (e.g. hex, binary, base 7! etc): (untested)
def convert(str):
try:
base = 10 # default
if ':' in str:
sstr = str.split(':')
base, str = int(sstr[0]), sstr[1]
val = int(str, base)
except ValueError:
val = None
return val
val = convert(raw_input("Enter value:"))
# 10 : Decimal
# 16:a : Hex, 10
# 2:1010 : Binary, 10
According to RFC 2616 (HTTP/1.1) 403 is sent when:
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead
In other words, if the client CAN get access to the resource by authenticating, 401 should be sent.
You first have to 'dot' source the script, so for you :
. .\Get-NetworkStatistics.ps1
The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted
or set-ExecutionPolicy AllSigned
see(the Execution Policy instructions).
You can do with create new one like this.
var list1 = ArrayList<Int>()
var list2 = list1.toMutableList()
list2.add(item)
Now you can use list2, Thank you.
Something quick and dirty:
<script type='text/javascript'>
function del_tr(remtr)
{
while((remtr.nodeName.toLowerCase())!='tr')
remtr = remtr.parentNode;
remtr.parentNode.removeChild(remtr);
}
function del_id(id)
{
del_tr(document.getElementById(id));
}
</script>
if you place
<a href='' onclick='del_tr(this);return false;'>x</a>
anywhere within the row you want to delete, than its even working without any ids
Consider using System.Windows.Forms.Timer
instead of System.Threading.Timer
for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.
In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.
As of php 5.4 you can use
$dbt=debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,2);
$caller = isset($dbt[1]['function']) ? $dbt[1]['function'] : null;
This will not waste memory as it ignores arguments and returns only the last 2 backtrace stack entries, and will not generate notices as other answers here.
Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.
You can also run your batch script through a vbs script like this:
'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True
This will execute your batch file with no cmd window shown.
When you echo $array;
, the result is Array
, result[0]
then represents the first character in Array
which is A
.
One way to handle this problem would be like this:
ajax.php
<?php
$array = array(1,2,3,4,5,6);
foreach($array as $a)
echo $a.",";
?>
jquery code
$(function(){ /* short for $(document).ready(function(){ */
$('#prev').click(function(){
$.ajax({type: 'POST',
url: 'ajax.php',
data: 'id=testdata',
cache: false,
success: function(data){
var tmp = data.split(",");
$('#content1').html(tmp[0]);
}
});
});
});
I don't know if this is still the recommended thing to use but the "Object Linking and Embedding" framework allows you to embed certain objects/controls directly into your application. This will probably only work for certain applications, I'm not sure if Notepad is one of them. For really simple things like notepad, you'll probably have an easier time just working with the text box controls provided by whatever medium you're using (e.g. WinForms).
Here's a link to OLE info to get started:
If you want to disable particular date(s) in jquery datepicker then here is the simple demo for you.
<script type="text/javascript">
var arrDisabledDates = {};
arrDisabledDates[new Date("08/28/2017")] = new Date("08/28/2017");
arrDisabledDates[new Date("12/23/2017")] = new Date("12/23/2017");
$(".datepicker").datepicker({
dateFormat: "dd/mm/yy",
beforeShowDay: function (date) {
var day = date.getDay(),
bDisable = arrDisabledDates[date];
if (bDisable)
return [false, "", ""]
}
});
</script>
I go for Avi Pinto's solution which uses jquery.data()
Using focus isn't a valid solution. It works at first time you change the options, but if you stay on that select element, and press key "up" or "down". It won't go through the focus event again.
So the solution should be more looks like the following,
//set the pre data, usually needed after you initialize the select element
$('mySelect').data('pre', $(this).val());
$('mySelect').change(function(e){
var before_change = $(this).data('pre');//get the pre data
//Do your work here
$(this).data('pre', $(this).val());//update the pre data
})
You have to define your TASK_CAT
column first and then set foreign key on it.
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " ("
+ TASK_ID + " integer primary key autoincrement, "
+ TASK_TITLE + " text not null, "
+ TASK_NOTES + " text not null, "
+ TASK_DATE_TIME + " text not null,"
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";
More information you can find on sqlite foreign keys doc.
I tried very hard with System.ComponentModel.TypeDescriptor without success. That does not means it can't work but I would like to see code for that.
In counter part, I wanted to change some Attribute values. I did 2 functions which work fine for that purpose.
// ************************************************************************
public static void SetObjectPropertyDescription(this Type typeOfObject, string propertyName, string description)
{
PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];
var att = pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
if (att != null)
{
var fieldDescription = att.GetType().GetField("description", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldDescription != null)
{
fieldDescription.SetValue(att, description);
}
}
}
// ************************************************************************
public static void SetPropertyAttributReadOnly(this Type typeOfObject, string propertyName, bool isReadOnly)
{
PropertyDescriptor pd = TypeDescriptor.GetProperties(typeOfObject)[propertyName];
var att = pd.Attributes[typeof(ReadOnlyAttribute)] as ReadOnlyAttribute;
if (att != null)
{
var fieldDescription = att.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
if (fieldDescription != null)
{
fieldDescription.SetValue(att, isReadOnly);
}
}
}
Starting from Windows Vista, a service cannot interact with the desktop. You will not be able to see any windows or console windows that are started from a service. See this MSDN forum thread.
On other OS, there is an option that is available in the service option called "Allow Service to interact with desktop". Technically, you should program for the future and should follow the Vista guideline even if you don't use it on Vista.
If you still want to run an application that never interact with the desktop, try specifying the process to not use the shell.
ProcessStartInfo info = new ProcessStartInfo(@"c:\myprogram.exe");
info.UseShellExecute = false;
info.RedirectStandardError = true;
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.CreateNoWindow = true;
info.ErrorDialog = false;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(info);
See if this does the trick.
First you inform Windows that the program won't use the shell (which is inaccessible in Vista to service).
Secondly, you redirect all consoles interaction to internal stream (see process.StandardInput
and process.StandardOutput
.
This allows to send text message through existing app. phoneNumber - is String. If you do not wish to specify phone number, use empty string "".
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", phoneNumber, null));
sendIntent.putExtra("sms_body", "text message");
startActivity(sendIntent);
Set the display.max_colwidth
option to None
(or -1
before version 1.0):
pd.set_option('display.max_colwidth', None)
For example, in iPython, we see that the information is truncated to 50 characters. Anything in excess is ellipsized:
If you set the display.max_colwidth
option, the information will be displayed fully:
Here is an updated version using lodash 4 and ES6
const result = _.chain(data)
.groupBy("color")
.toPairs()
.map(pair => _.zipObject(['color', 'users'], pair))
.value();
Answer below the dotted line below is the original that's now outdated.
Here is the latest information ( Thank you @deadfish ):
add &hl=<language>
like &hl=pl
or &hl=en
example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl
All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en
......................................................................
To change the actual local market:
Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html
To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720
In Visual Studio click on one of the fields -> click the light bulb -> Generate Constructors -> Select the fields
The above solutions didn't work for me. Here is what I finally came up with:
$( "#ddl" ).find( "option:selected" ).text(); // Text
$( "#ddl" ).find( "option:selected" ).prop("value"); // Value
To compliment the current accepted answer, if you assume that MAMP uses the most recent version of php5 as the default, you can add grep 'php5' in the middle:
PHP_VERSION= `ls /Applications/MAMP/bin/php/ | sort -n | grep 'php5' | tail -1`
and you are guaranteed to get the most recent php5 regardless of MAMP version.
dict.update()
looks like it will do what you want...
>> orig.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}
>>>
Perhaps, though, you don't want to update your original dictionary, but work on a copy:
>>> dest = orig.copy()
>>> dest.update(extra)
>>> orig
{'A': 1, 'C': 3, 'B': 2}
>>> dest
{'A': 1, 'C': 3, 'B': 2, 'E': 5, 'D': 4}
public int this[int index]
{
get => values[index];
}
You can use
git reset
to undo the recently added local files
git reset file_name
to undo the changes for a specific file
moment(d).isAfter(ahead30now); // true
http://momentjs.com/docs/#/query/is-after/
if (moment(d).isAfter(ahead30now)) {
// allow input time
console.log('UTC TIME DB', d.format());
} else {
}
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
Modify the_script.php like this.
<script>
the_function() {
alert("You win");
}
</script>
After trying gpdf as nullglob suggested, I found that I got the same compression results (a ~900mb file down to ~30mb) by just using the cups-pdf printer. This might be easier/preferred if you are already viewing a document and only need to compress one or two documents.
In Ubuntu 12.04, you can install this by
sudo apt-get install cups-pdf
After installation, be sure to check in System Tools > Administration > Printing > right-click 'PDF' and set it to 'enable'
By default, the output is saved into a folder named PDF in your home directory.
Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.
is
tells you if the object implements ClassA
anywhere in its type heirarchy. GetType()
tells you about the most-derived type.
Not the same thing.
I know this is an old question, but if you encounter this problem in MVC 3 then you can decorate your ActionMethod
with [ValidateInput(false)]
and just switch off request validation for a single ActionMethod
, which is handy. And you don't need to make any changes to the web.config
file, so you can still use the .NET 4 request validation everywhere else.
e.g.
[ValidateInput(false)]
public ActionMethod Edit(int id, string value)
{
// Do your own checking of value since it could contain XSS stuff!
return View();
}
i even tryed to avoid this, just in case doing the Abort on the thread manually, but i rather leave it with the "CompleteRequest" and move on - my code has return commands after redirects anyway. So this can be done
public static void Redirect(string VPathRedirect, global::System.Web.UI.Page Sender)
{
Sender.Response.Redirect(VPathRedirect, false);
global::System.Web.UI.HttpContext.Current.ApplicationInstance.CompleteRequest();
}
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
It is important to run your mongod command and keep the server running. If not, you will still be seeing this error.
I attach you my code:
const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient
const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'
MongoClient.connect(connectionURL, {useNewUrlParser: true, useUnifiedTopology: true}, (error, client) => {
if(error) {
return console.log('Error connecting to the server.')
}
console.log('Succesfully connected.')
})
_x000D_
Set the display property to none
as the default, then use a media query to apply the desired styles to the div when the browser reaches a certain width. Replace 768px
in the media query with whatever the minimum px value is where your div should be visible.
#title_message {
display: none;
}
@media screen and (min-width: 768px) {
#title_message {
clear: both;
display: block;
float: left;
margin: 10px auto 5px 20px;
width: 28%;
}
}
Add this line to your method, If you are using a API.
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
After a while of research and disappointments....I was able to make this up
<?php $conn = new mysqli('hostname', 'username', 'password','dbname') or die ('Cannot connect to db') $result = $conn->query("select * from table");?>
//insert the below code in the body
<table id="myTable"> <tr class="header"> <th style="width:20%;">Name</th>
<th style="width:20%;">Email</th>
<th style="width:10%;">City/ Region</th>
<th style="width:30%;">Details</th>
</tr>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['city']."</td>";
echo "<td>".$row['details']."</td>";
echo "</tr>";
}
?>
</table>
Trust me it works :)
See:
Code:
var strDate = "03.09.1979";
var dateParts = strDate.split(".");
var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
I don't know is this what you're looking for
List keys = new ArrayList(map.keySet());
int index = keys.indexOf(element);
Canonical Data in RDBMS, Graph Data;
Think as "Normalization" or "Normal form" of a data in a RDBMS. Same data exists in different tables, represented with a unique identifier and mapped it in different tables.
or
Think a single form of a data in Graph Database that represented in many triples.
Major benefit of it is to make Dml (Data manipulation) more efficient since you can upsert (insert/update) only one value instead of many.
When I want to develop insensitive case searchs, I always convert every string to lower case before do comparasion
public DataSet GetDataSet(string ConnectionString, string SQL)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
///conn.Open();
da.Fill(ds);
///conn.Close();
return ds;
}
yes this bug is there. However, I found a small workaround.
That should solve it. Assuming we want to create the user admin @ localhost, these would be the commands:
drop user admin@localhost; flush privileges; create user admin@localhost identified by 'admins_password'
Cheers
There is a symbol before help menu on xcode which has Edit user script. On Un/Comment Selection under comments section change my $cCmt = "//"; to my $cCmt = "#"; or whatever your IDE works with. Then by selecting lines and command + / (It's my xcode default) you can comment and uncomment the selected lines.
If you are sitting at the merge commit then this shows the diffs:
git diff HEAD~1..HEAD
If you're not at the merge commit then just replace HEAD with the merge commit. This method seems like the simplest and most intuitive.
def isPrime(x):
if x<2:
return False
for i in range(2,x):
if not x%i:
return False
return True
print isPrime(2)
True
print isPrime(3)
True
print isPrime(9)
False
Most answers are fairly old, so it might have not been possible back then, but there actually is a solution that satisfies all the possible use-cases.
So right know the answers are:
@Value
you have to have the value in a configuration file somewhere)The solution to solve those issues is to create the object manually using the ApplicationContext
:
@Component
public class MyConstructorClass
{
String var;
public MyConstructorClass() {}
public MyConstructorClass(String constrArg) {
this.var = var;
}
}
@Service
public class MyBeanService implements ApplicationContextAware
{
private static ApplicationContext applicationContext;
MyConstructorClass myConstructorClass;
public MyBeanService()
{
// Creating the object manually
MyConstructorClass myObject = new MyConstructorClass("hello world");
// Initializing the object as a Spring component
AutowireCapableBeanFactory factory = applicationContext.getAutowireCapableBeanFactory();
factory.autowireBean(myObject);
factory.initializeBean(myObject, myObject.getClass().getSimpleName());
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
}
This is a cool solution because:
@Autowired
obviously, but also @Async
for example),The only thing to keep in mind is that you have to have a constructor that takes no arguments (and that can be empty) in the class you want to instantiate (or an @Autowired
constructor if you need it).
Should it not be foreach
instead of for!?
//call SQL helper class to get initial data
DataTable dt = sql.ExecuteDataTable("sp_MyProc");
dt.Columns.Add("MyRow", **typeof**(System.Int32));
foreach(DataRow dr in dt.Rows)
{
//need to set value to MyRow column
dr["MyRow"] = 0; // or set it to some other value
}
You can use the built-in forEach
function for arrays.
Like this:
//this sets all product descriptions to a max length of 10 characters
data.products.forEach( (element) => {
element.product_desc = element.product_desc.substring(0,10);
});
Your version wasn't wrong though. It should look more like this:
for(let i=0; i<data.products.length; i++){
console.log(data.products[i].product_desc); //use i instead of 0
}
Using itertools.count
:
import itertools
for i in itertools.count(start=1):
if there_is_a_reason_to_break(i):
break
In Python 2, range()
and xrange()
were limited to sys.maxsize
. In Python 3 range()
can go much higher, though not to infinity:
import sys
for i in range(sys.maxsize**10): # you could go even higher if you really want
if there_is_a_reason_to_break(i):
break
So it's probably best to use count()
.
jQuery BBQ (Back Button & Query Library)
A high quality hash-based browser history plugin and very much up-to-date (Jan 26, 2010) as of this writing (jQuery 1.4.1).
objArray.sort((a, b) => a.DepartmentName.localeCompare(b.DepartmentName))
To get the Unix timestamp in seconds in MySQL:
select UNIX_TIMESTAMP();
Details: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp
Not tested PostgreSQL, but according to this site it should work: http://www.raditha.com/postgres/timestamp.php
select round( date_part( 'epoch', now() ) );
Razz's solution would work for the .hide()
and .show()
methods but would not work for the .toggle()
method.
Depending upon the scenario, having a css class .inline_block { display: inline-block; }
and calling $(element).toggleClass('inline_block')
solves the problem for me.
A better solution for "today" is:
SELECT * FROM jokes WHERE DATE(date) = DATE(NOW())
You can set the path variable for easily by command prompt.
Open run and write cmd
In the command window write the following: set path=%path%;C:\python36
If you just call exit in Bash without any parameters, it will return the exit code of the last command. Combined with OR
, Bash should only invoke exit, if the previous command fails. But I haven't tested this.
command1 || exit; command2 || exit;
Bash will also store the exit code of the last command in the variable $?
.
A case statement actually might not be the right approach here. If this is a factor, which is likely is, just set the levels of the factor appropriately.
Say you have a factor with the letters A to E, like this.
> a <- factor(rep(LETTERS[1:5],2))
> a
[1] A B C D E A B C D E
Levels: A B C D E
To join levels B and C and name it BC, just change the names of those levels to BC.
> levels(a) <- c("A","BC","BC","D","E")
> a
[1] A BC BC D E A BC BC D E
Levels: A BC D E
The result is as desired.
I suggest to use Google Guava Throwables class
propagate(Throwable throwable)
Propagates throwable as-is if it is an instance of RuntimeException or Error, or else as a last resort, wraps it in a RuntimeException and then propagates.**
void bar() {
Stream<A> as = ...
as.forEach(a -> {
try {
a.foo()
} catch(Exception e) {
throw Throwables.propagate(e);
}
});
}
UPDATE:
Now that it is deprecated use:
void bar() {
Stream<A> as = ...
as.forEach(a -> {
try {
a.foo()
} catch(Exception e) {
Throwables.throwIfUnchecked(e);
throw new RuntimeException(e);
}
});
}
First go to android studio folder on location that you installed it ( It’s usually in this path by default ; C:\Program Files\Android\Android Studio, unless you change it when you install Android Studio). Find and run uninstall.exe file.
Wait until uninstallation complete successfully, just few minutes, and after click the close.
To delete any remains of Android Studio setting files, in File Explorer, go to C:\Users\%username%, and delete .android, .AndroidStudio(#version-number)
and also .gradle, AndroidStudioProjects
if they exist. If you want remain your projects, you’d like to keep AndroidStudioProjects
folder.
Then, go to C:\Users\%username%\AppData\Roaming
and delete the JetBrains directory.
Note that AppData folder is hidden by default, to make visible it go to view tab and check hidden items in windows8 and10 ( in windows7 Select Folder Options, then select the View tab. Under Advanced settings, select Show hidden files, folders, and drives, and then select OK.
Done, you can remove Android Studio successfully, if you plan to delete SDK tools too, it is enough to remove SDK folder completely.
Do this:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/check" <!--check.xml-->
android:layout_margin="10dp"
android:textOn=""
android:textOff=""
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_centerVertical="true"/>
create check.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
One simple line in base R:
df$count = table(interaction(df[, (c("name", "type"))]))[interaction(df[, (c("name", "type"))])]
Same in two lines, for clarity/efficiency:
fact = interaction(df[, (c("name", "type"))])
df$count = table(fact)[fact]
I am using BS 3.3.7 and i have a problem when i open a modal then close it, the modal contents keep on the client side no html("") no clear at all. So i used this to remove completely the code inside the modal div. Well, you may ask why the padding-right code, in chrome for windows when open a modal from another modal and close this second modal the stays with a 17px padding right. Hope it helps...
$(document)
.on('shown.bs.modal', '.modal', function () {
$(document.body).addClass('modal-open')
})
.on('hidden.bs.modal', '.modal', function () {
$(document.body).removeClass('modal-open')
$(document.body).css("padding-right", "0px");
$(this).removeData('bs.modal').find(".modal-dialog").empty();
})
In computer networking, localhost (meaning "this computer") is the standard hostname given to the address of the loopback network interface.
Localhost always translates to the loopback IP address 127.0.0.1 in IPv4.
It is also used instead of the hostname of a computer. For example, directing a web browser installed on a system running an HTTP server to http://localhost will display the home page of the local web site.
Source: Wikipedia - Localhost.
The :80
part is the TCP port. You can consider these ports as communications endpoints on a particular IP address (in the case of localhost - 127.0.0.1). The IANA is responsible for maintaining the official assignments of standard port numbers for specific services. Port 80 happens to be the standard port for HTTP.
Queue is an Interface not a class.
try pcregrep
instead of regular grep
:
pcregrep -M "pattern1.*\n.*pattern2" filename
the -M
option allows it to match across multiple lines, so you can search for newlines as \n
.
td
cellThe answers provided do a great job to right-align text in a td
cell.
This might not be the solution when you're looking to align a block element as commented in the accepted answer. To achieve such with a block element, I have found it useful to make use of margins;
selector {
margin: top right bottom left;
}
td {
/* there is a shorthand, TODO! */
margin: auto 0 auto auto;
}
td {
margin: auto auto auto auto;
}
/* or the short-hand */
margin: auto;
td {
margin: auto;
}
Alternatively, you could make you td
content display inline-block
if that's an option, but that may distort the position of its child elements.
This is a very basic procedure, I got this after putting a general procedure on paper.
import java.util.Scanner;
public class DecimalToBinary {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a Number:");
int number = input.nextInt();
while(number!=0)
{
if(number%2==0)
{
number/=2;
System.out.print(0);//Example: 10/2 = 5 -> 0
}
else if(number%2==1)
{
number/=2;
System.out.print(1);// 5/2 = 2 -> 1
}
else if(number==2)
{
number/=2;
System.out.print(01);// 2/2 = 0 -> 01 ->0101
}
}
}
}
This is how I made it without extra css or jquery:
<div class="form-group">
<div class="input-group">
<label class="sr-only" for="extra3">Extra name 3</label>
<input type="text" id="extra3" class="form-control" placeholder="Extra name">
<span class="input-group-addon">
<label class="checkbox-inline">
Mandatory? <input type="checkbox" id="inlineCheckbox5" value="option1">
</label>
</span>
<span class="input-group-addon">
<label class="checkbox-inline">
Per person? <input type="checkbox" id="inlineCheckbox6" value="option2">
</label>
</span>
<span class="input-group-addon">
To be paid?
<select>
<option value="online">Online</option>
<option value="on spot">On Spot</option>
</select>
</span>
</div>
</div>
As already answered here (and here and here), mergetool is the command to configure this. For a nice graphical frontend I recommend kdiff3 (GPL).
All u need do is to change the lowercase 'hh' in the pattern to an uppercase letter 'HH'
for Kotlin:
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") val currentDate = sdf.format(Date())
for java:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss") Date currentDate = sdf.format(new Date())
Swift 4
let data = myStringVariable.data(using: String.Encoding.utf8.rawValue)
You need to set line-height.
<div style="border: 1px solid red;">
<span style="font-size: 38px; vertical-align:middle; float:left; line-height: 38px">Hejsan</span>
<span style="font-size: 13px; vertical-align:middle; float:right; line-height: 38px">svejsan</span>
<div style="clear: both;"></div>
Caveat Emptor - Destructive commands ahead.
Mitigation - git reflog
can save you if you need it.
1) UNDO local file changes and KEEP your last commit
git reset --hard
2) UNDO local file changes and REMOVE your last commit
git reset --hard HEAD^
3) KEEP local file changes and REMOVE your last commit
git reset --soft HEAD^
For Python versions prior to 2.6, use the string formatting operator %
:
filename = "ME%d.txt" % i
For 2.6 and later, use the str.format()
method:
filename = "ME{0}.txt".format(i)
Though the first example still works in 2.6, the second one is preferred.
If you have more than 10 files to name this way, you might want to add leading zeros so that the files are ordered correctly in directory listings:
filename = "ME%02d.txt" % i
filename = "ME{0:02d}.txt".format(i)
This will produce file names like ME00.txt
to ME99.txt
. For more digits, replace the 2
in the examples with a higher number (eg, ME{0:03d}.txt
).
You can either post HTML form to URL, which is mapped to servlet or insert your data in HttpServletRequest object you pass to jsp page.
With minor corrections:
function rearrange()
{
var windowHeight;
if (typeof window.innerWidth != 'undefined')
{
windowHeight = window.innerHeight;
}
// IE6 in standards compliant mode (i.e. with a valid doctype as the first
// line in the document)
else if (typeof document.documentElement != 'undefined'
&& typeof document.documentElement.clientWidth != 'undefined'
&& document.documentElement.clientWidth != 0)
{
windowHeight = document.documentElement.clientHeight;
}
// older versions of IE
else
{
windowHeight = document.getElementsByTagName('body')[0].clientHeight;
}
document.getElementById("foobar").style.height = (windowHeight - document.getElementById("foobar").offsetTop - 6)+ "px";
}
There is a proper way to split the filename and the extension: Extract filename and extension in Bash
You can apply it like this:
date=$(date +"%m%d%y")
for FILE in folder1/*.csv
do
bname=$(basename "$FILE")
extension="${bname##*.}"
filenamewoext="${bname%.*}"
newfilename="${filenamewoext}${date}.${extension}
cp folder1/${FILE} folder2/${newfilename}
done
Generally a cosine similarity between two documents is used as a similarity measure of documents. In Java, you can use Lucene (if your collection is pretty large) or LingPipe to do this. The basic concept would be to count the terms in every document and calculate the dot product of the term vectors. The libraries do provide several improvements over this general approach, e.g. using inverse document frequencies and calculating tf-idf vectors. If you are looking to do something copmlex, LingPipe also provides methods to calculate LSA similarity between documents which gives better results than cosine similarity. For Python, you can use NLTK.
Go to first line
:1
or Ctrl + Home
Go to last line
:%
or Ctrl + End
Go to another line (f.i. 27)
:27
[Works On VIM 7.4 (2016) and 8.0 (2018)]
A simpler way which eliminates checking if the app can open the url.
loadInBrowser = () => {
Linking.openURL(this.state.url).catch(err => console.error("Couldn't load page", err));
};
Calling it with a button.
<Button title="Open in Browser" onPress={this.loadInBrowser} />
I think this will do it for you:
location / {
try_files /base.html =404;
}
As other mentioned JSX
is not a standard Javascript extension. It's better to name your entry point of Application based on .js
and for the rest components, you can use .jsx
.
I have an important reason for why I'm using .JSX
for all component's file names.
Actually, In a large scale project with huge bunch of code, if we set all React's component with .jsx
extension, It'll be easier while navigating to different javascript files across the project(like helpers, middleware, etc.) and you know this is a React Component and not other types of the javascript file.
PID is the process ID - not the port number. You need to look for an entry with ":8080" at the end of the address/port part (the second column). Then you can look at the PID and use Task Manager to work out which process is involved... or run netstat -abn
which will show the process names (but must be run under an administrator account).
Having said that, I would expect the find "8080"
to find it...
Another thing to do is just visit http://localhost:8080
- on that port, chances are it's a web server of some description.
Try this:
USE DatabaseName
GO
DBCC SHRINKFILE( TransactionLogName, 1)
BACKUP LOG DatabaseName WITH TRUNCATE_ONLY
DBCC SHRINKFILE( TransactionLogName, 1)
GO
My first post...
I tried this: change 'tr' for 'td' and you will get all HTMLRowElements into an Array, and using textContent will change from Object into String
var dataArray = [];
var data = table.find('td'); //Get All HTML td elements
// Save important data into new Array
for (var i = 0; i <= data.size() - 1; i = i + 4)
{
dataArray.push(data[i].textContent, data[i + 1].textContent, data[i + 2].textContent);
}
Since I needed something, that also works with Localization, I came up with these two methods:
private int getArrayPositionForValue(final int arrayResId, final String value) {
final Resources english = Utils.getLocalizedResources(this, new Locale("en"));
final List<String> arrayValues = Arrays.asList(english.getStringArray(arrayResId));
for (int position = 0; position < arrayValues.size(); position++) {
if (arrayValues.get(position).equalsIgnoreCase(value)) {
return position;
}
}
Log.w(TAG, "getArrayPosition() --> return 0 (fallback); No index found for value = " + value);
return 0;
}
As you can see, I also stumbled over additional complexity of case sensitivity between arrays.xml and the value
I am comparing against.
If you don't have this, the above method can be simplified to something like:
return arrayValues.indexOf(value);
public static Resources getLocalizedResources(Context context, Locale desiredLocale) {
Configuration conf = context.getResources().getConfiguration();
conf = new Configuration(conf);
conf.setLocale(desiredLocale);
Context localizedContext = context.createConfigurationContext(conf);
return localizedContext.getResources();
}
Here's a simple trick that defines column indices "in place". Because set_index
sets row indices in place, we can do the same thing for columns by transposing the data frame, setting the index, and transposing it back:
df = df.T.set_index(0).T
Note you may have to change the 0
in set_index(0)
if your rows have a different index already.
Step 1 : Create two view inside a linear layout
Step 2 : First view must set to android:layout_weight="1"
Step 3 : Second view will automatically putted downwards
<LinearLayout
android:id="@+id/botton_header"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<Button
android:id="@+id/btn_health_advice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
Add an Id
property into the P
tag with value like text or something:
function gettext() {
var amount = document.getElementById('text').value;
}
Static block can be used to show that a program can run without main function also.
//static block
//static block is used to initlize static data member of the clas at the time of clas loading
//static block is exeuted before the main
class B
{
static
{
System.out.println("Welcome to Java");
System.exit(0);
}
}
Laravel 5.2+, back button
<a href="{{ url()->previous() }}" class="btn btn-default">Back</a>
Here I have a simple solution inspired by Ray's answer. This should be sufficient to identify any form of number.
This solution can also be easily modified if you want only positive numbers, integer values or values accurate to a maximum number of decimal places, etc.
As suggested in Ray's answer, you need to first add a PreviewTextInput
event:
<TextBox PreviewTextInput="TextBox_OnPreviewTextInput"/>
Then put the following in the code behind:
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textBox = sender as TextBox;
// Use SelectionStart property to find the caret position.
// Insert the previewed text into the existing text in the textbox.
var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
double val;
// If parsing is successful, set Handled to false
e.Handled = !double.TryParse(fullText, out val);
}
To invalid whitespace, we can add NumberStyles
:
using System.Globalization;
private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textBox = sender as TextBox;
// Use SelectionStart property to find the caret position.
// Insert the previewed text into the existing text in the textbox.
var fullText = textBox.Text.Insert(textBox.SelectionStart, e.Text);
double val;
// If parsing is successful, set Handled to false
e.Handled = !double.TryParse(fullText,
NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign,
CultureInfo.InvariantCulture,
out val);
}
I've backported the three Material Design progress drawables to Android 4.0, which can be used as a drop-in replacement for regular ProgressBar
, with exactly the same appearance.
These drawables also backported the tinting APIs (and RTL support), and uses ?colorControlActivated
as the default tint. A MaterialProgressBar
widget which extends ProgressBar
has also been introduced for convenience.
DreaminginCodeZH/MaterialProgressBar
This project has also been adopted by afollestad/material-dialogs for progress dialog.
On Android 4.4.4:
On Android 5.1.1:
You can of course format the result of current_timestamp()
.
Please have a look at the various formatting functions in the official documentation.
This works in all browsers -
new Date('2001/01/31 12:00:00 AM')
new Date('2001-01-31 12:00:00')
Format: YYYY-MM-DDTHH:mm:ss.sss
Details: http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15
public class BOX
{
double height, length, breadth;
public static bool operator == (BOX b1, BOX b2)
{
if (b1 is null)
return b2 is null;
return b1.Equals(b2);
}
public static bool operator != (BOX b1, BOX b2)
{
return !(b1 == b2);
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
return obj is BOX b2? (length == b2.length &&
breadth == b2.breadth &&
height == b2.height): false;
}
public override int GetHashCode()
{
return (height,length,breadth).GetHashCode();
}
}
Here is the analysis in the book Data Structures and Algorithm Analysis in C by Mark Allen Weiss (second edition, 2.4.4):
Euclid's algorithm works by continually computing remainders until 0 is reached. The last nonzero remainder is the answer.
Here is the code:
unsigned int Gcd(unsigned int M, unsigned int N)
{
unsigned int Rem;
while (N > 0) {
Rem = M % N;
M = N;
N = Rem;
}
Return M;
}
Here is a THEOREM that we are going to use:
If M > N, then M mod N < M/2.
PROOF:
There are two cases. If N <= M/2, then since the remainder is smaller than N, the theorem is true for this case. The other case is N > M/2. But then N goes into M once with a remainder M - N < M/2, proving the theorem.
So, we can make the following inference:
Variables M N Rem
initial M N M%N
1 iteration N M%N N%(M%N)
2 iterations M%N N%(M%N) (M%N)%(N%(M%N)) < (M%N)/2
So, after two iterations, the remainder is at most half of its original value. This would show that the number of iterations is at most
2logN = O(logN)
.Note that, the algorithm computes Gcd(M,N), assuming M >= N.(If N > M, the first iteration of the loop swaps them.)
Exact transfer to Angular2+ is as below:
<button (click)="myFunc()"></button>
also in your component file:
import { Component, OnInit } from "@angular/core";
@Component({
templateUrl:"button.html" //this is the component which has the above button html
})
export class App implements OnInit{
constructor(){}
ngOnInit(){
}
myFunc(){
console.log("function called");
}
}
This can be changed to 0/1 through using CASE WHEN
like this example:
SELECT
CASE WHEN SchemaName.TableName.BitFieldName = 'true' THEN 1 ELSE 0 END AS 'bit Value'
FROM SchemaName.TableName
So here is an other way:
background-image: linear-gradient(rgba(255,255,255,0.5), rgba(255,255,255,0.5)), url("your_image.png");
all these answers has the problem, that's always stretching the image to pagesize and cuts off some content at trying this.
Found a little bit easier way.
My own solution only stretch(is this the right word?) if the image is to large, can use multiply copies and pageorientations.
PrintDialog dlg = new PrintDialog();
if (dlg.ShowDialog() == true)
{
BitmapImage bmi = new BitmapImage(new Uri(strPath));
Image img = new Image();
img.Source = bmi;
if (bmi.PixelWidth < dlg.PrintableAreaWidth ||
bmi.PixelHeight < dlg.PrintableAreaHeight)
{
img.Stretch = Stretch.None;
img.Width = bmi.PixelWidth;
img.Height = bmi.PixelHeight;
}
if (dlg.PrintTicket.PageBorderless == PageBorderless.Borderless)
{
img.Margin = new Thickness(0);
}
else
{
img.Margin = new Thickness(48);
}
img.VerticalAlignment = VerticalAlignment.Top;
img.HorizontalAlignment = HorizontalAlignment.Left;
for (int i = 0; i < dlg.PrintTicket.CopyCount; i++)
{
dlg.PrintVisual(img, "Print a Image");
}
}
You can try
Random r = new Random();
int rInt = r.Next(0, 100); //for ints
int range = 100;
double rDouble = r.NextDouble()* range; //for doubles
Have a look at
Random Class, Random.Next Method (Int32, Int32) and Random.NextDouble Method
This worked for me:
driver.findElement(yourElement).clear();
driver.findElement(yourelement).sendKeys("");
For those wanting a more secure way to create a random byte array, yes the most secure way is:
byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);
BUT your threads might block if there is not enough randomness available on the machine, depending on your OS. The following solution will not block:
SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);
This is because the first example uses /dev/random
and will block while waiting for more randomness (generated by a mouse/keyboard and other sources). The second example uses /dev/urandom
which will not block.