If your sending out an internal survey that requires 100% participation from your company's employees, then a better route would be to just have the form keep track of the responders ID/Username/email etc. Every few days or so just send a nice little email reminder to those in your organization to complete the survey...you could probably even automate this.
//display sample reg form in notepad.txt
using (StreamWriter stream = new FileInfo("D:\\tt.txt").AppendText())//ur file location//.AppendText())
{
stream.WriteLine("Name :" + textBox1.Text);//display textbox data in notepad
stream.WriteLine("DOB : " + dateTimePicker1.Text);//display datepicker data in notepad
stream.WriteLine("DEP:" + comboBox1.SelectedItem.ToString());
stream.WriteLine("EXM :" + listBox1.SelectedItem.ToString());
}
volatile:
volatile
is a keyword. volatile
forces all threads to get latest value of the variable from main memory instead of cache. No locking is required to access volatile variables. All threads can access volatile variable value at same time.
Using volatile
variables reduces the risk of memory consistency errors, because any write to a volatile variable establishes a happens-before relationship with subsequent reads of that same variable.
This means that changes to a volatile
variable are always visible to other threads. What's more, it also means that when a thread reads a volatile
variable, it sees not just the latest change to the volatile, but also the side effects of the code that led up the change.
When to use: One thread modifies the data and other threads have to read latest value of data. Other threads will take some action but they won't update data.
AtomicXXX:
AtomicXXX
classes support lock-free thread-safe programming on single variables. These AtomicXXX
classes (like AtomicInteger
) resolves memory inconsistency errors / side effects of modification of volatile variables, which have been accessed in multiple threads.
When to use: Multiple threads can read and modify data.
synchronized:
synchronized
is keyword used to guard a method or code block. By making method as synchronized has two effects:
First, it is not possible for two invocations of synchronized
methods on the same object to interleave. When one thread is executing a synchronized
method for an object, all other threads that invoke synchronized
methods for the same object block (suspend execution) until the first thread is done with the object.
Second, when a synchronized
method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized
method for the same object. This guarantees that changes to the state of the object are visible to all threads.
When to use: Multiple threads can read and modify data. Your business logic not only update the data but also executes atomic operations
AtomicXXX
is equivalent of volatile + synchronized
even though the implementation is different. AmtomicXXX
extends volatile
variables + compareAndSet
methods but does not use synchronization.
Related SE questions:
Difference between volatile and synchronized in Java
Volatile boolean vs AtomicBoolean
Good articles to read: ( Above content is taken from these documentation pages)
https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.html
https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/atomic/package-summary.html
Consider fwrite():
<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>
https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/universal.html
w.winfo_children()
Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top).
for widget in frame.winfo_children():
widget.destroy()
Will destroy all the widget in your frame. No need for a second frame.
If you read the comments there's a nice discussion around this particular naming convention.
It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books, etc. speak about var
declaration, and function
declaration.
Here is the additional Wikipedia post that supports my point: Declarations and definitions ...and to answer the main question. Declare variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)
If you have a column called "col1" which is int, you cast it to String like this:
CONVERT(col1,char)
e.g. this allows you to check an int value is containing another value (here 9) like this:
CONVERT(col1,char) LIKE '%9%'
As already mentioned that, break-statement works only with switches and loops. Here is another way to achieve what is being asked. I am reproducing https://stackoverflow.com/a/257421/1188057 as nobody else mentioned it. It's just a trick involving the do-while loop.
do {
// do something
if (error) {
break;
}
// do something else
if (error) {
break;
}
// etc..
} while (0);
Though I would prefer the use of goto-statement.
According to documentation class date
is a parent for class datetime
. And isinstance()
method will give you True
in all cases. If you need to distinguish datetime
from date
you should check name of the class
import datetime
datetime.datetime.now().__class__.__name__ == 'date' #False
datetime.datetime.now().__class__.__name__ == 'datetime' #True
datetime.date.today().__class__.__name__ == 'date' #True
datetime.date.today().__class__.__name__ == 'datetime' #False
I've faced with this problem when i have different formatting rules for dates and dates with time
I'm not sure what you want. First of all, of course each time you commit/push the directory is going to get a little larger, since it has to store each of those additional commits.
However, probably you want git gc
which will "cleanup unnecessary files and optimize the local repository" (manual page).
Another possibly relevant command is git clean
which will delete untracked files from your tree (manual page).
Aspx
<ajax:ModalPopupExtender runat="server" ID="modalPop"
PopupControlID="pnlpopup"
TargetControlID="btnGo"
BackgroundCssClass="modalBackground"
DropShadow="true"
CancelControlID="btnCancel" X="470" Y="300" />
//Codebehind
protected void OkButton_Clicked(object sender, EventArgs e)
{
modalPop.Hide();
//Do something in codebehind
}
And don't set the OK button as OkControlID.
this Func may help you . it add every list object to grid view
private void show_data()
{
BindingSource Source = new BindingSource();
for (int i = 0; i < CC.Contects.Count; i++)
{
Source.Add(CC.Contects.ElementAt(i));
};
Data_View.DataSource = Source;
}
I write this for simple database app
UPDATE
The bookmarklet hack below is broken due to XHR issues and API changes.
Thankfully Github now has "A Whole New Code Search" which does the job superbly.
Checkout this voodoo: Github code search userscript.
Follow the directions there, or if you hate bloating your browser with scripts and extensions, use my bookmarkified bundle of the userscript:
javascript:(function(){var s='https://raw.githubusercontent.com/skratchdot/github-enhancement-suite/master/build/github-enhancement-suite.user.js',t='text/javascript',d=document,n=navigator,e;(e=d.createElement('script')).src=s;e.type=t;d.getElementsByTagName('head')[0].appendChild(e)})();doIt('');void('');
Save the source above as the URL of a new bookmark. Browse to any Github repo, click the bookmark, and bam: in-page, ajaxified code search.
CAVEAT Github must index a repo before you can search it.
Abracadabra...
Here's a sample search from the annotated ECMAScript 5.1 specification repository:
For local access, large numbers of directories/files doesn't seem to be an issue. However, if you're accessing it across a network, there's a noticeable performance hit after a few hundred (especially when accessed from Vista machines (XP to Windows Server w/NTFS seemed to run much faster in that regard)).
You can simply use NSURLCredential
, it will save both username and password in the keychain in just two lines of code.
See my detailed answer.
Or why not
if line.startswith(prefix):
return line.replace(prefix, '', 1)
this may be old, but for those looking for answer you can use this...
public void stopHandler() {
handler.removeMessages(0);
}
cheers
You can create variable like this:
x = 10
print(x)
Or this:
globals()['y'] = 100
print(y)
Lets create a new class:
class Foo(object):
def __init__(self):
self.name = 'John'
You can create class instance this way:
instance_name_1 = Foo()
Or this way:
globals()['instance_name_2'] = Foo()
Lets create a function:
def create_new_instance(class_name,instance_name):
globals()[instance_name] = class_name()
print('Class instance '{}' created!'.format(instance_name))
Call a function:
create_new_instance(Foo,'new_instance') #Class instance 'new_instance' created!
print(new_instance.name) #John
Also we can write generator function:
def create_instance(class_name,instance_name):
count = 0
while True:
name = instance_name + str(count)
globals()[name] = class_name()
count += 1
print('Class instance: {}'.format(name))
yield True
generator_instance = create_instance(Foo,'instance_')
for i in range(5):
next(generator_instance)
#out
#Class instance: instance_0
#Class instance: instance_1
#Class instance: instance_2
#Class instance: instance_3
#Class instance: instance_4
print(instance_0.name) #john
print(instance_1.name) #john
print(instance_2.name) #john
print(instance_3.name) #john
print(instance_4.name) #john
#print(instance_5.name) #error.. we only created 5 instances..
next(generator_instance) #Class instance: instance_5
print(instance_5.name) #John Now it works..
Code coverage features, as well as programmable API's, come with Visual Studio 2010. Sadly, the only two editions that include the full Code Coverage capabilities are Premium and Ultimate. However, I do believe the API's will be available with any edition, so creating code coverage files and writing a viewer for the coverage info would likely be possible.
I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.
.text span {
background:rgba(165, 220, 79, 0.8);
float: left;
clear: left;
padding:7px 10px;
color:white;
}
Note:Remove <br/>
's before using this off course.
I tried @PhilNicholas 's code and got the same problem of @its_me said in the comments that search bar show up on the next line of navbar, and I found that form
need to be added an attribute width
.
<form role="search" style="width: 15em; margin: 0.3em 2em;">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<div class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</div>
</div>
</form>
foreach(DataRow row in dt.Rows)
{
string value = row[3].ToString();
}
xrange from Python 2 is a generator and implements iterator while range is just a function. In Python3 I don't know why was dropped off the xrange.
Try this in web.config to replace IIS error pages. This is the best solution I guess, and it sends out the correct status code too.
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<remove statusCode="500" subStatusCode="-1" />
<error statusCode="404" path="Error404.html" responseMode="File" />
<error statusCode="500" path="Error.html" responseMode="File" />
</httpErrors>
</system.webServer>
More info from Tipila - Use Custom Error Pages ASP.NET MVC
You are mixing pointers and arrays. If what you want is an array, then use an array:
struct test {
static int data[10]; // array, not pointer!
};
int test::data[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
If on the other hand you want a pointer, the simplest solution is to write a helper function in the translation unit that defines the member:
struct test {
static int *data;
};
// cpp
static int* generate_data() { // static here is "internal linkage"
int * p = new int[10];
for ( int i = 0; i < 10; ++i ) p[i] = 10*i;
return p;
}
int *test::data = generate_data();
In c#, View.BringSubviewToFront(childView); YourView.Layer.ZPosition = 1; both should work.
dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/
Simple answer
If you are behind a proxy server, please set the proxy for curl. The curl is not able to connect to server so it shows wrong version number. Set proxy by opening subl ~/.curlrc or use any other text editor. Then add the following line to file: proxy= proxyserver:proxyport For e.g. proxy = 10.8.0.1:8080
If you are not behind a proxy, make sure that the curlrc file does not contain the proxy settings.
Below code disables ListViewItem row selection and also allows to add padding, margin etc.
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListViewItem}">
<ListViewItem Padding="0" Margin="0">
<ContentPresenter />
</ListViewItem>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
Try this one for Updating:
[HttpPost]
public ActionResult Edit(Models.MathClass mathClassModel)
{
//get current entry from db (db is context)
var item = db.Entry<Models.MathClass>(mathClassModel);
//change item state to modified
item.State = System.Data.Entity.EntityState.Modified;
//load existing items for ManyToMany collection
item.Collection(i => i.Students).Load();
//clear Student items
mathClassModel.Students.Clear();
//add Toner items
foreach (var studentId in mathClassModel.SelectedStudents)
{
var student = db.Student.Find(int.Parse(studentId));
mathClassModel.Students.Add(student);
}
if (ModelState.IsValid)
{
db.SaveChanges();
return RedirectToAction("Index");
}
return View(mathClassModel);
}
For simplicity, why not create the backup table from the select statement?
CREATE TABLE t1_backup AS SELECT a, b FROM t1;
DROP TABLE t1;
ALTER TABLE t1_backup RENAME TO t1;
We were able to solve a similar issue here using Oracle LISTAGG. There was a point where what we were grouping on exceeded the 4K limit but this was easily solved by having the first dataset take the first 15 items to aggregate, each of which have a 256K limit.
More info: We have projects, which have change orders, which in turn have explanations. Why the database is set up to take change text in chunks of 256K limits is not known but its one of the design constraints. So the application that feeds change explanations into the table stops at 254K and inserts, then gets the next set of text and if > 254K generates another row, etc. So we have a project to a change order, a 1:1. Then we have these as 1:n for explanations. LISTAGG concatenates all these. We have RMRKS_SN values, 1 for each remark and/or for each 254K of characters.
The largest RMRKS_SN was found to be 31, so I did the first dataset pulling SN 0 to 15, the 2nd dataset 16 to 30 and the last dataset 31 to 45 -- hey, let's plan on someone adding a LOT of explanation to some change orders!
In the SQL report, the Tablix ties to the first dataset. To get the other data, here's the expression:
=First(Fields!NON_STD_TXT.Value, "DataSet_EXPLAN") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_16_TO_30") & First(Fields!NON_STD_TXT.Value, "ds_EXPLAN_SN_31_TO_45")
For us, we have to have DB Group create functions, etc. because of security constraints. So with a bit of creativity, we didn't have to do a User Aggregate or a UDF.
If your application has some sort of SN to aggregate by, this method should work. I don't know what the equivalent TSQL is -- we're fortunate to be dealing with Oracle for this report, for which LISTAGG is a Godsend.
The code is:
SELECT
LT.C_O_NBR AS LT_CO_NUM,
RT.C_O_NBR AS RT_CO_NUM,
LT.STD_LN_ITM_NBR,
RT.NON_STD_LN_ITM_NBR,
RT.NON_STD_PRJ_NBR,
LT.STD_PRJ_NBR,
NVL(LT.PRPSL_LN_NBR, RT.PRPSL_LN_NBR) AS PRPSL_LN_NBR,
LT.STD_CO_EXPL_TXT AS STD_TXT,
LT.STD_CO_EXPLN_T,
LT.STD_CO_EXPL_SN,
RT.NON_STD_CO_EXPLN_T,
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 0 AND 15
GROUP BY
LT.C_O_NBR,
RT.C_O_NBR,
...
And in the other 2 datasets just select the LISTAGG only for the subqueries in the FROM:
SELECT
LISTAGG(RT.RMRKS_TXT_FLD, '')
WITHIN GROUP(ORDER BY RT.RMRKS_SN) AS NON_STD_TXT
FROM ...
WHERE RT.RMRKS_SN BETWEEN 31 AND 45
...
... and so on.
The book is a bit dated with respect to subclass-superclass calling. It's also a little dated with respect to subclassing built-in classes.
It looks like this nowadays:
class FileInfo(dict):
"""store file metadata"""
def __init__(self, filename=None):
super(FileInfo, self).__init__()
self["name"] = filename
Note the following:
We can directly subclass built-in classes, like dict
, list
, tuple
, etc.
The super
function handles tracking down this class's superclasses and calling functions in them appropriately.
If you want to check quietly via $? without the hassle of grep'ing wget's output you can use:
wget -q "http://blah.meh.com/my/path" -O /dev/null
Works even on URLs with just a path but has the disadvantage that something's really downloaded so this is not recommended when checking big files for existence.
You can also do:
return InternalServerError(new Exception("SOME CUSTOM MESSAGE"));
You don't need to create a button. The facility exists by default.
Just right click on the arrow buttons on the bottom left hand corner of the Excel window. These are the arrow buttons which if you left click move left or right one worksheet.
If you right-click on these arrows Excel will pop up a dialogue with a list of worksheets from which you can click to set your chosen sheet active.
In a .txt
file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+
in the space Find what
and let the space Replace with blank
Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button
//
syntaxregex.test(string)
, not string.test(regex)
So
jQuery(function () {
$(".mail").keyup(function () {
var VAL = this.value;
var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');
if (email.test(VAL)) {
alert('Great, you entered an E-Mail-address');
}
});
});
I wrote this small package that lets you require packages by their relative path from project root, without introducing any global variables or overriding node defaults
https://github.com/Gaafar/pkg-require
It works like this
// create an instance that will find the nearest parent dir containing package.json from your __dirname
const pkgRequire = require('pkg-require')(__dirname);
// require a file relative to the your package.json directory
const foo = pkgRequire('foo/foo')
// get the absolute path for a file
const absolutePathToFoo = pkgRequire.resolve('foo/foo')
// get the absolute path to your root directory
const packageRootPath = pkgRequire.root()
I don't understand what the meaning of ordering with the same column ASC
and DESC
in the same ORDER BY
, but this how you can do it: naam DESC, naam ASC
like so:
ORDER BY `product_category_id` DESC,`naam` DESC, `naam` ASC
If you're doing this to several fields, or doing it quite often, then perhaps a plugin is the answer.
Here's the beginnings of a jQuery plugin that formats the value of a field to two decimal places.
It is triggered by the onchange event of the field. You may want something different.
<script type="text/javascript">
// mini jQuery plugin that formats to two decimal places
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
// apply the currencyFormat behaviour to elements with 'currency' as their class
$( function() {
$('.currency').currencyFormat();
});
</script>
<input type="text" name="one" class="currency"><br>
<input type="text" name="two" class="currency">
My hint:
FIND IF EXISTS in .env:
APP_URL=http://yourhost.dev
REPLACE TO (OR ADD)
APP_DOMAIN=yourhost.dev
FIND in config/app.php:
'url' => env('APP_URL'),
REPLACE TO
'domain' => env('APP_DOMAIN'),
'url' => 'http://' . env('APP_DOMAIN'),
USE:
Config::get('app.domain'); // yourhost.dev
Config::get('app.url') // http://yourhost.dev
Do your magic!
Just an addition to @Andy Hayden's answer:
Since DataFrame.mask
is the opposite twin of DataFrame.where
, they have the exactly same signature but with opposite meaning:
DataFrame.where
is useful for Replacing values where the condition is False. DataFrame.mask
is used for Replacing values where the condition is True.So in this question, using df.mask(df.isna(), other=None, inplace=True)
might be more intuitive.
The time.Parse
function does not do Unix timestamps. Instead you can use strconv.ParseInt
to parse the string to int64
and create the timestamp with time.Unix
:
package main
import (
"fmt"
"time"
"strconv"
)
func main() {
i, err := strconv.ParseInt("1405544146", 10, 64)
if err != nil {
panic(err)
}
tm := time.Unix(i, 0)
fmt.Println(tm)
}
Output:
2014-07-16 20:55:46 +0000 UTC
Playground: http://play.golang.org/p/v_j6UIro7a
Edit:
Changed from strconv.Atoi
to strconv.ParseInt
to avoid int overflows on 32 bit systems.
Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return false;
}
if(getCookie("KoiMilGaya")) {
//alert('found');
// Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again..
} else {
//alert('nothing');
// Display popup or anthing here. it shows on first visit only.
// this will load again when user closer browser and open again.
setCookie('KoiMilGaya','1');
}
You can just use the TimeOfDay property of date time, which is TimeSpan type:
DateTime.TimeOfDay
This property has been around since .NET 1.1
More information: http://msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx
This will give just the names of the stored procedures.
select specific_name
from information_schema.routines
where routine_type = 'PROCEDURE';
i think u miss understand about table relation..
users : scores = 1 : *
just join
is not a solution.
is this your intention?
SELECT users.username, avg(scores.point), avg(scores.avg_time)
FROM scores, users
WHERE scores.user_id = users.id
GROUP BY users.username
ORDER BY avg(scores.point) DESC, avg(scores.avg_time)
LIMIT 0, 20
(this query to get each users average point and average avg_time by desc point, asc )avg_time
if you want to get each scores ranking? use left outer join
SELECT users.username, scores.point, scores.avg_time
FROM scores left outer join users on scores.user_id = users.id
ORDER BY scores.point DESC, scores.avg_time
LIMIT 0, 20
Make the list a character vector (not a vector of names)
rm(list = c('temp1','temp2'))
or
rm(temp1, temp2)
I have a feeling that your ClientID
is not of a string type (zero-terminated char*
or std::string
) but some integral type (e.g. int
) so you need to convert number to the string first:
std::stringstream ss;
ss << ClientID;
query.append(ss.str());
But you can use operator+
as well (instead of append
):
query += ss.str();
Although this question is old, it is still relevant for my more or less up-to-date system. After enabling debug mode of sudo (Debug sudo /var/log/sudo_debug all@info
in /etc/sudo.conf
) I was pointed to /dev: "/dev is world writable
". So you might need to check the tty file permissions, especially those of the directory where the tty/pts node resides in.
This would get all files in path/to/files with an .swf extension into an array and then sort that array by the file's mtime
$files = glob('path/to/files/*.swf');
usort($files, function($a, $b) {
return filemtime($b) - filemtime($a);
});
The above uses an Lambda function and requires PHP 5.3. Prior to 5.3, you would do
usort($files, create_function('$a,$b', 'return filemtime($b)-filemtime($a);'));
If you don't want to use an anonymous function, you can just as well define the callback as a regular function and pass the function name to usort
instead.
With the resulting array, you would then iterate over the files like this:
foreach($files as $file){
printf('<tr><td><input type="checkbox" name="box[]"></td>
<td><a href="%1$s" target="_blank">%1$s</a></td>
<td>%2$s</td></tr>',
$file, // or basename($file) for just the filename w\out path
date('F d Y, H:i:s', filemtime($file)));
}
Note that because you already called filemtime
when sorting the files, there is no additional cost when calling it again in the foreach loop due to the stat cache.
To add okhttp as a dependency do as follows
now you have okhttp as a dependency
Now design a interface as below so we can have the callback to our activity once the network response received.
public interface NetworkCallback {
public void getResponse(String res);
}
I create a class named NetworkTask so i can use this class to handle all the network requests
public class NetworkTask extends AsyncTask<String , String, String>{
public NetworkCallback instance;
public String url ;
public String json;
public int task ;
OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public NetworkTask(){
}
public NetworkTask(NetworkCallback ins, String url, String json, int task){
this.instance = ins;
this.url = url;
this.json = json;
this.task = task;
}
public String doGetRequest() throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
public String doPostRequest() throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
@Override
protected String doInBackground(String[] params) {
try {
String response = "";
switch(task){
case 1 :
response = doGetRequest();
break;
case 2:
response = doPostRequest();
break;
}
return response;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
instance.getResponse(s);
}
}
now let me show how to get the callback to an activity
public class MainActivity extends AppCompatActivity implements NetworkCallback{
String postUrl = "http://your-post-url-goes-here";
String getUrl = "http://your-get-url-goes-here";
Button doGetRq;
Button doPostRq;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
doGetRq = findViewById(R.id.button2);
doPostRq = findViewById(R.id.button1);
doPostRq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.sendPostRq();
}
});
doGetRq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity.this.sendGetRq();
}
});
}
public void sendPostRq(){
JSONObject jo = new JSONObject();
try {
jo.put("email", "yourmail");
jo.put("password","password");
} catch (JSONException e) {
e.printStackTrace();
}
// 2 because post rq is for the case 2
NetworkTask t = new NetworkTask(this, postUrl, jo.toString(), 2);
t.execute(postUrl);
}
public void sendGetRq(){
// 1 because get rq is for the case 1
NetworkTask t = new NetworkTask(this, getUrl, jo.toString(), 1);
t.execute(getUrl);
}
@Override
public void getResponse(String res) {
// here is the response from NetworkTask class
System.out.println(res)
}
}
The line below would hide the index column of DataFrame when you print
df.style.hide_index()
Update: tested w Python 3.7
Use a PHP Excel for generatingExcel file. You can find a good one called PHPExcel here: https://github.com/PHPOffice/PHPExcel
And for PDF
generation use http://princexml.com/
I would have done using just single line like
List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
.Where(file => new string[] { ".jpg", ".gif", ".png" }
.Contains(Path.GetExtension(file)))
.ToList();
Use the microtime
function. The documentation includes example code.
For systemd style init scripts it's really easy. You just add a User= in the [Service] section.
Here is an init script I use for qbittorrent-nox on CentOS 7:
[Unit]
Description=qbittorrent torrent server
[Service]
User=<username>
ExecStart=/usr/bin/qbittorrent-nox
Restart=on-abort
[Install]
WantedBy=multi-user.target
public static String getCurrentMethodName() {
return Thread.currentThread().getStackTrace()[2].getClassName() + "." + Thread.currentThread().getStackTrace()[2].getMethodName();
}
Ugg! This turned out to simply be a Java version issue for me. I got the handshake error using JRE 1.6 and everything worked perfectly using JRE 1.8.0_144.
Using JSTL:
<c:set var="message" value='${requestScope["Error_Message"]}' />
Here var sets the variable name and request.getAttribute is equal to requestScope. But it's not essential. ${Error_Message} will give you the same outcome. It'll search every scope. If you want to do some operation with content you take from Error_Message you have to do it using message. like below one.
<c:out value="${message}"/>
You can use this code snippet ...
<html>
<body>
<form>
<input type="radio" name="color" value="black" required />
<input type="radio" name="color" value="white" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Specify "required" keyword in one of the select statements. If you want to change the default way of its appearance. You can follow these steps. This is just for extra info if you have any intention to modify the default behavior.
Add the following into you .css
file.
/* style all elements with a required attribute */
:required {
background: red;
}
For more information you can refer following URL.
Public - If you can see the class, then you can see the method
Private - If you are part of the class, then you can see the method, otherwise not.
Protected - Same as Private, plus all descendants can also see the method.
Static (class) - Remember the distinction between "Class" and "Object" ? Forget all that. They are the same with "static"... the class is the one-and-only instance of itself.
Static (method) - Whenever you use this method, it will have a frame of reference independent of the actual instance of the class it is part of.
There are many ways to do this. My favorite way is:
Add a mod_user
field to your source table (the one you want to log).
Create a log table that contains the fields you want to log, plus a log_datetime
and seq_num
field. seq_num
is the primary key.
Build a trigger on the source table that inserts the current record into the log table whenever any monitored field is changed.
Now you've got a record of every change and who made it.
Send a POST request with content type = 'form-data':
import requests
files = {
'username': (None, 'myusername'),
'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)
Why has no one mentioned glob
? glob
lets you use Unix-style pathname expansion, and is my go to function for almost everything that needs to find more than one path name. It makes it very easy:
from glob import glob
paths = glob('*/')
Note that glob
will return the directory with the final slash (as unix would) while most path
based solutions will omit the final slash.
You can use a time_t
struct and clock()
function from time.h.
Store the start time in a time_t
struct by using clock()
and check the elapsed time by comparing the difference between stored time and current time.
In rails 6, simply add this to your controller:
class UsersController < ApplicationController
include UsersHelper
# Your actions
end
Now the user_helpers.rb will be available in the controller.
You should done my guideline:
1. Add bellow source into Gemfile
source 'https://rails-assets.org' do
gem 'rails-assets-tether', '>= 1.1.0'
end
Run command:
bundle install
Add this line after jQuery in application.js.
//= require jquery
//= require tether
Restart rails server.
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
I have almost exactly the same code as you and mine works.
Do you have jQueryUI.js included in the page?
There's a fiddle here
<input type="text" ng-model="date" jqdatepicker />
<br/>
{{ date }}
var datePicker = angular.module('app', []);
datePicker.directive('jqdatepicker', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datepicker({
dateFormat: 'DD, d MM, yy',
onSelect: function (date) {
scope.date = date;
scope.$apply();
}
});
}
};
});
You'll also need the ng-app="app" somewhere in your HTML
In my case, the folder was _Manager. After I renamed it to Manager it worked.
Now, I see login popup and I enter credentials from conf/tomcat-users.xml, It all works fine.
I am in the same boat as you do. I need to study for tech interviews, but memorizing a list is not really helpful. If you have 3-4 hours to spare, and want to do a deeper dive, I recommend checking out
mycodeschool
I’ve looked on Coursera and other resources such as blogs and textbooks,
but I find them either not comprehensive enough or at the other end of the spectrum, too dense with prerequisite computer science terminologies.
The dude in the video have a bunch of lectures on data structures. Don’t mind the silly drawings, or the slight accent at all. You need to understand not just which data structure to select, but some other points to consider when people think about data structures:
If you want to go further and extract the exact information you want from the Playbook results, use JSON query language like jmespath, an example:
- name: Sample Playbook
// Fill up your task
no_log: True
register: example_output
- name: Json Query
set_fact:
query_result:
example_output:"{{ example_output | json_query('results[*].name') }}"
Note that if you split the variables into lines, you must use backslashes to wrap the newlines.
with A() as a, \
B() as b, \
C() as c:
doSomething(a,b,c)
Parentheses don't work, since Python creates a tuple instead.
with (A(),
B(),
C()):
doSomething(a,b,c)
Since tuples lack a __enter__
attribute, you get an error (undescriptive and does not identify class type):
AttributeError: __enter__
If you try to use as
within parentheses, Python catches the mistake at parse time:
with (A() as a,
B() as b,
C() as c):
doSomething(a,b,c)
SyntaxError: invalid syntax
This issue is tracked in https://bugs.python.org/issue12782.
Recently, Python announced in PEP 617 that they'll be replacing the current parser with a new one. Because Python's current parser is LL(1), it cannot distinguish between "multiple context managers" with (A(), B()):
and "tuple of values" with (A(), B())[0]:
.
The new parser can properly parse "multiple context managers" surrounded by tuples. The new parser will be enabled in 3.9, but this syntax will still be rejected until the old parser is removed in Python 3.10.
docker container list -f "status=exited"
or
docker container ls -f "status=exited"
or
docker ps -f "status=exited"
You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.
I prefer the way Golang does quote escaping for XML (and a few extras like newline escaping, and escaping some other characters), so I have ported its XML escape function to PHP below
function isInCharacterRange(int $r): bool {
return $r == 0x09 ||
$r == 0x0A ||
$r == 0x0D ||
$r >= 0x20 && $r <= 0xDF77 ||
$r >= 0xE000 && $r <= 0xFFFD ||
$r >= 0x10000 && $r <= 0x10FFFF;
}
function xml(string $s, bool $escapeNewline = true): string {
$w = '';
$Last = 0;
$l = strlen($s);
$i = 0;
while ($i < $l) {
$r = mb_substr(substr($s, $i), 0, 1);
$Width = strlen($r);
$i += $Width;
switch ($r) {
case '"':
$esc = '"';
break;
case "'":
$esc = ''';
break;
case '&':
$esc = '&';
break;
case '<':
$esc = '<';
break;
case '>':
$esc = '>';
break;
case "\t":
$esc = '	';
break;
case "\n":
if (!$escapeNewline) {
continue 2;
}
$esc = '
';
break;
case "\r":
$esc = '
';
break;
default:
if (!isInCharacterRange(mb_ord($r)) || (mb_ord($r) === 0xFFFD && $Width === 1)) {
$esc = "\u{FFFD}";
break;
}
continue 2;
}
$w .= substr($s, $Last, $i - $Last - $Width) . $esc;
$Last = $i;
}
$w .= substr($s, $Last);
return $w;
}
Note you'll need at least PHP7.2 because of the mb_ord
usage, or you'll have to swap it out for another polyfill, but these functions are working great for us!
For anyone curious, here is the relevant Go source https://golang.org/src/encoding/xml/xml.go?s=44219:44263#L1887
When you are working with a Gitlab or Github you can run in trouble in this way. You squash your commits with one of the above method. My preferite one is:
git rebase -i HEAD~4
or
git rebase -i origin/master
select squash or fixup for yours commit. At this point you would check with git status. And the message could be:
On branch ABC-1916-remote
Your branch and 'origin/ABC-1916' have diverged,
and have 1 and 7 different commits each, respectively.
(use "git pull" to merge the remote branch into yours)
And you can be tempted to pull it. DO NOT DO THAT or you will be in the same situation as before.
Instead push to your origin with:
git push origin +ABC-1916-remote:ABC-1916
The + allow to force push only to one branch.
On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.
This is the correct way for getting the correct output.... However, childs parent id maybe sometimes printed as 1 because parent process gets terminated and the root process with pid = 1 controls this orphan process.
pid_t pid;
pid = fork();
if (pid == 0)
printf("This is the child process. My pid is %d and my parent's id
is %d.\n", getpid(), getppid());
else
printf("This is the parent process. My pid is %d and my parent's
id is %d.\n", getpid(), pid);
The first arg that you give to grep needs to evaluate as true or false to indicate whether there was a match. So it should be:
# note that grep returns a list, so $matched needs to be in brackets to get the
# actual value, otherwise $matched will just contain the number of matches
if (my ($matched) = grep $_ eq $match, @array) {
print "found it: $matched\n";
}
If you need to match on a lot of different values, it might also be worth for you to consider putting the array
data into a hash
, since hashes allow you to do this efficiently without having to iterate through the list.
# convert array to a hash with the array elements as the hash keys and the values are simply 1
my %hash = map {$_ => 1} @array;
# check if the hash contains $match
if (defined $hash{$match}) {
print "found it\n";
}
This worked for me.
header = ['row1', 'row2', 'row3']
some_list = [1, 2, 3]
with open('test.csv', 'wt', newline ='') as file:
writer = csv.writer(file, delimiter=',')
writer.writerow(i for i in header)
for j in some_list:
writer.writerow(j)
You can use set intersection operations with your ArrayList
objects.
Something like this:
List<Integer> l1 = new ArrayList<Integer>();
l1.add(1);
l1.add(2);
l1.add(3);
List<Integer> l2= new ArrayList<Integer>();
l2.add(4);
l2.add(2);
l2.add(3);
System.out.println("l1 == "+l1);
System.out.println("l2 == "+l2);
List<Integer> l3 = new ArrayList<Integer>(l2);
l3.retainAll(l1);
System.out.println("l3 == "+l3);
Now, l3
should have only common elements between l1
and l2
.
CONSOLE OUTPUT
l1 == [1, 2, 3]
l2 == [4, 2, 3]
l3 == [2, 3]
Use pathed from gtools.
It does things in an intuitive way. For example:
pathed /REMOVE "c:\my\folder"
pathed /APPEND "c:\my\folder"
It shows results without the need to spawn a new cmd!
I was having serious problems with
.data('property', value);
It was not setting the data-property
attribute.
Started using jQuery's .attr()
:
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
.attr('property', value)
to set the value and
.attr('property')
to retrieve the value.
Now it just works!
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
I tried to adapt @Siddhart's code to a relative path to run my open_form
macro, but it didn't seem to work. Here was my first attempt. My working solution is below.
Option Explicit
Dim xlApp, xlBook
dim fso
dim curDir
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlApp = CreateObject("Excel.Application")
'~~> Change Path here
Set xlBook = xlApp.Workbooks.Open(curDir & "Excels\CLIENTES.xlsb", 0, true)
xlApp.Run "open_form"
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
WScript.Echo "Finished."
EDIT
I have actually worked it out, just in case someone wants to run a userform "alike" a stand alone application:
Issues I was facing:
1 - I did not want to use the Workbook_Open Event as the excel is locked in read only. 2 - The batch command is limited that the fact that (to my knowledge) it cannot call the macro.
I first wrote a macro to launch my userform while hiding the application:
Sub open_form()
Application.Visible = False
frmAddClient.Show vbModeless
End Sub
I then created a vbs to launch this macro (doing it with a relative path has been tricky):
dim fso
dim curDir
dim WinScriptHost
set fso = CreateObject("Scripting.FileSystemObject")
curDir = fso.GetAbsolutePathName(".")
set fso = nothing
Set xlObj = CreateObject("Excel.application")
xlObj.Workbooks.Open curDir & "\Excels\CLIENTES.xlsb"
xlObj.Run "open_form"
And I finally did a batch file to execute the VBS...
@echo off
pushd %~dp0
cscript Add_Client.vbs
Note that I have also included the "Set back to visible" in my Userform_QueryClose
:
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
ThisWorkbook.Close SaveChanges:=True
Application.Visible = True
Application.Quit
End Sub
Anyway, thanks for your help, and I hope this will help if someone needs it
You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:
namespace X
{
namespace Y
{
class A;
void func(A* a) { ... } // incomplete type here!
}
}
...but, in class A was defined like this:
namespace X
{
class A { ... };
}
Thus, A was defined as X::A
, but I was using it as X::Y::A
.
The fix obviously is to move the forward reference to its proper place like so:
namespace X
{
class A;
namespace Y
{
void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
}
}
If all you're doing is attaching a string, you could do it in just 2 lines:
mail.Attachments.Add(Attachment.CreateAttachmentFromString("1,2,3", "text/csv");
mail.Attachments.Last().ContentDisposition.FileName = "filename.csv";
I wasn't able to get mine to work using our mail server with StreamWriter.
I think maybe because with StreamWriter you're missing a lot of file property information and maybe our server didn't like what was missing.
With Attachment.CreateAttachmentFromString() it created everything I needed and works great!
Otherwise, I'd suggest taking your file that is in memory and opening it using MemoryStream(byte[]), and skipping the StreamWriter all together.
It depends.
The main point is to avoid repeated code.
If the same code need to be re-used 2 times or more, and should be in sync when change, use external style sheet.
If you only use it once, I think inline is ok.
This is something easy to do and it worked for me:
//Create a Javascript executor
JavascriptExecutor jst= (JavascriptExecutor) driver;
jst.executeScript("arguments[1].value = arguments[0]; ", 55, driver.findElement(By.id("id")));
55 = value assigned
This is equivalent to new Date().getTime()
in JavaScript :
Use the below statement to get the time in seconds.
SELECT cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)
Use the below statement to get the time in milliseconds.
SELECT cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint) * 1000
There are some attempts at making SOAP work with python, but I haven't tested it much so I can't say if it is good or not.
SOAPy is one example.
Suppose you want to create a branch from a trunk name (as "TEST") then use:
svn cp -m "CREATE BRANCH TEST" $svn_url/trunk $svn_url/branches/TEST
Simply, App.config is an XML
based file format that holds the Application Level Configurations.
Example:
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="key" value="test" />
</appSettings>
</configuration>
You can access the configurations by using ConfigurationManager
as shown in the piece of code snippet below:
var value = System.Configuration.ConfigurationManager.AppSettings["key"];
// value is now "test"
Note: ConfigurationSettings
is obsolete method to retrieve configuration information.
var value = System.Configuration.ConfigurationSettings.AppSettings["key"];
Use my example...
public void createNotification() {
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon,
"message", System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
long[] pattern = { 0, 100, 600, 100, 700};
vibrator.vibrate(pattern, -1);
Intent intent = new Intent(this, Main.class);
PendingIntent activity = PendingIntent.getActivity(this, 0, intent, 0);
String sms = getSharedPreferences("SMSPREF", MODE_PRIVATE).getString("incoming", "EMPTY");
notification.setLatestEventInfo(this, "message" ,
sms, activity);
notification.number += 1;
notificationManager.notify(0, notification);
}
If you set numberOfLines
to 0 (and the label to word wrap), the label will automatically wrap and use as many of lines as needed.
If you're editing a UILabel
in IB, you can enter multiple lines of text by pressing option+return to get a line break - return alone will finish editing.
This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.
This doesn't show the window:
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;
...
cmd.Start();
For attached properties you can either call SetValue on the object for which you want to assign the value:
tblock.SetValue(Grid.RowProperty, 4);
Or call the static Set method (not as an instance method like you tried) for the property on the owner type, in this case SetRow:
Grid.SetRow(tblock, 4);
In my case image path
was wrong! So firstly, you might want to check if image path is correct :)
SELECT t1.ks, t1.[# Tasks], COALESCE(t2.[# Late], 0) AS [# Late]
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
LEFT JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON (t1.ks = t2.ks);
JavaScript has a Number
type which is a 64 bit floating point number*.
If you're looking to convert a string to a number, use
parseInt
or parseFloat
. If using parseInt
, I'd recommend always passing the radix too.+
operator e.g. +"123456"
Number
constructor e.g. var n = Number("12343")
*there are situations where the number will internally be held as an integer.
I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.
You can make master
point at 1258f0d0aae
this way:
git checkout master
git reset --hard 1258f0d0aae
But you have to be careful about doing this. It may well rewrite the history of that branch. That would create problems if you have published it and other people are working on the branch.
Also, the git reset --hard
command will throw away any uncommitted changes (i.e. those just in your working tree or the index).
You can also force an update to a branch with:
git branch -f master 1258f0d0aae
... but git won't let you do that if you're on master
at the time.
You cannot read text strings with csvread. Here is another solution:
fid1 = fopen('test.csv','r'); %# open csv file for reading
fid2 = fopen('new.csv','w'); %# open new csv file
while ~feof(fid1)
line = fgets(fid1); %# read line by line
A = sscanf(line,'%*[^,],%f,%f'); %# sscanf can read only numeric data :(
if A(2)<4.185 %# test the values
fprintf(fid2,'%s',line); %# write the line to the new file
end
end
fclose(fid1);
fclose(fid2);
Something like this?
SELECT *
FROM table1
WHERE convert(varchar, column_datetime, 111) = '2008/08/14'
I would use a ByteArrayOutputStream
. And on finish you can call:
new String( baos.toByteArray(), codepage );
or better:
baos.toString( codepage );
For the String
constructor, the codepage
can be a String
or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.
The method toString()
accepts only a String
as a codepage
parameter (stand Java 8).
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
Can you try this, readfile
need the full file path.
$filename='/pdf/jobs/pdffile.pdf';
$url_download = BASE_URL . RELATIVE_PATH . $filename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content-Disposition:inline;filename='".basename($filename)."'");
header('Content-Length: ' . filesize($filename));
header("Cache-control: private"); //use this to open files directly
readfile($filename);
If the script is the same across all users, you can use a lockfile
approach. If you acquire the lock, proceed else show a message and exit.
As an example:
[Terminal #1] $ lockfile -r 0 /tmp/the.lock
[Terminal #1] $
[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] lockfile: Sorry, giving up on "/tmp/the.lock"
[Terminal #1] $ rm -f /tmp/the.lock
[Terminal #1] $
[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] $
After /tmp/the.lock
has been acquired your script will be the only one with access to execution. When you are done, just remove the lock. In script form this might look like:
#!/bin/bash
lockfile -r 0 /tmp/the.lock || exit 1
# Do stuff here
rm -f /tmp/the.lock
Call any of these
byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input)
From
If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library
Luckily, we now have a couple of convenience methods in the nio packages. For instance:
byte[] java.nio.file.Files.readAllBytes(Path path)
The fastest and simplest way is by setting the .length
property to the desired length:
arr.length = 4;
This is also the desired way to reset/empty arrays:
arr.length = 0;
Caveat: setting this property can also make the array longer than it is: If its length is 2, running arr.length = 4
will add two undefined
items to it. Perhaps add a condition:
if (arr.length > 4) arr.length = 4;
Alternatively:
arr.length = Math.min(arr.length, 4);
I know the OP says Recycle Bin. What I do though is recreate the file, especially if it's a single file. And when in the file, I just press CMD+Z (I'm on a Mac) and I get my file back.
Put simply, an lvalue is something that can appear on the left-hand side of an assignment, typically a variable or array element.
So if you define int *p
, then p
is an lvalue. p+1
, which is a valid expression, is not an lvalue.
If you're trying to add 1 to p
, the correct syntax is:
p = p + 1;
$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');
while($row = mysql_fetch_array($sql_results))
{
$subArray[location_id]=$row['location']; //location_id is key and $row['location'] is value which come fron database.
$subArray[x]=$row['x'];
$subArray[y]=$row['y'];
$array[] = $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';
Tried couple solutions from many sources but all seemed like too much trouble. Finally I found the easiest one :)
If you're not yet familiar with zsh and oh-my-zsh then install it. You will love it :)
Then edit .zshrc
vim ~/.zshrc
find plugins
section and update it to use ssh-agent
like so:
plugins=(ssh-agent git)
And that's all! You'll have ssh-agent
up and running every time you start your shell
user = Product.where(email: /^#{email}$/i).first
The screen widths Bootstrap v3.x uses are as follows:
Extra small devices
Phones (<768px)
/ .col-xs-
Small devices
Tablets (=768px)
/ .col-sm-
Medium devices
Desktops (=992px)
/ .col-md-
Large devices
Desktops (=1200px)
/ .col-lg-
So, these are good to use and work well in practice.
This is a simple way to select an option from a dropdownlist based on a string val
private void SetDDLs(DropDownList d,string val)
{
ListItem li;
for (int i = 0; i < d.Items.Count; i++)
{
li = d.Items[i];
if (li.Value == val)
{
d.SelectedIndex = i;
break;
}
}
}
I think this should work .. :)
<input type="checkbox" name="Days[]" value="Daily">Daily<br>
<input type="checkbox" name="Days[]" value="Sunday">Sunday<br>
To get the memory usage of just your application (as opposed to the shared libraries it uses, you need to use the Linux smaps interface). This answer explains it well.
Using Java 8:
ftw.forEach((key, value) -> {
if (value.equals("foo")) {
System.out.print(key);
}
});
try this:
var span = document.getElementById("span");
span.style.fontSize = "25px";
span.innerHTML = "String";
You don't need a class, an object or a companion object for declaring constants in Kotlin. You can just declare a file holding all the constants (for example Constants.kt or you can also put them inside any existing Kotlin file) and directly declare the constants inside the file. The constants known at compile time must be marked with const
.
So, in this case, it should be:
const val MY_CONST = "something"
and then you can import the constant using:
import package_name.MY_CONST
You can refer to this link
If you want to read large files, you should read them bit by bit instead of reading them at once.
It’s simple math: If you read a 1 MB large file at once, than at least 1 MB of memory is needed at the same time to hold the data.
So you should read them bit by bit using fopen
& fread
.
This worked for me endDate: "today"
$('#datepicker').datepicker({
format: "dd/mm/yyyy",
autoclose: true,
orientation: "top",
endDate: "today"
});
All you need is parent
part if you use pathlib
.
from pathlib import Path
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parent)
Will output:
C:\Program Files\Internet Explorer
Case you need all parts (already covered in other answers) use parts
:
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parts)
Then you will get a list:
('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')
Saves tone of time.
You need to use the proper git URL:
pip install git+https://github.com/jkbr/httpie.git#egg=httpie
Also see the VCS Support section of the pip documentation.
Don’t forget to include the egg=<projectname>
part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.
You can answer your own question very easily by inputting the HTML code into the W3 Validator. (It features a text input field, you won't even have to put your code on a server...)
(And no, it won't validate.)
if (this.router && this.router.url === '/') { or your current page url e.g '/home'
window.location.reload();
} else {
this.router.navigate([url]);
}
@Autowired
can be used with setters so you could have a setter modifying an static field.
Just one final suggestion... DON'T
viewport
meta tag on mobile browser,
The initial-scale property controls the zoom level when the page is first loaded. The maximum-scale, minimum-scale, and user-scalable properties control how users are allowed to zoom the page in or out.
You can compare string with below functions.
NSString *first = @"abc";
NSString *second = @"abc";
NSString *third = [[NSString alloc] initWithString:@"abc"];
NSLog(@"%d", (second == third))
NSLog(@"%d", (first == second));
NSLog(@"%d", [first isEqualToString:second]);
NSLog(@"%d", [first isEqualToString:third]);
Output will be :-
0
1
1
1
You may not be able to do it with @ResponseBody, but something like this should work:
package xxx;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class FooBar {
@RequestMapping(value="foo/bar", method = RequestMethod.GET)
public void fooBar(HttpServletResponse response) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(myService.getJson().getBytes());
response.setContentType("application/json");
response.setContentLength(out.size());
response.getOutputStream().write(out.toByteArray());
response.getOutputStream().flush();
}
}
The LIBXML_NOCDATA
is optional third parameter of simplexml_load_file()
function. This returns the XML object with all the CDATA data converted into strings.
$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);
echo "<pre>";
print_r($xml);
echo "</pre>";
You can use standard JS toFixed
method
var num = 5.56789;
var n=num.toFixed(2);
//5.57
In order to add commas (to separate 1000's) you can add regexp as follows (where num
is a number):
num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")
//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000
Complete example:
var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//document.write(num) would write value as follows: $1,250.22
Separation character depends on country and locale. For some countries it may need to be .
Class for ArrayList & ArrayAdapter
class RequestClass {
private String Id;
private String BookingTime;
private String UserName;
private String Rating;
public RequestClass(String Id,String bookingTime,String userName,String rating){
this.Id=Id;
this.BookingTime=bookingTime;
this.UserName=userName;
this.Rating=rating;
}
public String getId(){return Id; }
public String getBookingTime(){return BookingTime; }
public String getUserName(){return UserName; }
public String getRating(){return Rating; }
}
Main Activity:
ArrayList<RequestClass> _requestList;
_requestList=new ArrayList<>();
try {
JSONObject jsonobject = new JSONObject(result);
JSONArray JO = jsonobject.getJSONArray("Record");
JSONObject object;
for (int i = 0; i < JO.length(); i++) {
object = (JSONObject) JO.get(i);
_requestList.add(new RequestClass( object.optString("playerID"),object.optString("booking_time"),
object.optString("username"),object.optString("rate") ));
}//end of for loop
RequestCustomAdapter adapter = new RequestCustomAdapter(context, R.layout.requestlayout, _requestList);
listView.setAdapter(adapter);
Custom Adapter Class
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Created by wajid on 1/12/2018.
*/
class RequestCustomAdapter extends ArrayAdapter<RequestClass> {
Context mContext;
int mResource;
public RequestCustomAdapter(Context context, int resource,ArrayList<RequestClass> objects) {
super(context, resource, objects);
mContext=context;
mResource=resource;
}
public static class ViewHolder{
RelativeLayout _layout;
TextView _bookingTime;
TextView _ratingTextView;
TextView _userNameTextView;
Button acceptButton;
Button _rejectButton;
}
@NonNull
@Override
public View getView(final int position, View convertView, ViewGroup parent){
final ViewHolder holder;
if(convertView == null) {
LayoutInflater inflater=LayoutInflater.from(mContext);
convertView=inflater.inflate(mResource,parent,false);
holder=new ViewHolder();
holder._layout = convertView.findViewById(R.id.requestLayout);
holder._bookingTime = convertView.findViewById(R.id.bookingTime);
holder._userNameTextView = convertView.findViewById(R.id.userName);
holder._ratingTextView = convertView.findViewById(R.id.rating);
holder.acceptButton = convertView.findViewById(R.id.AcceptRequestButton);
holder._rejectButton = convertView.findViewById(R.id.RejectRequestButton);
holder._rejectButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext, holder._rejectButton.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
holder.acceptButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(mContext, holder.acceptButton.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
convertView.setTag(holder);
}
else{
holder=(ViewHolder)convertView.getTag();
}
holder._bookingTime.setText(getItem(position).getBookingTime());
if(!getItem(position).getUserName().equals("")){
holder._userNameTextView.setText(getItem(position).getUserName());
}
if(!getItem(position).getRating().equals("")){
holder._ratingTextView.setText(getItem(position).getRating());
}
return convertView;
}
}
ListView in Main xml:
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:id="@+id/AllRequestListView">
</ListView>
Resource Layout for list view requestlayout.xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/requestLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/bookingTime"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/bookingTime"
android:text="Temp Name"
android:id="@+id/userName"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/userName"
android:text="No Rating"
android:id="@+id/rating"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/AcceptRequestButton"
android:focusable="false"
android:layout_below="@+id/rating"
android:text="Accept"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/RejectRequestButton"
android:layout_below="@+id/AcceptRequestButton"
android:focusable="false"
android:text="Reject"
/>
</RelativeLayout>
Expanding on zoul's answer:
If you want to setup Vim to use specific settings when editing a particular filetype, you'll want to use autocommands:
autocmd Filetype css setlocal tabstop=4
This will make it so that tabs are displayed as 4 spaces. Setting expandtab
will cause Vim to actually insert spaces (the number of them being controlled by tabstop
) when you press tab; you might want to use softtabstop
to make backspace work properly (that is, reduce indentation when that's what would happen should tabs be used, rather than always delete one char at a time).
To make a fully educated decision as to how to set things up, you'll need to read Vim docs on tabstop
, shiftwidth
, softtabstop
and expandtab
. The most interesting bit is found under expandtab
(:help 'expandtab
):
There are four main ways to use tabs in Vim:
Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4 (or 3 or whatever you prefer) and use 'noexpandtab'. Then Vim will use a mix of tabs and spaces, but typing and will behave like a tab appears every 4 (or 3) characters.
Set 'tabstop' and 'shiftwidth' to whatever you prefer and use 'expandtab'. This way you will always insert spaces. The formatting will never be messed up when 'tabstop' is changed.
Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a |modeline| to set these values when editing the file again. Only works when using Vim to edit the file.
Always set 'tabstop' and 'shiftwidth' to the same value, and 'noexpandtab'. This should then work (for initial indents only) for any tabstop setting that people use. It might be nice to have tabs after the first non-blank inserted as spaces if you do this though. Otherwise aligned comments will be wrong when 'tabstop' is changed.
You can also do it this way to reference the previous branch implicitly:
git checkout mainline
git pull
git merge -
git push
I can't get it to work on $.get()
because it has no complete
event.
I suggest to use $.ajax()
like this,
$.ajax({
url: 'http://www.example.org',
data: {'a':1,'b':2,'c':3},
dataType: 'xml',
complete : function(){
alert(this.url)
},
success: function(xml){
}
});
This is not an Xcode bug, though the warning message is not helpful enough to describe the real cause.
This error message occurs when you have several files in your project that have the same name. You just have to delete or rename the files with duplicate names and the problem is solved.
Assuming that you've downloaded and installed Tomcat as Windows Service Installer exe file from the Tomcat homepage, then check the Apache feather icon in the systray (or when absent, run Monitor Tomcat from the start menu). Doubleclick the feather icon and go to the Java tab. There you can configure the memory.
Restart the service to let the changes take effect.
check this Twig Reference.
You can do it that simple:
{% if (a or b) %}
...
{% endif %}
I'll throw this in as an alternative just for the heck of it, even though it's pretty much useless when compared to " ".join(my_list)
for strings. For non-strings (such as an array of ints) this may be better:
" ".join(str(item) for item in my_list)
- What is the most typical/common way of doing this with an object C++ (that doesn't involve overloading the == operator)?
- Is this even the right approach? ie. should I not write functions that take an object as an argument, but rather, write member functions? (But even if so, please answer the original question.)
No, references cannot be null (unless Undefined Behavior has already happened, in which case all bets are already off). Whether you should write a method or non-method depends on other factors.
- Between a function that takes a reference to an object, or a function that takes a C-style pointer to an object, are there reasons to choose one over the other?
If you need to represent "no object", then pass a pointer to the function, and let that pointer be NULL:
int silly_sum(int const* pa=0, int const* pb=0, int const* pc=0) {
/* Take up to three ints and return the sum of any supplied values.
Pass null pointers for "not supplied".
This is NOT an example of good code.
*/
if (!pa && (pb || pc)) return silly_sum(pb, pc);
if (!pb && pc) return silly_sum(pa, pc);
if (pc) return silly_sum(pa, pb) + *pc;
if (pa && pb) return *pa + *pb;
if (pa) return *pa;
if (pb) return *pb;
return 0;
}
int main() {
int a = 1, b = 2, c = 3;
cout << silly_sum(&a, &b, &c) << '\n';
cout << silly_sum(&a, &b) << '\n';
cout << silly_sum(&a) << '\n';
cout << silly_sum(0, &b, &c) << '\n';
cout << silly_sum(&a, 0, &c) << '\n';
cout << silly_sum(0, 0, &c) << '\n';
return 0;
}
If "no object" never needs to be represented, then references work fine. In fact, operator overloads are much simpler because they take overloads.
You can use something like boost::optional.
A working example:
$qb = $this->createQueryBuilder('a');
$query=$qb->getQuery();
// SHOW SQL:
echo $query->getSQL();
// Show Parameters:
echo $query->getParameters();
SELECT contendernum,totals, RANK() OVER (ORDER BY totals ASC) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
GROUP BY ContenderNum
) AS a
I'm surprised there is not some single formatter that returns a default (and safe) 'for appending in filename' - format of the time,
We could simply write FD.write('mybackup'+time.strftime('%(formatter here)') + 'ext'
"%x" instead of "%Y%m%d-%H%M%S"
if you want to populate a table in SQL SERVER you can use while statement as follows:
declare @llenandoTabla INT = 0;
while @llenandoTabla < 10000
begin
insert into employeestable // Name of my table
(ID, FIRSTNAME, LASTNAME, GENDER, SALARY) // Parameters of my table
VALUES
(555, 'isaias', 'perez', 'male', '12220') //values
set @llenandoTabla = @llenandoTabla + 1;
end
Hope it helps.
I see that you tagged this with Ubuntu. Most likely the MySQL driver (and possibly MySQL) is not installed. Assuming you have SSH or terminal access and sudo permissions, log into the server and run this:
sudo apt-get install mysql-server mysql-client php5-mysql
If the MySQL packages or the php5-mysql package are already installed, this will update them.
UPDATE
Since this answer still gets the occasional click I am going to update it to include PHP 7. PHP 7 requires a different package for MySQL so you will want to use a different argument for the apt-get command.
# Replace 7.4 with your version of PHP
sudo apt-get install mysql-server mysql-common php7.4 php7.4-mysql
And importantly, mysql_connect()
has been deprecated since PHP v5.5.0. Refer the official documentation here: PHP: mysql_connect()
No doubt that NLTK is the most suitable for the purpose. But getting started with NLTK is quite painful (But once you install it - you just reap the rewards)
So here is simple re based code available at http://pythonicprose.blogspot.com/2009/09/python-split-paragraph-into-sentences.html
# split up a paragraph into sentences
# using regular expressions
def splitParagraphIntoSentences(paragraph):
''' break a paragraph into sentences
and return a list '''
import re
# to split by multile characters
# regular expressions are easiest (and fastest)
sentenceEnders = re.compile('[.!?]')
sentenceList = sentenceEnders.split(paragraph)
return sentenceList
if __name__ == '__main__':
p = """This is a sentence. This is an excited sentence! And do you think this is a question?"""
sentences = splitParagraphIntoSentences(p)
for s in sentences:
print s.strip()
#output:
# This is a sentence
# This is an excited sentence
# And do you think this is a question
Old question, but here's a fairly clean way to create a nullable parameter:
new SqlParameter("@note", (object) request.Body ?? DBNull.Value);
If request.Body has a value, then it's value is used. If it's null, then DbNull.Value is used.
I had to go look for ojdbc compatible with version on oracle that was installed this fixed my problem, my bad was thinking one ojdbc would work for all
Try this
@font-face { _x000D_
src: url(fonts/Market_vilis.ttf) format("truetype");_x000D_
}_x000D_
div.FontMarket { _x000D_
font-family: Market Deco;_x000D_
}
_x000D_
<div class="FontMarket">KhonKaen Market</div>
_x000D_
vilis.org
You shouldn't use money when you need to do multiplications / divisions on the value. Money is stored in the same way an integer is stored, whereas decimal is stored as a decimal point and decimal digits. This means that money will drop accuracy in most cases, while decimal will only do so when converted back to its original scale. Money is fixed point, so its scale doesn't change during calculations. However because it is fixed point when it gets printed as a decimal string (as opposed to as a fixed position in a base 2 string), values up to the scale of 4 are represented exactly. So for addition and subtraction, money is fine.
A decimal is represented in base 10 internally, and thus the position of the decimal point is also based on the base 10 number. Which makes its fractional part represent its value exactly, just like with money. The difference is that intermediate values of decimal can maintain precision up to 38 digits.
With a floating point number, the value is stored in binary as if it were an integer, and the decimal (or binary, ahem) point's position is relative to the bits representing the number. Because it is a binary decimal point, base 10 numbers lose precision right after the decimal point. 1/5th, or 0.2, cannot be represented precisely in this way. Neither money nor decimal suffer from this limitation.
It is easy enough to convert money to decimal, perform the calculations, and then store the resulting value back into a money field or variable.
From my POV, I want stuff that happens to numbers to just happen without having to give too much thought to them. If all calculations are going to get converted to decimal, then to me I'd just want to use decimal. I'd save the money field for display purposes.
Size-wise I don't see enough of a difference to change my mind. Money takes 4 - 8 bytes, whereas decimal can be 5, 9, 13, and 17. The 9 bytes can cover the entire range that the 8 bytes of money can. Index-wise (comparing and searching should be comparable).
This is easy to fix.
Run > Debug Configurations
and edit the setting. Run > Edit Configurations
select Run default Activity and it will no longer save the setting in this fashion.Don't pass db models directly to your views. You're lucky enough to be using MVC, so encapsulate using view models.
Create a view model class like this:
public class EmployeeAddViewModel
{
public Employee employee { get; set; }
public Dictionary<int, string> staffTypes { get; set; }
// really? a 1-to-many for genders
public Dictionary<int, string> genderTypes { get; set; }
public EmployeeAddViewModel() { }
public EmployeeAddViewModel(int id)
{
employee = someEntityContext.Employees
.Where(e => e.ID == id).SingleOrDefault();
// instantiate your dictionaries
foreach(var staffType in someEntityContext.StaffTypes)
{
staffTypes.Add(staffType.ID, staffType.Type);
}
// repeat similar loop for gender types
}
}
Controller:
[HttpGet]
public ActionResult Add()
{
return View(new EmployeeAddViewModel());
}
[HttpPost]
public ActionResult Add(EmployeeAddViewModel vm)
{
if(ModelState.IsValid)
{
Employee.Add(vm.Employee);
return View("Index"); // or wherever you go after successful add
}
return View(vm);
}
Then, finally in your view (which you can use Visual Studio to scaffold it first), change the inherited type to ShadowVenue.Models.EmployeeAddViewModel. Also, where the drop down lists go, use:
@Html.DropDownListFor(model => model.employee.staffTypeID,
new SelectList(model.staffTypes, "ID", "Type"))
and similarly for the gender dropdown
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(model.genderTypes, "ID", "Gender"))
Update per comments
For gender, you could also do this if you can be without the genderTypes in the above suggested view model (though, on second thought, maybe I'd generate this server side in the view model as IEnumerable). So, in place of new SelectList...
below, you would use your IEnumerable.
@Html.DropDownListFor(model => model.employee.genderID,
new SelectList(new SelectList()
{
new { ID = 1, Gender = "Male" },
new { ID = 2, Gender = "Female" }
}, "ID", "Gender"))
Finally, another option is a Lookup table. Basically, you keep key-value pairs associated with a Lookup type. One example of a type may be gender, while another may be State, etc. I like to structure mine like this:
ID | LookupType | LookupKey | LookupValue | LookupDescription | Active
1 | Gender | 1 | Male | male gender | 1
2 | State | 50 | Hawaii | 50th state | 1
3 | Gender | 2 | Female | female gender | 1
4 | State | 49 | Alaska | 49th state | 1
5 | OrderType | 1 | Web | online order | 1
I like to use these tables when a set of data doesn't change very often, but still needs to be enumerated from time to time.
Hope this helps!
jQuery 3
As of jQuery 3, removeAttr
does not set the corresponding property to false
anymore:
Prior to jQuery 3.0, using
.removeAttr()
on a boolean attribute such aschecked
,selected
, orreadonly
would also set the corresponding named property tofalse
. This behavior was required for ancient versions of Internet Explorer but is not correct for modern browsers because the attribute represents the initial value and the property represents the current (dynamic) value.It is almost always a mistake to use
.removeAttr( "checked" )
on a DOM element. The only time it might be useful is if the DOM is later going to be serialized back to an HTML string. In all other cases,.prop( "checked", false )
should be used instead.
Hence only .prop('checked',false)
is correct way when using this version.
Original answer (from 2011):
For attributes which have underlying boolean properties (of which checked
is one), removeAttr
automatically sets the underlying property to false
. (Note that this is among the backwards-compatibility "fixes" added in jQuery 1.6.1).
So, either will work... but the second example you gave (using prop
) is the more correct of the two. If your goal is to uncheck the checkbox, you really do want to affect the property, not the attribute, and there's no need to go through removeAttr
to do that.
Umbrello UML Modeller is a Unified Modelling Language diagram programme for KDE. UML allows you to create diagrams of software and other systems in a standard format. Our handbook gives a good introduction to Umbrello and UML modelling. http://uml.sourceforge.net/
There are some problems when logical vector contains NA
values.
See for example:
z <- c(TRUE, FALSE, NA)
sum(z) # gives you NA
table(z)["TRUE"] # gives you 1
length(z[z == TRUE]) # f3lix answer, gives you 2 (because NA indexing returns values)
So I think the safest is to use na.rm = TRUE
:
sum(z, na.rm = TRUE) # best way to count TRUE values
(which gives 1). I think that table
solution is less efficient (look at the code of table
function).
Also, you should be careful with the "table" solution, in case there are no TRUE values in the logical vector. Suppose z <- c(NA, FALSE, NA)
or simply z <- c(FALSE, FALSE)
, then table(z)["TRUE"]
gives you NA
for both cases.
By default, on Linux, Pip installs packages to /usr/local/lib/python2.7/dist-packages.
Using virtualenv or --user during install will change this default location. If you use pip show
make sure you are using the right user or else pip
may not see the packages you are referencing.
Doing it in one bulk read:
import re
textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)
Line by line:
import re
textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += reg.findall(line)
textfile.close()
But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:
import re
textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
matches += [(reg.findall(line),offset)]
offset += len(line)
textfile.close()
But it still just makes more sense to read the whole file in at once.
From 5.2.2/2 (character display semantics) :
\b
(backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.
\n
(new line) Moves the active position to the initial position of the next line.
\r
(carriage return) Moves the active position to the initial position of the current line.
Here, your code produces :
<new_line>ab
\b
: back one charactersi
: overrides the b
with s
(producing asi
on the second line)\r
: back at the beginning of the current lineha
: overrides the first two characters (producing hai
on the second line)In the end, the output is :
\nhai
I was able to get this to work by using the Invoke-Expression
cmdlet.
Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"
@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy()
(or .values
for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.
For example, you can use ndarray.max()
along the first axis.
# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
A B
0 1 -2
1 2 8
2 3 1
df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns,
# df['C'] = df.values.max(1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
If your data has NaN
s, you will need numpy.nanmax
:
df['C'] = np.nanmax(df.values, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
You can also use numpy.maximum.reduce
. numpy.maximum
is a ufunc (Universal Function), and every ufunc has a reduce
:
df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df
A B C
0 1 -2 1
1 2 8 8
2 3 1 3
np.maximum.reduce
and np.max
appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max
. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).
The graph was generated using perfplot. Benchmarking code, for reference:
import pandas as pd
import perfplot
np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))
perfplot.show(
setup=lambda n: pd.concat([df_] * n, ignore_index=True),
kernels=[
lambda df: df.assign(new=df.max(axis=1)),
lambda df: df.assign(new=df.values.max(1)),
lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
],
labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
n_range=[2**k for k in range(0, 15)],
xlabel='N (* len(df))',
logx=True,
logy=True)
To make multiple checking statements more readable (and avoid nested ifs):
var tmp = 'Test[[email protected]]';
var posStartEmail = undefined;
var posEndEmail = undefined;
var email = undefined;
do {
if (tmp.toLowerCase().substring(0,4) !== 'test') { break; }
posStartEmail = tmp.toLowerCase().substring(4).indexOf('[');
posEndEmail = tmp.toLowerCase().substring(4).indexOf(']');
if (posStartEmail === -1 || posEndEmail === -1) { break; }
email = tmp.substring(posStartEmail+1+4,posEndEmail);
if (email.indexOf('@') === -1) { break; }
// all checks are done - do what you intend to do
alert ('All checks are ok')
break; // the most important break of them all
} while(true);
This is a briefer variation of the accepted answer: the function below extracts the bits from-to inclusive by creating a bitmask. After applying an AND logic over the original number the result is shifted so the function returns just the extracted bits. Skipped index/integrity checks for clarity.
uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to)
{
unsigned mask = ( (1<<(to-from+1))-1) << from;
return (orig16BitWord & mask) >> from;
}
You are using a forward declaration for the type MainWindowClass
. That's fine, but it also means that you can only declare a pointer or reference to that type. Otherwise the compiler has no idea how to allocate the parent object as it doesn't know the size of the forward declared type (or if it actually has a parameterless constructor, etc.)
So, you either want:
// forward declaration, details unknown
class A;
class B {
A *a; // pointer to A, ok
};
Or, if you can't use a pointer or reference....
// declaration of A
#include "A.h"
class B {
A a; // ok, declaration of A is known
};
At some point, the compiler needs to know the details of A
.
If you are only storing a pointer to A
then it doesn't need those details when you declare B
. It needs them at some point (whenever you actually dereference the pointer to A
), which will likely be in the implementation file, where you will need to include the header which contains the declaration of the class A
.
// B.h
// header file
// forward declaration, details unknown
class A;
class B {
public:
void foo();
private:
A *a; // pointer to A, ok
};
// B.cpp
// implementation file
#include "B.h"
#include "A.h" // declaration of A
B::foo() {
// here we need to know the declaration of A
a->whatever();
}
I find the most readable way to express this is using a sql expression:
df.filter("my_date < date'2015-01-01'")
we can verify this works correctly by looking at the physical plan from .explain()
+- *(1) Filter (isnotnull(my_date#22) && (my_date#22 < 16436))
static int[] getIndex(int[] data, int number) {
int[] positions = new int[data.length];
if (data.length > 0) {
int counter = 0;
for(int i =0; i < data.length; i++) {
if(data[i] == number){
positions[counter] = i;
counter++;
}
}
}
return positions;
}
It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.
4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.
If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.
For Ubuntu Users, the code_editor.xml
is in
/usr/share/mysql-workbench/data
edit as you need, In Ubuntu which is a must need, some default used colours lacks contrast and it is unable to read, For a quick workaround you can also use this solution.
Visit this repo to get the full XML file.
Edit (oct 2017):
background-clip
or ratherbackground-image options
are now supported by every major browser: CanIUse
Yes, you can do this with only one character and only CSS.
Webkit (and Chrome) only, though:
h1 {_x000D_
display: inline-block;_x000D_
margin: 0; /* for demo snippet */_x000D_
line-height: 1em; /* for demo snippet */_x000D_
font-family: helvetica, arial, sans-serif;_x000D_
font-weight: bold;_x000D_
font-size: 300px;_x000D_
background: linear-gradient(to right, #7db9e8 50%,#1e5799 50%);_x000D_
-webkit-background-clip: text;_x000D_
-webkit-text-fill-color: transparent;_x000D_
}
_x000D_
<h1>X</h1>
_x000D_
Visually, all the examples that use two characters (be it via JS, CSS pseudo elements, or just HTML) look fine, but note that that all adds content to the DOM which may cause accessibility--as well as text selection/cut/paste issues.
Stream operations flatMap
and map
accept a function as input.
flatMap
expects the function to return a new stream for each element of the stream and returns a stream which combines all the elements of the streams returned by the function for each element. In other words, with flatMap
, for each element from the source, multiple elements will be created by the function. http://www.zoftino.com/java-stream-examples#flatmap-operation
map
expects the function to return a transformed value and returns a new stream containing the transformed elements. In other words, with map
, for each element from the source, one transformed element will be created by the function.
http://www.zoftino.com/java-stream-examples#map-operation
In modern browsers you can do:
.reMode_hover:not(.reMode_selected):hover{}
Consult http://caniuse.com/css-sel3 for compatibility information.
public class OddEvenPrinetr {
private static Object printOdd = new Object();
public static void main(String[] args) {
Runnable oddPrinter = new Runnable() {
int count = 1;
@Override
public void run() {
while(true){
synchronized (printOdd) {
if(count >= 101){
printOdd.notify();
return;
}
System.out.println(count);
count = count + 2;
try {
printOdd.notify();
printOdd.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
Runnable evenPrinter = new Runnable() {
int count = 0;
@Override
public void run() {
while(true){
synchronized (printOdd) {
printOdd.notify();
if(count >= 100){
return;
}
count = count + 2;
System.out.println(count);
printOdd.notify();
try {
printOdd.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
new Thread(oddPrinter).start();
new Thread(evenPrinter).start();
}
}
You need to type result
to an array of string const result: string[] = [];
.
$<input name="currency">
See also: Restricting input to textbox: allowing only numbers and decimal point
As Tmdean correctly pointed out you can use the Mid()
function. The MSDN Library also has a great reference section on VBScript which you can find here:
The following bash script returns the Name of your current ec2 instance (the value of the "Name" tag). Modify TAG_NAME to your specific case.
TAG_NAME="Name"
INSTANCE_ID="`wget -qO- http://instance-data/latest/meta-data/instance-id`"
REGION="`wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"
TAG_VALUE="`aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=$TAG_NAME" --region $REGION --output=text | cut -f5`"
To install the aws cli
sudo apt-get install python-pip -y
sudo pip install awscli
In case you use IAM instead of explicit credentials, use these IAM permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [ "ec2:DescribeTags"],
"Resource": ["*"]
}
]
}
Following solution worked for me. When connecting to the db, specify that data should be truncated if they are too long (jdbcCompliantTruncation). My link looks like this:
jdbc:mysql://SERVER:PORT_NO/SCHEMA?sessionVariables=sql_mode='NO_ENGINE_SUBSTITUTION'&jdbcCompliantTruncation=false
If you increase the size of the strings, you may face the same problem in future if the string you are attempting to store into the DB is longer than the new size.
EDIT: STRICT_TRANS_TABLES has to be removed from sql_mode as well.
You can't return because you're not in a function. You can exit
though.
import sys
sys.exit(0)
0 (the default) means success, non-zero means failure.
Try simple code, to convert DataTable to excel file as csv:
var lines = new List<string>();
string[] columnNames = dataTable.Columns
.Cast<DataColumn>()
.Select(column => column.ColumnName)
.ToArray();
var header = string.Join(",", columnNames.Select(name => $"\"{name}\""));
lines.Add(header);
var valueLines = dataTable.AsEnumerable()
.Select(row => string.Join(",", row.ItemArray.Select(val => $"\"{val}\"")));
lines.AddRange(valueLines);
File.WriteAllLines("excel.csv", lines);
This will write a new file excel.csv
into the current working directory which is generally either where the .exe is or where you launch it from.
There are really two dimensions to the scripting vs program reality:
Is the language powerful enough, particularly with string operations, to compete with a macro processor like the posix shell and particularly bash? If it isn't better than bash for running some function there isn't much point in using it.
Is the language convenient and quickly started? Java, Scala, JRuby, Closure and Groovy are all powerful languages, but Java requires a lot of boilerplate and the JVM they all require just takes too long to start up.
OTOH, Perl, Python, and Ruby all start up quickly and have powerful string handling (and pretty much everything-else-handling) operations, so they tend to occupy the sometimes-disparaged-but-not-easily-encroached-upon "scripting" world. It turns out they do well at running entire traditional programs as well.
Left in limbo are languages like Javascript, which aren't used for scripting but potentially could be. Update: since this was written node.js was released on multiple platforms. In other news, the question was closed. "Oh well."
You may see this error when you have added a new file to your code and you're now trying to commit the code without staging(adding) it.
To overcome this, you may first add the file by using git add (git add your_file_name.py
) and then committing the changes (git commit -m "Rename Files" -m "Sample script to rename files as you like"
)
Another way to do it in async function :
const express = require('express')
const path = require('path')
const db = require(path.join(__dirname, '../database/config')).db;
const router = express.Router()
// Create.R.U.D
router.post('/new-order', async function (req, res, next) {
// security check
if (Object.keys(req.body).length === 0) {
res.status(404).send({
msg: "Error",
code: 404
});
return;
}
try {
// operations
let orderNumber = await db.collection('orders').countDocuments()
let number = orderNumber + 1
let order = {
number: number,
customer: req.body.customer,
products: req.body.products,
totalProducts: req.body.totalProducts,
totalCost: req.body.totalCost,
type: req.body.type,
time: req.body.time,
date: req.body.date,
timeStamp: Date.now(),
}
if (req.body.direction) {
order.direction = req.body.direction
}
if (req.body.specialRequests) {
order.specialRequests = req.body.specialRequests
}
// Here newOrder will store some informations in result of this process.
// You can find the inserted id and some informations there too.
let newOrder = await db.collection('orders').insertOne({...order})
if (newOrder) {
// MARK: Server response
res.status(201).send({
msg: `Order N°${number} created : id[${newOrder.insertedId}]`,
code: 201
});
} else {
// MARK: Server response
res.status(404).send({
msg: `Order N°${number} not created`,
code: 404
});
}
} catch (e) {
print(e)
return
}
})
// C.Read.U.D
// C.R.Update.D
// C.R.U.Delete
module.exports = router;
I managed to fix it finally. The problem is not related to HikariCP.
The problem persisted because of some complex methods in REST controllers executing multiple changes in DB through JPA repositories. For some reasons calls to these interfaces resulted in a growing number of "freezed" active connections, exhausting the pool. Either annotating these methods as @Transactional
or enveloping all the logic in a single call to transactional service method seem to solve the problem.
From Apple iOS7 transition Guide,
Specifically,
self.automaticallyAdjustsScrollViewInsets = YES;
self.edgesForExtendedLayout = UIRectEdgeNone;
works for me when I don't want to overlap and I have a UITableViewController.
You could use table
, i.e.
n_occur <- data.frame(table(vocabulary$id))
gives you a data frame with a list of id
s and the number of times they occurred.
n_occur[n_occur$Freq > 1,]
tells you which id
s occurred more than once.
vocabulary[vocabulary$id %in% n_occur$Var1[n_occur$Freq > 1],]
returns the records with more than one occurrence.
input width is 10 + 2 times 1 px for border
You can just validate your pipeline to find out syntax issues. Jenkis has nice API for Jenkisfile validation - https://jenkins_url/pipeline-model-converter/validate
Using curl and passing your .Jenkinsfile, you will get syntax check instantly
curl --user username:password -X POST -F "jenkinsfile=<jenkinsfile" https://jenkins_url/pipeline-model-converter/validate
You can add this workflow to editors:
To save the Log cat content to the file, you need to redirect to the android sdk's platform tools folder and hit the below command
adb logcat > logcat.txt
In Android Studio, version 3.6RC1, file will be created of the name "logcat.txt" in respective project folder. you can change the name according to your interest. enjoy
Its very simple. Just give the below command for listing all keyspaces.
Cqlsh> Describe keyspaces;
If you want to check the keyspace in the system schema using the SQL query
below is the command.
SELECT * FROM system_schema.keyspaces;
Hope this will answer your question...
You can go through the explanation on understanding and creating the keyspaces from below resources.
Documentation:
https://docs.datastax.com/en/cql/3.1/cql/cql_reference/create_keyspace_r.html https://www.i2tutorials.com/cassandra-tutorial/cassandra-create-keyspace/
True
is equal to 1
.
>>> sum([True, True, False, False, False, True])
3
This is the solution that worked for me
https://gist.github.com/elidickinson/5525752#gistcomment-1649300, thanks to @philipp-klinz
<table cellpadding="0" cellspacing="0" border="0" style="padding:0px;margin:0px;width:100%;">
<tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
<tr>
<td style="padding:0px;margin:0px;"> </td>
<td style="padding:0px;margin:0px;" width="560"><!-- max width goes here -->
<!-- PLACE CONTENT HERE -->
</td>
<td style="padding:0px;margin:0px;"> </td>
</tr>
<tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
</table>
It would help to have sample information about your output. Recursively using rbind
on bigger and bigger things is not recommended. My first guess at something that would help you:
z <- list(1:3,4:6,7:9)
do.call(rbind,z)
See a related question for more efficiency, if needed.