Go to: Settings
> Preferences
> Backup
> and Uncheck Remember current session for next launch
In older versions (6.5-), this option is located on Settings
> Preferences
> MISC
.
Any decent text editor has a search&replace facility that supports regular expressions.
If however, you have reason to reinvent the wheel in Java, you can do:
Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;
String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));
This only works for Java 7 or newer. If you are stuck on an older Java, you can do:
String content = IOUtils.toString(new FileInputStream(myfile), myencoding);
content = content.replaceAll(myPattern, myReplacement);
IOUtils.write(content, new FileOutputStream(myfile), myencoding);
In this case, you'll need to add error handling and close the streams after you are done with them.
IOUtils
is documented at http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html
For those who are still facing this issue try adding:
libxml_use_internal_errors(true);
before the loadHtml
call and add
libxml_use_internal_errors(false);
after the call.
This solved it for me.
For example Tomcat (default) expects:
spring.datasource.ourdb.url=...
and HikariCP will be happy with:
spring.datasource.ourdb.jdbc-url=...
We can satisfy both without boilerplate configuration:
spring.datasource.ourdb.jdbc-url=${spring.datasource.ourdb.url}
Take a look at source DataSourceBuilder.java
If Tomcat, HikariCP or Commons DBCP are on the classpath one of them will be selected (in that order with Tomcat first).
... so, we can easily replace connection pool provider using this maven configuration (pom.xml):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
</dependency>
Check out the ReadKey()
method on the System.Console
.NET class. I think that will do what you're looking for.
http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx
Example:
Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());
I think that equality is something that can be absolutely determined. The trouble with null
is that it's inherently unknown. Null
combined with any other value is null
- unknown. Asking SQL "Is my value equal to null
?" would be unknown every single time, even if the input is null
. I think the implementation of IS NULL
makes it clear.
There are a couple of things you could look at. Based on your question, it looks like the function owner is different from the table owner.
1) Grants via a role : In order to create stored procedures and functions on another user's objects, you need direct access to the objects (instead of access through a role).
2)
By default, stored procedures and SQL methods execute with the privileges of their owner, not their current user.
If you created a table in Schema A and the function in Schema B, you should take a look at Oracle's Invoker/Definer Rights concepts to understand what might be causing the issue.
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/subprograms.htm#LNPLS00809
Doesn't have to be; "64-bit machine" can mean many things, but typically means that the CPU has registers that big. The sizeof a type is determined by the compiler, which doesn't have to have anything to do with the actual hardware (though it typically does); in fact, different compilers on the same machine can have different values for these.
request.args
is a MultiDict with the parsed contents of the query string.
From the documentation of get
method:
get(key, default=None, type=None)
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible.
This won't work. You first have to initialize the array. So far, you only have a String[] reference, pointing to null
.
When you try to read the length member, what you actually do is null.length
, which results in a NullPointerException.
readonly
can be initialized at declaration or get its value from the constructor only. Unlike const
it has to be initialized and declare at the same time.
readonly
has everything const
has, plus constructor initialization
using System;
class MainClass {
public static void Main (string[] args) {
Console.WriteLine(new Test().c);
Console.WriteLine(new Test("Constructor").c);
Console.WriteLine(new Test().ChangeC()); //Error A readonly field
// `MainClass.Test.c' cannot be assigned to (except in a constructor or a
// variable initializer)
}
public class Test {
public readonly string c = "Hello World";
public Test() {
}
public Test(string val) {
c = val;
}
public string ChangeC() {
c = "Method";
return c ;
}
}
}
You can get the scrollbar position using document.documentElement.scrollTop
. And then it is simply matter of comparing it to the previous position.
ALTER TABLE
can do multiple table alterations in one statement, but MODIFY COLUMN
can only work on one column at a time, so you need to specify MODIFY COLUMN
for each column you want to change:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100);
Also, note this warning from the manual:
When you use CHANGE or MODIFY,
column_definition
must include the data type and all attributes that should apply to the new column, other than index attributes such as PRIMARY KEY or UNIQUE. Attributes present in the original definition but not specified for the new definition are not carried forward.
EDIT (02 Jan 2012):
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
ORIGINAL
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser()
like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri
in onActivityResult()
like so:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath()
method in my FileUtils.java
is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
You can implement your own Iterator. Your iterator could be constructed to wrap the Iterator returned by the List, or you could keep a cursor and use the List's get(int index) method. You just have to add logic to your Iterator's next method AND the hasNext method to take into account your filtering criteria. You will also have to decide if your iterator will support the remove operation.
This is a problem still as of 7.2.1 . Create a library cause you do not know what it will do if you make it an application & you are screwed.
Did find how to fix this though. Edit nbproject/project.properties
, change the following line to false as shown:
mkdist.disabled=false
After this you can change the main class in properties and it will be reflected in manifest.
I'm using this code, pretty good. You will very easy to know user-agents visitted your site. This code is opening a file and write the user_agent down the file. You can check each day this file by go to yourdomain.com/useragent.txt
and know about new user_agents and put them in your condition of if clause.
$user_agent = strtolower($_SERVER['HTTP_USER_AGENT']);
if(!preg_match("/Googlebot|MJ12bot|yandexbot/i", $user_agent)){
// if not meet the conditions then
// do what you need
// here open a file and write the user_agent down the file. You can check each day this file useragent.txt and know about new user_agents and put them in your condition of if clause
if($user_agent!=""){
$myfile = fopen("useragent.txt", "a") or die("Unable to open file useragent.txt!");
fwrite($myfile, $user_agent);
$user_agent = "\n";
fwrite($myfile, $user_agent);
fclose($myfile);
}
}
This is the content of useragent.txt
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (compatible; MJ12bot/v1.4.6; http://mj12bot.com/)Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (compatible; yandexbot/3.0; +http://yandex.com/bots)
mozilla/5.0 (iphone; cpu iphone os 9_3 like mac os x) applewebkit/601.1.46 (khtml, like gecko) version/9.0 mobile/13e198 safari/601.1
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; linkdexbot/2.2; +http://www.linkdex.com/bots/)
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64; rv:49.0) gecko/20100101 firefox/49.0
mozilla/5.0 (windows nt 6.1; wow64; rv:33.0) gecko/20100101 firefox/33.0
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.36 (khtml, like gecko) chrome/53.0.2785.143 safari/537.36
mozilla/5.0 (compatible; baiduspider/2.0; +http://www.baidu.com/search/spider.html)
zoombot (linkbot 1.0 http://suite.seozoom.it/bot.html)
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
sogou web spider/4.0(+http://www.sogou.com/docs/help/webmasters.htm#07)
mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/44.0.2403.155 safari/537.36 opr/31.0.1889.174
Thanks to @nekno and @ale84 for great answers.
However, I modified @ale84's script it little to increment build numbers for floating point.
the value of incl can be changed according to your floating format requirements. For eg: if incl = .01, output format would be ... 1.19, 1.20, 1.21 ...
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
incl=.01
buildNumber=`echo $buildNumber + $incl|bc`
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"
Reversed order digit extractor (eg. for 23 will be 3 and 2):
while (number > 0)
{
int digit = number%10;
number /= 10;
//print digit
}
Normal order digit extractor (eg. for 23 will be 2 and 3):
std::stack<int> sd;
while (number > 0)
{
int digit = number%10;
number /= 10;
sd.push(digit);
}
while (!sd.empty())
{
int digit = sd.top();
sd.pop();
//print digit
}
MS SQL Server has supported ANSI SQL FETCH FIRST
for many years now:
SELECT * FROM TABLE
ORDER BY ID DESC
OFFSET 0 ROWS FETCH FIRST 1 ROW ONLY
(Works with most modern databases.)
Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.
server {
listen 80;
server_name localhost;
access_log logs/localhost.access.log main;
location / {
root /var/www/board/public;
index index.html index.htm index.php;
}
}
You can actually add a key pair through the elastic beanstalk config page. it then restarts your instance for you and everything works.
In general, you must have a file handle before opening the stream. You have a fileOutputStream handle before createNewFile() in the else block. The stream does not create the file if it doesn't exist.
Not really android specific, but that's a lot IO for this purpose. What if you do many "write" operations one after another? You will be reading the entire contents and writing the entire contents, taking time, and more importantly, battery life.
I suggest using java.io.RandomAccessFile, seek()'ing to the end, then writeChars() to append. It will be much cleaner code and likely much faster.
yes you can use
<property name="hbm2ddl.auto" value="create"/>
A simple trick that works for me is the following:
Example:
import matplotlib.pyplot as plt
plt.imshow(add_something)
plt.xlabel("x")
plt.ylabel("y")
plt.show(block=False)
#more code here (e.g. do calculations and use print to see them on the screen
plt.show()
Note: plt.show()
is the last line of my script.
u can rename the class as classA.mm and add C++ features in it.
Not directly. But you can use extensions such as LESS to help you achieve the same.
Using ng-selected for selected value. I Have successfully implemented code in AngularJS v1.3.2
<select ng-model="objBillingAddress.StateId" >_x000D_
<option data-ng-repeat="c in States" value="{{c.StateId}}" ng-selected="objBillingAddress.BillingStateId==c.StateId">{{c.StateName}}</option>_x000D_
</select>
_x000D_
It should be this way:
h2.myClass
looks for h2 with class myClass
. But you actually want to apply style for h2 inside .myClass
so you can use descendant selector .myClass h2
.
h2 {
color: red;
}
.myClass {
color: green;
}
.myClass h2 {
color: blue;
}
This ref will give you some basic idea about the selectors and have a look at descendant selectors
Simple Definition
SRC : (Source). To specify the origin of (a communication); document:
HREF : (Hypertext Reference). A reference or link to another page, document...
From the site Enrique posted:
window.history.forward(1);
document.attachEvent("onkeydown", my_onkeydown_handler);
function my_onkeydown_handler() {
switch (event.keyCode) {
case 116 : // 'F5'
event.returnValue = false;
event.keyCode = 0;
window.status = "We have disabled F5";
break;
}
}
SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.
For more detail you can refer the link.
A worked, completed and simple example:
package io.github.baijifeilong.excel;
import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
/**
* Created by [email protected] at 2019/12/6 11:41
*/
public class ExcelBoldTextDemo {
@SneakyThrows
public static void main(String[] args) {
new XSSFWorkbook() {{
XSSFRow row = createSheet().createRow(0);
row.setRowStyle(createCellStyle());
row.getRowStyle().getFont().setBold(true);
row.createCell(0).setCellValue("Alpha");
row.createCell(1).setCellValue("Beta");
row.createCell(2).setCellValue("Gamma");
}}.write(new FileOutputStream("demo.xlsx"));
}
}
This one worked for me:
df=df.sort_values(by=[2])
Whereas:
df=df.sort_values(by=['2'])
is not working.
If you want to close a buffer without destroying your window layout (current layout based on splits), you can use a Plugin like bbye. Based on this, you can just use
:Bdelete (instead of :bdelete)
:Bwipeout (instead of :bwipeout)
Or just create a mapping in your .vimrc
for easier access like
:nnoremap <Leader>q :Bdelete<CR>
From the plugin's documentation:
- Close and remove the buffer.
- Show another file in that window.
- Show an empty file if you've got no other files open.
- Do not leave useless [no file] buffers if you decide to edit another file in that window.
- Work even if a file's open in multiple windows.
- Work a-okay with various buffer explorers and tabbars.
From the plugin's documentation:
Vim has two commands for closing a buffer:
:bdelete
and:bwipeout
. The former removes the file from the buffer list, clears its options, variables and mappings. However, it remains in the jumplist, soCtrl-o
takes you back and reopens the file. If that's not what you want, use:bwipeout
or Bbye's equivalent:Bwipeout
where you would've used:bdelete
.
Yes, you can by using DBlink (postgresql only) and DBI-Link (allows foreign cross database queriers) and TDS_LInk which allows queries to be run against MS SQL server.
I have used DB-Link and TDS-link before with great success.
You could develop a web application with .NET Core and MVC and encapsulate it in a Windows universal JavaScript app: Progressive Web Apps on Windows
It is still a web application, but it's a very lightweight way to transform a web application into a desktop app without learning a new framework or/and redevelop the UI, and it works great.
The inconvenience is unlike Electron or ReactXP for example, the result is a universal Windows application and not a cross platform desktop application.
Ta da:
NSInteger myInteger = 42;
int myInt = (int) myInteger;
NSInteger
is nothing more than a 32/64 bit int. (it will use the appropriate size based on what OS/platform you're running)
I'm no expert in Typescript, but I think the main problem is the way of accessing data. Seeing how you described your Images
interface, you can define any key as a String.
When accessing a property, the "dot" syntax (images.main
) supposes, I think, that it already exists. I had such problems without Typescript, in "vanilla" Javascript, where I tried to access data as:
return json.property[0].index
where index was a variable. But it interpreted index
, resulting in a:
cannot find property "index" of json.property[0]
And I had to find a workaround using your syntax:
return json.property[0][index]
It may be your only option there. But, once again, I'm no Typescript expert, if anyone knows a better solution / explaination about what happens, feel free to correct me.
Task.WaitAll
blocks the current thread until everything has completed.
Task.WhenAll
returns a task which represents the action of waiting until everything has completed.
That means that from an async method, you can use:
await Task.WhenAll(tasks);
... which means your method will continue when everything's completed, but you won't tie up a thread to just hang around until that time.
That is very weird. I checked the CheckBox documentation page which reads
<asp:CheckBox id="CheckBox1"
AutoPostBack="True|False"
Text="Label"
TextAlign="Right|Left"
Checked="True|False"
OnCheckedChanged="OnCheckedChangedMethod"
runat="server"/>
As you can see, there is no OnClick or OnClientClick attributes defined.
Keeping this in mind, I think this is what is happening.
When you do this,
<asp:CheckBox runat="server" OnClick="alert(this.checked);" />
ASP.NET doesn't modify the OnClick attribute and renders it as is on the browser. It would be rendered as:
<input type="checkbox" OnClick="alert(this.checked);" />
Obviously, a browser can understand 'OnClick' and puts an alert.
And in this scenario
<asp:CheckBox runat="server" OnClientClick="alert(this.checked);" />
Again, ASP.NET won't change the OnClientClick attribute and will render it as
<input type="checkbox" OnClientClick="alert(this.checked);" />
As browser won't understand OnClientClick nothing will happen. It also won't raise any error as it is just another attribute.
You can confirm above by looking at the rendered HTML.
And yes, this is not intuitive at all.
If it's not a literal, you have to use \\\\
so that you get \\
which means an escaped backslash.
That's because there are two representations. In the string representation of your regex, you have "\\\\"
, Which is what gets sent to the parser. The parser will see \\
which it interprets as a valid escaped-backslash (which matches a single backslash).
The kind of output you are seeing from your byte array ([B@405217f8
) is also an output for a zero length byte array (ie new byte[0]
). It looks like this string is a reference to the array rather than a description of the contents of the array like we might expect from a regular collection's toString()
method.
As with other respondents, I would point you to the String
constructors that accept a byte[]
parameter to construct a string from the contents of a byte array. You should be able to read raw bytes from a socket's InputStream
if you want to obtain bytes from a TCP connection.
If you have already read those bytes as a String
(using an InputStreamReader
), then, the string can be converted to bytes using the getBytes()
function. Be sure to pass in your desired character set to both the String constructor and getBytes()
functions, and this will only work if the byte data can be converted to characters by the InputStreamReader
.
If you want to deal with raw bytes you should really avoid using this stream reader layer.
I read all the posts here and realized that we may need a real life example. Why, actually, we have @property?
So, consider a Flask app where you use authentication system.
You declare a model User in models.py
:
class User(UserMixin, db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True)
username = db.Column(db.String(64), unique=True, index=True)
password_hash = db.Column(db.String(128))
...
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
In this code we've "hidden" attribute password
by using @property
which triggers AttributeError
assertion when you try to access it directly, while we used @property.setter to set the actual instance variable password_hash
.
Now in auth/views.py
we can instantiate a User with:
...
@auth.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
user = User(email=form.email.data,
username=form.username.data,
password=form.password.data)
db.session.add(user)
db.session.commit()
...
Notice attribute password
that comes from a registration form when a user fills the form. Password confirmation happens on the front end with EqualTo('password', message='Passwords must match')
(in case if you are wondering, but it's a different topic related Flask forms).
I hope this example will be useful
Of course @Stephan202 has given a really nice answer. I am providing an alternative.
def compressx(min_index = 3, max_index = 6, x = ['a', 'b', 'c', 'd', 'e', 'f', 'g']):
x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
return x
compressx()
>>>['a', 'b', 'c', 'def', 'g']
You can also do the following.
x = x[:min_index] + [''.join(x[min_index:max_index])] + x[max_index:]
print(x)
>>>['a', 'b', 'c', 'def', 'g']
If you are using Toolbar try below code:
toolbar.setTitle("");
If you have a big list, It's better to use itertools and write a function to yield each part as needed:
from itertools import islice
def make_chunks(data, SIZE):
it = iter(data)
# use `xragne` if you are in python 2.7:
for i in range(0, len(data), SIZE):
yield [k for k in islice(it, SIZE)]
You can use this like:
A = [0, 1, 2, 3, 4, 5, 6]
size = len(A) // 2
for sample in make_chunks(A, size):
print(sample)
The output is:
[0, 1, 2]
[3, 4, 5]
[6]
Thanks to @thefourtheye and @Bede Constantinides
public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
JSONArray array;
@Override
protected JSONArray doInBackground(Void... params) {
try {
commonurl cu = new commonurl();
String u = cu.geturl("tempshowusermain.php");
URL url =new URL(u);
// URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
JSONObject jsonObject=new JSONObject();
jsonObject.put("lid",lid);
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
outputStream.write(jsonObject.toString().getBytes("UTF-8"));
int code = httpURLConnection.getResponseCode();
if (code == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
object = new JSONObject(stringBuffer.toString());
// array = new JSONArray(stringBuffer.toString());
array = object.getJSONArray("response");
}
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(JSONArray array) {
super.onPostExecute(array);
try {
for (int x = 0; x < array.length(); x++) {
object = array.getJSONObject(x);
ComonUserView commUserView=new ComonUserView();// commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
//pidArray.add(jsonObject2.getString("pid").toString());
commUserView.setLid(object.get("lid").toString());
commUserView.setUname(object.get("uname").toString());
commUserView.setAboutme(object.get("aboutme").toString());
commUserView.setHeight(object.get("height").toString());
commUserView.setAge(object.get("age").toString());
commUserView.setWeight(object.get("weight").toString());
commUserView.setBodytype(object.get("bodytype").toString());
commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
commUserView.setImagepath(object.get("imagepath").toString());
commUserView.setDistance(object.get("distance").toString());
commUserView.setLookingfor(object.get("lookingfor").toString());
commUserView.setStatus(object.get("status").toString());
cm.add(commUserView);
}
custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
gridusername.setAdapter(custuserprof);
// listusername.setAdapter(custuserprof);
} catch (Exception e) {
e.printStackTrace();
}
}
Do you mean these hex values?
.glyphicon-asterisk:before{content:"\2a";}
.glyphicon-plus:before{content:"\2b";}
.glyphicon-euro:before{content:"\20ac";}
...
You can find these in glyphicons.css
here:
http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css
(If you only want to know the Glyphicons classes: http://getbootstrap.com/components/#glyphicons)
The official tutorial discusses deploying an app to production. One option is to use Waitress, a production WSGI server. Other servers include Gunicorn and uWSGI.
When running publicly rather than in development, you should not use the built-in development server (
flask run
). The development server is provided by Werkzeug for convenience, but is not designed to be particularly efficient, stable, or secure.Instead, use a production WSGI server. For example, to use Waitress, first install it in the virtual environment:
$ pip install waitress
You need to tell Waitress about your application, but it doesn’t use
FLASK_APP
like flask run does. You need to tell it to import and call the application factory to get an application object.$ waitress-serve --call 'flaskr:create_app' Serving on http://0.0.0.0:8080
Or you can use waitress.serve()
in the code instead of using the CLI command.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "<h1>Hello!</h1>"
if __name__ == "__main__":
from waitress import serve
serve(app, host="0.0.0.0", port=8080)
$ python hello.py
For some reason you don't use jQuery nor ES6? This might help you:
var values = "Test,Prof,Off";_x000D_
var splitValues = values.split(',');_x000D_
var multi = document.getElementById('strings');_x000D_
_x000D_
multi.value = null; // Reset pre-selected options (just in case)_x000D_
var multiLen = multi.options.length;_x000D_
for (var i = 0; i < multiLen; i++) {_x000D_
if (splitValues.indexOf(multi.options[i].value) >= 0) {_x000D_
multi.options[i].selected = true;_x000D_
}_x000D_
}
_x000D_
<select name='strings' id="strings" multiple style="width:100px;">_x000D_
<option value="Test">Test</option>_x000D_
<option value="Prof">Prof</option>_x000D_
<option value="Live">Live</option>_x000D_
<option value="Off">Off</option>_x000D_
<option value="On" selected>On</option>_x000D_
</select>
_x000D_
Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.
import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
public class ReadDocFile
{
public static void main(String[] args)
{
File file = null;
WordExtractor extractor = null;
try
{
file = new File("c:\\New.doc");
FileInputStream fis = new FileInputStream(file.getAbsolutePath());
HWPFDocument document = new HWPFDocument(fis);
extractor = new WordExtractor(document);
String[] fileData = extractor.getParagraphText();
for (int i = 0; i < fileData.length; i++)
{
if (fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch (Exception exep)
{
exep.printStackTrace();
}
}
}
This expands on Paul's answer. In Pandas, indexing a DataFrame returns a reference to the initial DataFrame. Thus, changing the subset will change the initial DataFrame. Thus, you'd want to use the copy if you want to make sure the initial DataFrame shouldn't change. Consider the following code:
df = DataFrame({'x': [1,2]})
df_sub = df[0:1]
df_sub.x = -1
print(df)
You'll get:
x
0 -1
1 2
In contrast, the following leaves df unchanged:
df_sub_copy = df[0:1].copy()
df_sub_copy.x = -1
An improvement to the most useful answer here:
1] No need to restart the mysql server
2] Security concern for a MySQL server connected to a network
There is no need to restart the MySQL server.
use FLUSH PRIVILEGES;
after the update mysql.user statement for password change.
The FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.
The --skip-grant-options
enables anyone to connect without a password and with all privileges. Because this is insecure, you might want to
use --skip-grant-tables in conjunction with --skip-networking to prevent remote clients from connecting.
from: reference: resetting-permissions-generic
There is a comprehensive list of tools on the PostgreSQL Wiki:
https://wiki.postgresql.org/wiki/PostgreSQL_Clients
And of course PostgreSQL itself comes with pgAdmin, a GUI tool for accessing Postgres databases.
Probably, more intuitive way would be like this
if type(e) is list:
print('Found a list element inside the list')
You can define a global alias so you can invoke a short log in a more comfortable way:
git config --global alias.slog "log --pretty=oneline --abbrev-commit"
Then you can call it using git slog
(it even works with autocompletion if you have it enabled).
Or you can always map
over an iterator, without the need to build an intermediate list:
>>> _ = map(sys.stdout.write, (x for x in string.letters if x in (y for y in "BigMan on campus")))
acgimnopsuBM
For MAC
./gradlew build --refresh-dependencies
For Windows
gradlew build --refresh-dependencies
Can also try gradlew assembleDevelopmentDebug --refresh-dependencies
The alias should be included after the DELETE
keyword:
DELETE th
FROM term_hierarchy AS th
WHERE th.parent = 1015 AND th.tid IN
(
SELECT DISTINCT(th1.tid)
FROM term_hierarchy AS th1
INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
WHERE th1.parent = 1015
);
Why not refer to the documentation or the sample code shipping with the SDK? There's code in the samples on how to create/update/fill/read databases using the helper class described in the document I linked.
On Visual Studio 2013 RC2, there is a template for this. Just add it to App_Start folder.
The template produces such a class:
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(WebApiOsp.App_Start.Startup))]
namespace WebApiOsp.App_Start
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
}
}
}
var persons = new List<Person>
{
new Person {ID = 1, Name = "jhon", Salary = 2500},
new Person {ID = 2, Name = "Sena", Salary = 1500},
new Person {ID = 3, Name = "Max", Salary = 5500},
new Person {ID = 4, Name = "Gen", Salary = 3500}
};
var acertainperson = persons.Where(p => p.Name == "jhon").First();
Console.WriteLine("{0}: {1} points",
acertainperson.Name, acertainperson.Salary);
jhon: 2500 points
var doingprettywell = persons.Where(p => p.Salary > 2000);
foreach (var person in doingprettywell)
{
Console.WriteLine("{0}: {1} points",
person.Name, person.Salary);
}
jhon: 2500 points
Max: 5500 points
Gen: 3500 points
var astupidcalc = from p in persons
where p.ID > 2
select new
{
Name = p.Name,
Bobos = p.Salary*p.ID,
Bobotype = "bobos"
};
foreach (var person in astupidcalc)
{
Console.WriteLine("{0}: {1} {2}",
person.Name, person.Bobos, person.Bobotype);
}
Max: 16500 bobos
Gen: 14000 bobos
A simple increment should do the trick.
UPDATE mytable
SET logins = logins + 1
WHERE id = 12
If you would like to update a previously existing row, or insert it if it doesn't already exist, you can use the REPLACE
syntax or the INSERT...ON DUPLICATE KEY UPDATE
option (As Rob Van Dam demonstrated in his answer).
Or perhaps you're looking for something like INSERT...MAX(logins)+1
? Essentially you'd run a query much like the following - perhaps a bit more complex depending on your specific needs:
INSERT into mytable (logins)
SELECT max(logins) + 1
FROM mytable
Base on the question, I use this script below to automatic increase my version number in all maven parent/submodules:
#!/usr/bin/env bash
# Advances the last number of the given version string by one.
function advance\_version () {
local v=$1
\# Get the last number. First remove any suffixes (such as '-SNAPSHOT').
local cleaned=\`echo $v | sed \-e 's/\[^0-9\]\[^0-9\]\*$//'\`
local last\_num=\`echo $cleaned | sed \-e 's/\[0-9\]\*\\.//g'\`
local next\_num=$(($last\_num+1))
\# Finally replace the last number in version string with the new one.
echo $v | sed \-e "s/\[0-9\]\[0-9\]\*\\(\[^0-9\]\*\\)$/$next\_num/"
}
version=$(mvn org.apache.maven.plugins:maven-help-plugin:3.2.0:evaluate -Dexpression=project.version -q -DforceStdout)
new\_version=$(advance\_version $version)
mvn versions:set -DnewVersion=${new\_version} -DprocessAllModules -DgenerateBackupPoms=false
If your are using HTML5 then try following code snippet
<img id="uploadPreview" style="width: 100px; height: 100px;" />
<input id="uploadImage" type="file" name="myPhoto" onchange="PreviewImage();" />
<script type="text/javascript">
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
document.getElementById("uploadPreview").src = oFREvent.target.result;
};
};
</script>
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
If you like to go into the app folders to see what's going on and don't want to have to go through labyrinthine UUDID's, I made this: https://github.com/kallewoof/plget
and using it, I made this: https://gist.github.com/kallewoof/de4899aabde564f62687
Basically, when I want to go to some app's folder, I do:
$ cd ~/iosapps
$ ./app.sh
$ ls -l
total 152
lrwxr-xr-x 1 me staff 72 Nov 14 17:15 My App Beta-iOS-7-1_iPad-Retina.iapp -> iOS-7-1_iPad-Retina.dr/Applications/BD660795-9131-4A5A-9A5D-074459F6A4BF
lrwxr-xr-x 1 me staff 72 Nov 14 17:15 Other App Beta-iOS-7-1_iPad-Retina.iapp -> iOS-7-1_iPad-Retina.dr/Applications/A74C9F8B-37E0-4D89-80F9-48A15599D404
lrwxr-xr-x 1 me staff 72 Nov 14 17:15 My App-iOS-7-1_iPad-Retina.iapp -> iOS-7-1_iPad-Retina.dr/Applications/07BA5718-CF3B-42C7-B501-762E02F9756E
lrwxr-xr-x 1 me staff 72 Nov 14 17:15 Other App-iOS-7-1_iPad-Retina.iapp -> iOS-7-1_iPad-Retina.dr/Applications/5A4642A4-B598-429F-ADC9-BB15D5CEE9B0
-rwxr-xr-x 1 me staff 3282 Nov 14 17:04 app.sh
lrwxr-xr-x 1 me staff 158 Nov 14 17:15 com.mycompany.app1-iOS-8-0_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/129FE671-F8D2-446D-9B69-DE56F1AC80B9/data/Containers/Data/Application/69F7E3EF-B450-4840-826D-3830E79C247A
lrwxr-xr-x 1 me staff 158 Nov 14 17:15 com.mycompany.app1-iOS-8-1_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/414E8875-8875-4088-B17A-200202219A34/data/Containers/Data/Application/976D1E91-DA9E-4DA0-800D-52D1AE527AC6
lrwxr-xr-x 1 me staff 158 Nov 14 17:15 com.mycompany.app1beta-iOS-8-0_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/129FE671-F8D2-446D-9B69-DE56F1AC80B9/data/Containers/Data/Application/473F8259-EE11-4417-B04E-6FBA7BF2ED05
lrwxr-xr-x 1 me staff 158 Nov 14 17:15 com.mycompany.app1beta-iOS-8-1_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/414E8875-8875-4088-B17A-200202219A34/data/Containers/Data/Application/CB21C38E-B978-4B8F-99D1-EAC7F10BD894
lrwxr-xr-x 1 me staff 158 Nov 14 17:15 com.mycompany.otherapp-iOS-8-1_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/414E8875-8875-4088-B17A-200202219A34/data/Containers/Data/Application/DE3FF8F1-303D-41FA-AD8D-43B22DDADCDE
lrwxr-xr-x 1 me staff 51 Nov 14 17:15 iOS-7-1_iPad-Retina.dr -> simulator/4DC11775-F2B5-4447-98EB-FC5C1DB562AD/data
lrwxr-xr-x 1 me staff 51 Nov 14 17:15 iOS-8-0_iPad-2.dr -> simulator/6FC02AE7-27B4-4DBF-92F1-CCFEBDCAC5EE/data
lrwxr-xr-x 1 me staff 51 Nov 14 17:15 iOS-8-0_iPad-Retina.dr -> simulator/129FE671-F8D2-446D-9B69-DE56F1AC80B9/data
lrwxr-xr-x 1 me staff 51 Nov 14 17:15 iOS-8-1_iPad-Retina.dr -> simulator/414E8875-8875-4088-B17A-200202219A34/data
lrwxr-xr-x 1 me staff 158 Nov 14 17:15 org.cocoapods.demo.pajdeg-iOS-8-0_iPad-Retina.iapp -> /Users/me/Library/Developer/CoreSimulator/Devices/129FE671-F8D2-446D-9B69-DE56F1AC80B9/data/Containers/Data/Application/C3069623-D55D-462C-82E0-E896C942F7DE
lrwxr-xr-x 1 me staff 51 Nov 14 17:15 simulator -> /Users/me/Library/Developer/CoreSimulator/Devices
The ./app.sh
part syncs the links. It is necessary basically always nowadays as apps change UUID for every run in Xcode as of 6.0. Also, unfortunately, apps are by bundle id for 8.x and by app name for < 8.
I think this is a better solution
// UTC milliseconds
new Date(Date.now()+(new Date().getTimezoneOffset()*60000)).getTime()
// UTC seconds
new Date(Date.now()+(new Date().getTimezoneOffset()*60000)).getTime()/1000|0
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
If you're one the commandline shell, you can do this very quickly. Just fill in "dbname" :D
DB="dbname"
(
echo 'ALTER DATABASE `'"$DB"'` CHARACTER SET utf8 COLLATE utf8_general_ci;'
mysql "$DB" -e "SHOW TABLES" --batch --skip-column-names \
| xargs -I{} echo 'ALTER TABLE `'{}'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;'
) \
| mysql "$DB"
DB="dbname"; ( echo 'ALTER DATABASE `'"$DB"'` CHARACTER SET utf8 COLLATE utf8_general_ci;'; mysql "$DB" -e "SHOW TABLES" --batch --skip-column-names | xargs -I{} echo 'ALTER TABLE `'{}'` CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;' ) | mysql "$DB"
A String
instance allocates a certain amount of bytes in memory. Maybe you're looking at something like sizeof("Hello World")
which would return the number of bytes allocated by the datastructure itself?
In Java, there's usually no need for a sizeof
function, because we never allocate memory to store a data structure. We can have a look at the String.java
file for a rough estimation, and we see some 'int', some references and a char[]
. The Java language specification defines, that a char
ranges from 0 to 65535, so two bytes are sufficient to keep a single char in memory. But a JVM does not have to store one char in 2 bytes, it only has to guarantee, that the implementation of char
can hold values of the defines range.
So sizeof
really does not make any sense in Java. But, assuming that we have a large String and one char
allocates two bytes, then the memory footprint of a String
object is at least 2 * str.length()
in bytes.
You can also use this old trick for converting complex if/then/else blocks into a slightly cleaner switch statement:
<div [ngSwitch]="true">
<button (click)="foo=(++foo%3)+1">Switch!</button>
<div *ngSwitchCase="foo === 1">one</div>
<div *ngSwitchCase="foo === 2">two</div>
<div *ngSwitchCase="foo === 3">three</div>
</div>
Take a look on life cycle of Activity
Where
***onCreate()***
Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().
***onStart()***
Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.
And you can write your simple class to take a look when these methods call
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private final static String TAG = "TestActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "On Create .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onDestroy()
*/
@Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "On Destroy .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onPause()
*/
@Override
protected void onPause() {
super.onPause();
Log.i(TAG, "On Pause .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "On Restart .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "On Resume .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStart()
*/
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "On Start .....");
}
/* (non-Javadoc)
* @see android.app.Activity#onStop()
*/
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "On Stop .....");
}
}
Hope this will clear your confusion.
And take a look here for details.
Lifecycle Methods in Details is a very good example and demo application, which is a very good article to understand the life cycle.
Why not pass an object to v-bind:class to dynamically toggle the class:
<div v-bind:class="{ disabled: order.cancelled_at }"></div>
This is what is recommended by the Vue docs.
If you are a Wordpress developer I have some great news for you.
Just search for, install and activate the Wordpress plugin called: reBusted.
No configuration is necessary.
It will automatically force cache refresh if the content has been updated and it solves this issue completely and reliably. Tested and used on hundreds of clients Wordpress sites – works perfectly everywhere.
Cannot recommend it enough.
If you use Wordpress, this is by far your best option and most elegant resolution for this issue.
Enjoy!
$(document).click(function (e) {
alert($(e.target).text());
});
You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:
@(deletedView ? "Deleted" : "Created by")
Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.
Try this:
$Object = 'FirstPart SecondPart' | ConvertFrom-String -PropertyNames Val1, Val2
$Object.Val1
$Object.Val2
I tried the following code and it worked for me.
<button class="btn btn-default center-block" type="submit">Button</button>
The button control is in a div and using center-block class of bootstrap helped me to align the button to the center of div
Check the link where you will find the center-block class
I scripted the simple tag parser for using a custom-size img tag in Jekyll.
https://gist.github.com/nurinamu/4ccf7197a1bdfb0d7079
{% img /path/to/img.png 100x200 %}
You can add the file to the _plugins
folder.
WebDriverManager allows to automate the management of the binary drivers (e.g. chromedriver, geckodriver, etc.) required by Selenium WebDriver.
Link: https://github.com/bonigarcia/webdrivermanager
you can use something link this: WebDriverManager.iedriver().setup();
add the following dependency for Maven:
<dependency>
<groupId>io.github.bonigarcia</groupId>
<artifactId>webdrivermanager</artifactId>
<version>x.x.x</version>
<scope>test</scope>
</dependency>
or see: https://www.toolsqa.com/selenium-webdriver/webdrivermanager/
Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?
codaddict's solution works fine, but this one is a bit more efficient: (Python syntax)
password = re.compile(r"""(?#!py password Rev:20160831_2100)
# Validate password: 2 upper, 1 special, 2 digit, 1 lower, 8 chars.
^ # Anchor to start of string.
(?=(?:[^A-Z]*[A-Z]){2}) # At least two uppercase.
(?=[^!@#$&*]*[!@#$&*]) # At least one "special".
(?=(?:[^0-9]*[0-9]){2}) # At least two digit.
.{8,} # Password length is 8 or more.
$ # Anchor to end of string.
""", re.VERBOSE)
The negated character classes consume everything up to the desired character in a single step, requiring zero backtracking. (The dot star solution works just fine, but does require some backtracking.) Of course with short target strings such as passwords, this efficiency improvement will be negligible.
There is no limit to the input of md5 that I know of. Some implementations require the entire input to be loaded into memory before passing it into the md5 function (i.e., the implementation acts on a block of memory, not on a stream), but this is not a limitation of the algorithm itself. The output is always 128 bits. Note that md5 is not an encryption algorithm, but a cryptographic hash. This means that you can use it to verify the integrity of a chunk of data, but you cannot reverse the hashing. Also note that md5 is considered broken, so you shouldn't use it for anything security-related (it's still fine to verify the integrity of downloaded files and such).
UPDATE will return the number of modified rows. If you use JDBC (Java), you can then check this value against 0 and, if no rows have been affected, fire INSERT instead. If you use some other programming language, maybe the number of the modified rows still can be obtained, check documentation.
This may not be as elegant but you have much simpler SQL that is more trivial to use from the calling code. Differently, if you write the ten line script in PL/PSQL, you probably should have a unit test of one or another kind just for it alone.
.span7.btn { display: block; margin-left: auto; margin-right: auto; }
I am not completely familiar with bootstrap, but something like the above should do the trick. It may not be necessary to include all of the classes. This should center the button within its parent, the span7.
this worker for me
git clone <repository> .
If you're experiencing this in an enum, or when initializing an array with anonymous classes, it's a known bug in Eclipse. See Eclipse content assist not working in enum constant parameter list.
The given answers only work when there are no borders around the table, which is very limiting!
I have a macro in SASS to do this, which fully supports external and internal borders, achieving the same styling as border-collapse: collapse without actually specifying it.
Tested in FF/IE8/Safari/Chrome.
Gives nice rounded borders in pure CSS in all browsers but IE8 (degrades gracefully) since IE8 doesn't support border-radius :(
Some older browsers may require vendor prefixes to work with border-radius
, so feel free to add those prefixes to your code as necessary.
This answer is not the shortest - but it works.
.roundedTable {
border-radius: 20px / 20px;
border: 1px solid #333333;
border-spacing: 0px;
}
.roundedTable th {
padding: 4px;
background: #ffcc11;
border-left: 1px solid #333333;
}
.roundedTable th:first-child {
border-left: none;
border-top-left-radius: 20px;
}
.roundedTable th:last-child {
border-top-right-radius: 20px;
}
.roundedTable tr td {
border: 1px solid #333333;
border-right: none;
border-bottom: none;
padding: 4px;
}
.roundedTable tr td:first-child {
border-left: none;
}
To apply this style simply change your
<table>
tag to the following:
<table class="roundedTable">
and be sure to include the above CSS styles in your HTML.
Hope this helps.
Add extra columns as null for the table having less columns like
Select Col1, Col2, Col3, Col4, Col5 from Table1
Union
Select Col1, Col2, Col3, Null as Col4, Null as Col5 from Table2
While
constructs are terminated not with an End While
but with a Wend
.
While counter < 20
counter = counter + 1
Wend
Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.
Also in the VBA help file:
Tip The
Do...Loop
statement provides a more structured and flexible way to perform looping.
No, there's no legal and reliable way to do this.
If you find a way, it will be disabled in the future, as it has happened with every method before.
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
Don't edit the vector assets directly. If you're using a vector drawable in an ImageButton, just choose your color in android:tint
.
<ImageButton
android:layout_width="48dp"
android:layout_height="48dp"
android:id="@+id/button"
android:src="@drawable/ic_more_vert_24dp"
android:tint="@color/primary" />
if you want to kill a specific node process , you can go to command line route and type:
ps aux | grep node
to get a list of all node process ids. now you can get your process id(pid), then do:
kill -9 PID
and if you want to kill all node processes then do:
killall -9 node
-9 switch is like end task on windows. it will force the process to end. you can do:
kill -l
to see all switches of kill command and their comments.
Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:
Unexpected indent. This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g. if/while/for statement). All lines of code in a block must start with exactly the same string of whitespace. For instance:
>>> def a():
... print "foo"
... print "bar"
IndentationError: unexpected indent
This one is especially common when running python interactively: make sure you don't put any extra spaces before your commands. (Very annoying when copy-and-pasting example code!)
>>> print "hello"
IndentationError: unexpected indent
Unindent does not match any outer indentation level. This line of code has fewer spaces at the start than the one before, but equally it does not match any other block it could be part of. Python cannot decide where it goes. For instance, in the following, is the final print supposed to be part of the if clause, or not?
>>> if user == "Joey":
... print "Super secret powers enabled!"
... print "Revealing super secrets"
IndendationError: unindent does not match any outer indentation level
Expected an indented block. This line of code has the same number of spaces at the start as the one before, but the last line was expected to start a block (e.g. if/while/for statement, function definition).
>>> def foo():
... print "Bar"
IndentationError: expected an indented block
If you want a function that doesn't do anything, use the "no-op" command pass:
>>> def foo():
... pass
Mixing tabs and spaces is allowed (at least on my version of Python), but Python assumes tabs are 8 characters long, which may not match your editor. Just say "no" to tabs. Most editors allow them to be automatically replaced by spaces.
The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.
Using a CLI, the easiest way (cross-platform) I've found is to use the NPM package https://github.com/sindresorhus/open-cli
npm install --global open-cli
Installing it globally allows running something like open-cli https://unlyed.github.io/next-right-now/
.
You can also install it locally (e.g: in a project) and run npx open-cli https://unlyed.github.io/next-right-now/
Or, using a NPM script (which is how I actually use it):
"doc:online": "open-cli https://unlyed.github.io/next-right-now/",
Running yarn doc:online
will open the webpage, and this works on any platform (windows, mac, linux).
This is the correct answer. It worked!!
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
driver = webdriver.Chrome("E:\\Python\\selenium\\webdriver\\chromedriver.exe")
driver.get("https://www.tatacliq.com/global-desi-navy-embroidered-kurta/p-mp000000000876745")
driver.set_page_load_timeout(45)
driver.maximize_window()
driver.implicitly_wait(2)
driver.get_screenshot_as_file("E:\\Python\\Tatacliq.png")
print ("Executed Successfully")
driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").click()
SpecialPrice = driver.find_element_by_xpath("//div[@class='pdp-promo-title pdp-title']").text
print(SpecialPrice)
get all data from table
db.student.find({})
SELECT * FROM student
get all data from table without _id
db.student.find({}, {_id:0})
SELECT name, roll FROM student
get all data from one field with _id
db.student.find({}, {roll:1})
SELECT id, roll FROM student
get all data from one field without _id
db.student.find({}, {roll:1, _id:0})
SELECT roll FROM student
find specified data using where clause
db.student.find({roll: 80})
SELECT * FROM students WHERE roll = '80'
find a data using where clause and greater than condition
db.student.find({ "roll": { $gt: 70 }}) // $gt is greater than
SELECT * FROM student WHERE roll > '70'
find a data using where clause and greater than or equal to condition
db.student.find({ "roll": { $gte: 70 }}) // $gte is greater than or equal
SELECT * FROM student WHERE roll >= '70'
find a data using where clause and less than or equal to condition
db.student.find({ "roll": { $lte: 70 }}) // $lte is less than or equal
SELECT * FROM student WHERE roll <= '70'
find a data using where clause and less than to condition
db.student.find({ "roll": { $lt: 70 }}) // $lt is less than
SELECT * FROM student WHERE roll < '70'
There is no ranking functionality in MySQL. The closest you can get is to use a variable:
SELECT t.*,
@rownum := @rownum + 1 AS rank
FROM YOUR_TABLE t,
(SELECT @rownum := 0) r
so how would that work in my case? I'd need two variables, one for each of col1 and col2? Col2 would need resetting somehow when col1 changed..?
Yes. If it were Oracle, you could use the LEAD function to peak at the next value. Thankfully, Quassnoi covers the logic for what you need to implement in MySQL.
You can also use :
to embed documentation in a function.
Assume you have a library script mylib.sh
, providing a variety of functions. You could either source the library (. mylib.sh
) and call the functions directly after that (lib_function1 arg1 arg2
), or avoid cluttering your namespace and invoke the library with a function argument (mylib.sh lib_function1 arg1 arg2
).
Wouldn't it be nice if you could also type mylib.sh --help
and get a list of available functions and their usage, without having to manually maintain the function list in the help text?
#!/bin/bash # all "public" functions must start with this prefix LIB_PREFIX='lib_' # "public" library functions lib_function1() { : This function does something complicated with two arguments. : : Parameters: : ' arg1 - first argument ($1)' : ' arg2 - second argument' : : Result: : " it's complicated" # actual function code starts here } lib_function2() { : Function documentation # function code here } # help function --help() { echo MyLib v0.0.1 echo echo Usage: mylib.sh [function_name [args]] echo echo Available functions: declare -f | sed -n -e '/^'$LIB_PREFIX'/,/^}$/{/\(^'$LIB_PREFIX'\)\|\(^[ \t]*:\)/{ s/^\('$LIB_PREFIX'.*\) ()/\n=== \1 ===/;s/^[ \t]*: \?['\''"]\?/ /;s/['\''"]\?;\?$//;p}}' } # main code if [ "${BASH_SOURCE[0]}" = "${0}" ]; then # the script was executed instead of sourced # invoke requested function or display help if [ "$(type -t - "$1" 2>/dev/null)" = function ]; then "$@" else --help fi fi
A few comments about the code:
declare -f
to enumerate all available functions, then filters them through sed to only display functions with the appropriate prefix.mylib.sh function1
and it gets translated internally to lib_function1
. This is an exercise left to the reader.$1
. At the same time, it will clutter your namespace if you source the library. If you don't like that, you can either change the name to something like lib_help
or actually check the args for --help
in the main code and invoke the help function manually.Sadly, there's no equivalent to the null coalescing operator that works with DBNull; for that, you need to use the ternary operator:
newValue = (oldValue is DBNull) ? null : oldValue;
I agree with MarsPeople regarding loading libraries in the wrong order. My example is from working with owl.carousel.
I got the same error when importing jquery after owl.carousel:
<script src="owl.carousel.js"></script>
<script src="jquery-3.1.1.min.js"></script>
and fixed it by importing jquery before owl.carousel:
<script src="jquery-3.1.1.min.js"></script>
<script src="owl.carousel.js"></script>
I'm a big fan of hdf5 for storing large numpy arrays. There are two options for dealing with hdf5 in python:
Both are designed to work with numpy arrays efficiently.
If you throw a new exception with the initial exception you will preserve the initial stack trace too..
try{
}
catch(Exception ex){
throw new MoreDescriptiveException("here is what was happening", ex);
}
I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.
I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.
I hope this helps.
Answer In Kotlin Give Permissions
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
private fun getCurrentNetworkDetail() {
val connManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
if (networkInfo.isConnected) {
val wifiManager =
context.getApplicationContext().getSystemService(Context.WIFI_SERVICE) as WifiManager
val connectionInfo = wifiManager.connectionInfo
if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.ssid)) {
Log.e("ssid", connectionInfo.ssid)
}
}
else{
Log.e("ssid", "No Connection")
}
}
import re
pattern = re.compile("<(\d{4,5})>")
for i, line in enumerate(open('test.txt')):
for match in re.finditer(pattern, line):
print 'Found on line %s: %s' % (i+1, match.group())
A couple of notes about the regex:
?
at the end and the outer (...)
if you don't want to match the number with the angle brackets, but only want the number itselfUpdate: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.
More about regex in python can be found here : Regular Expression HOWTO
In case somebody is wondering how to just run an executable file:
..... > .\file.exe
or
......> full\path\to\file.exe
This may be what you are looking for:
body>div {_x000D_
background: #aaa;_x000D_
display: flex;_x000D_
flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
body>div>div {_x000D_
flex-grow: 1;_x000D_
width: 33%;_x000D_
height: 100px;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(even) {_x000D_
background: #23a;_x000D_
}_x000D_
_x000D_
body>div>div:nth-child(odd) {_x000D_
background: #49b;_x000D_
}
_x000D_
<div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
<div></div>_x000D_
</div>
_x000D_
I like the urllib.urlencode
function, and it doesn't appear to exist in urllib2
.
>>> urllib.urlencode({'abc':'d f', 'def': '-!2'})
'abc=d+f&def=-%212'
Navigate from Error List Tab
to the Visual Studios Output
folder by one of the following:
Output
in standard VS view at the bottomView > Output
or Ctrl+Alt+O
where Show output from <build>
should be selected.
You can find out more by analyzing the output logs.
In my case it was an error in the Cmake step, see below. It could be in any build step, as described in the other answers.
> -- Build Type is debug
> CMake Error in CMakeLists.txt:
> A logical block opening on the line
> <path_to_file:line_number>
> is not closed.
Using the knitr package:
```{r, engine='bash', code_block_name} ...
E.g.:
```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt
```
You can also use:
engine='sh'
for shellengine='python'
for Pythonengine='perl'
, engine='haskell'
and a bunch of other C-like languages and even gawk
, AWK, etc.You shouldn't be calling .ToString()
.
As the error message clearly states, you're writing a conditional in which one half is an IHtmlString
and the other half is a string.
That doesn't make sense, since the compiler doesn't know what type the entire expression should be.
There is never a reason to call Html.Raw(...).ToString()
.
Html.Raw
returns an HtmlString
instance that wraps the original string.
The Razor page output knows not to escape HtmlString
instances.
However, calling HtmlString.ToString()
just returns the original string
value again; it doesn't accomplish anything.
you can try this one also,
df= df.applymap(lambda s:s.lower() if type(s) == str else s)
Found here what I was looking for. Helped me recall what I used 3-4 years back.
I wanted to reuse the same syntax to be able to create table with data resulting from the join of a table.
Came up with below query after a few attempts.
SELECT a.*
INTO DetailsArchive
FROM (SELECT d.*
FROM details AS d
INNER JOIN
port AS p
ON p.importid = d.importid
WHERE p.status = 2) AS a;
Another way;
alert( "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf("Jun") / 3 + 1 );
You can use lambda
functions in findAll
as explained in documentation. So that in your case to search for td
tag with only valign = "top"
use following:
td_tag_list = soup.findAll(
lambda tag:tag.name == "td" and
len(tag.attrs) == 1 and
tag["valign"] == "top")
try this:
key=key.replace(/ /g,"_");
that'll do a global find/replace
break
interacts solely with the closest enclosing loop or switch, whether it be a for
, while
or do .. while
type. It is frequently referred to as a goto in disguise, as all loops in C can in fact be transformed into a set of conditional gotos:
for (A; B; C) D;
// translates to
A;
goto test;
loop: D;
iter: C;
test: if (B) goto loop;
end:
while (B) D; // Simply doesn't have A or C
do { D; } while (B); // Omits initial goto test
continue; // goto iter;
break; // goto end;
The difference is, continue
and break
interact with virtual labels automatically placed by the compiler. This is similar to what return
does as you know it will always jump ahead in the program flow. Switches are slightly more complicated, generating arrays of labels and computed gotos, but the way break works with them is similar.
The programming error the notice refers to is misunderstanding break
as interacting with an enclosing block rather than an enclosing loop. Consider:
for (A; B; C) {
D;
if (E) {
F;
if (G) break; // Incorrectly assumed to break if(E), breaks for()
H;
}
I;
}
J;
Someone thought, given such a piece of code, that G
would cause a jump to I
, but it jumps to J
. The intended function would use if (!G) H;
instead.
What operating system are you on? If you running Windows you will want to make sure you have the drivers. You should also make sure that your Android SDK Manager is not only installed, but it also contains some additional things for different devices. Not sure if yours is in there or not.
Make sure that your phone has debugging enabled. I found myself having to run
adb kill-server
adb devices
often.
I had the same problem. But I also had to perform additional steps. Here is what I did.
Perform the following steps (Only 64bit version of SQL Server 2005 Developer Edition tested on Windows 8 Pro 64bit)
For STEP 5 above: Although I didn't try looking into SP4 / SP3 setup for SQLSERVR.EXE and SQLOS.DLL but if you don't have an existing installation of SQL Server 2005 SP3/SP4 then maybe try looking into the SP3/SP4 EXE (Compressed file). I am not sure if this may help. In any case you can create a VM and install SQL Server 2005 with SP3/Sp4 to copy the files for Windows 8
I had the same problem, and it was caused by line for insecured registry in: /etc/default/docker
Spent hours on this, hopefully I can save someone else some time. To me the following approach to using debounce
on a control is more intuitive and easier to understand for me. It's built on the angular.io docs solution for autocomplete but with the ability for me to intercept the calls without having to depend on tying the data to the DOM.
A use case scenario for this might be checking a username after it's typed to see if someone has already taken it, then warning the user.
Note: don't forget, (blur)="function(something.value)
might make more sense for you depending on your needs.
You can put the data in a file and re-direct it like this:
$ cat file.sh
#!/bin/bash
read x
read y
echo $x
echo $y
Data for the script:
$ cat data.txt
2
3
Executing the script:
$ file.sh < data.txt
2
3
Here's what I've got so far (found it on the page Ben Alpert mentioned):
SELECT REPLACE(
SUBSTRING(
SUBSTRING_INDEX(c.`courseNames`, ',', e.`courseId` + 1)
, LENGTH(SUBSTRING_INDEX(c.`courseNames`, ',', e.`courseId`)
) + 1)
, ','
, ''
)
FROM `clients` c INNER JOIN `clientenrols` e USING (`clientId`)
You need to call ParseExact
, which parses a date that exactly matches a format that you supply.
For example:
DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);
The IFormatProvider
parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture
.
If the string does come from the user, you should pass CultureInfo.CurrentCulture
, which will use the settings that the user specified in Regional Options in Control Panel.
I think the question went in the wrong way, If you want to take the Request header from JQuery/JavaScript the answer is simply No. The other solutions is create a aspx page or jsp page then we can easily access the request header. Take all the request in aspx page and put into a session/cookies then you can access the cookies in JavaScript page..
<script> var disabledDaysRange = $disabledDaysRange ???? Please Help;
$(function() {
function disableRangeOfDays(d) {
in the above assign array to javascript variable "disableDaysRange"
$disallowDates = "";
echo "[";
foreach($disabledDaysRange as $disableDates){
$disallowDates .= "'".$disableDates."',";
}
echo substr(disallowDates,0,(strlen(disallowDates)-1)); // this will escape the last comma from $disallowDates
echo "];";
so your javascript var diableDateRange shoudl be
var diableDateRange = ["2013-01-01","2013-01-02","2013-01-03"];
You cannot push to the one checked out branch of a repository because it would mess with the user of that repository in a way that will most probably end with loss of data and history. But you can push to any other branch of the same repository.
As bare repositories never have any branch checked out, you can always push to any branch of a bare repository.
When a branch is checked out, committing will add a new commit with the current branch's head as its parent and move the branch's head to be that new commit.
So
A ? B
?
[HEAD,branch1]
becomes
A ? B ? C
?
[HEAD,branch1]
But if someone could push to that branch inbetween, the user would get itself in what git calls detached head mode:
A ? B ? X
? ?
[HEAD] [branch1]
Now the user is not in branch1 anymore, without having explicitly asked to check out another branch. Worse, the user is now outside any branch, and any new commit will just be dangling:
[HEAD]
?
C
?
A ? B ? X
?
[branch1]
Hypothetically, if at this point, the user checks out another branch, then this dangling commit becomes fair game for Git's garbage collector.
Yes, you can use jQuery's attribute selector for that.
var linksToGoogle = $('a[href="http://google.com"]');
Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:
var allLinksToGoogle = $('a[href^="http://google.com"]');
Here is a code example to follow. #thumbnail is a DIV parent of the #handle DIV
buildDraggable = function() {
$( "#handle" ).draggable({
containment: '#thumbnail',
drag: function(event) {
var top = $(this).position().top;
var left = $(this).position().left;
ICZoom.panImage(top, left);
},
});
If you want to iterate over both keys and values of the dictionary, do this:
for key, value in data.items():
print key, value
You've got several options:
x
ecute permissions on that directory.x
ecute permissions.
chmod(1)
to change the permissions orsetfacl(1)
command to add an access control list entry for your user account. (This also requires mounting the filesystem with the acl
option; see mount(8)
and fstab(5)
for details on the mount parameter.)It's impossible to suggest the correct approach without knowing more about the problem; why are the directory permissions set the way they are? Why do you need access to that directory?
Use second process. Declare at AndroidManifest
new Service
with
android:process=":second"
Exchange between first and second process over BroadcastReceiver
You'd have to set up the post-build shell script as a separate Jenkins job and trigger it as a post-build step. It looks like you will need to use the Parameterized Trigger Plugin as the standard "Build other projects" option only works if your triggering build is successful.
With Javascript you can get full size profile images like this
pass your accessToken
to the getface()
function from your FB.init
call
function getface(accessToken){
FB.api('/me/friends', function (response) {
for (id in response.data) {
var homie=response.data[id].id
FB.api(homie+'/albums?access_token='+accessToken, function (aresponse) {
for (album in aresponse.data) {
if (aresponse.data[album].name == "Profile Pictures") {
FB.api(aresponse.data[album].id + "/photos", function(aresponse) {
console.log(aresponse.data[0].images[0].source);
});
}
}
});
}
});
}
This fixes the math to scale to the max size in both width and height rather than just one depending on the width and height of the original.
- (UIImage *) scaleProportionalToSize: (CGSize)size
{
float widthRatio = size.width/self.size.width;
float heightRatio = size.height/self.size.height;
if(widthRatio > heightRatio)
{
size=CGSizeMake(self.size.width*heightRatio,self.size.height*heightRatio);
} else {
size=CGSizeMake(self.size.width*widthRatio,self.size.height*widthRatio);
}
return [self scaleToSize:size];
}
Firefox :
moznomarginboxes
attribute in <html>
Example :
<html moznomarginboxes mozdisallowselectionprint>
Best way i use:
1- add link to your html:
<a id="linkDynamic" target="_blank" href="#"></a>
2- add JS function:
function OpenNewTab(href)
{
document.getElementById('linkDynamic').href = href;
document.getElementById('linkDynamic').click();
}
3- just call OpenNewTab function with the link you want
You can use .sortBy
, it will always return an ascending list:
_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]
But you can use the .reverse method to get it descending:
var array = _.sortBy([2, 3, 1], function(num) {
return num;
});
console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]
Or when dealing with numbers add a negative sign to the return to descend the list:
_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]
Under the hood .sortBy
uses the built in .sort([handler])
:
// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]
// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
// a = current item in array
// b = next item in array
return b - a;
});
Well, DNS should be the same worldwide, wouldn't it? Of course it can take up to a day or so until your new DNS record is propagated around the world. So either something is wrong on your colleague's end or the DNS record still takes some time...
I usually use online DNS lookup tools for that, e.g. http://network-tools.com/
It can check your HTTP header as well. Only a proxy located in Europe would be better.
You should have name column as a unique constraint. here is a 3 lines of code to change your issues
First find out the primary key constraints by typing this code
\d table_name
you are shown like this at bottom "some_constraint" PRIMARY KEY, btree (column)
Drop the constraint:
ALTER TABLE table_name DROP CONSTRAINT some_constraint
Add a new primary key column with existing one:
ALTER TABLE table_name ADD CONSTRAINT some_constraint PRIMARY KEY(COLUMN_NAME1,COLUMN_NAME2);
That's All.
Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format
(svg
and eot
are dead formats, ttf
and otf
are full system fonts, and should not be used for web purposes)
In short, font-face is very old, but only recently has been supported by more than IE.
eot
is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.
ttf
and otf
are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.
Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.
Then, woff
gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.
2019 edit A few years later, woff2
gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.
If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)
@font-face {
font-family: 'MyWebFont';
src: url('myfont.woff2') format('woff2'),
url('myfont.woff') format('woff');
}
Support for woff
can be checked at http://caniuse.com/woff
Support for woff2
can be checked at http://caniuse.com/woff2
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
An exemple of the only solution that works for me in the simple usecase where I am on a fork and I want to checkout a new branch from a tag that is on the main project repository ( here upstream )
git fetch upstream --tags
Give me
From https://github.com/keycloak/keycloak
90b29b0e31..0ba9055d28 stage -> upstream/stage
* [new tag] 11.0.0 -> 11.0.0
Then I can create a new branch from this tag and checkout on it
git checkout -b tags/<name> <newbranch>
git checkout tags/11.0.0 -b v11.0.0
I had to add the .classpath too, form a java project. I made a dummy java project and looked in the workspace for this dummy java project to see what is required. I transferred the two files. profile and .claspath to my checked out, and disconnected source from my subversion server. From then on it turned to a java project from just a plain old project.
When you have two or more windows open horizontally or vertically and want to switch them all to the other orientation, you can use the following:
(switch to horizontal)
:windo wincmd K
(switch to vertical)
:windo wincmd H
It's effectively going to each window individually and using ^WK or ^WH.
9007199254740992 (that's 9,007,199,254,740,992) with no guarantees :)
Program
#include <math.h>
#include <stdio.h>
int main(void) {
double dbl = 0; /* I started with 9007199254000000, a little less than 2^53 */
while (dbl + 1 != dbl) dbl++;
printf("%.0f\n", dbl - 1);
printf("%.0f\n", dbl);
printf("%.0f\n", dbl + 1);
return 0;
}
Result
9007199254740991 9007199254740992 9007199254740992
It seems that there is in fact a pure CSS solution, requiring only the css attr
expression, generated content and attribute selectors (which suggests that it works as far back as IE8):
https://jsfiddle.net/z42r2vv0/2/
a {
position: relative;
display: inline-block;
margin-top: 20px;
}
a[title]:hover::after {
content: attr(title);
position: absolute;
top: -100%;
left: 0;
}
_x000D_
<a href="http://www.google.com/" title="Hello world!">
Hover over me
</a>
_x000D_
update w/ input from @ViROscar: please note that it's not necessary to use any specific attribute, although I've used the "title" attribute in the example above; actually my recommendation would be to use the "alt" attribute, as there is some chance that the content will be accessible to users unable to benefit from CSS.
update again I'm not changing the code because the "title" attribute has basically come to mean the "tooltip" attribute, and it's probably not a good idea to hide important text inside a field only accessible on hover, but if you're interested in making this text accessible the "aria-label" attribute seems like the best place for it: https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-label_attribute
$.fn.attr(attributeName) returns the attribute value as string, or undefined
when the attribute is not present.
Since ""
, and undefined
are both falsy (evaluates to false when coerced to boolean) values in JavaScript, in this case I would write the check as below:
if (wlocation) { ... }
I had the same issue, and I tried everything what is posted here to fix it but none worked for me. In my case I'm using Cygwin to compile the dll. It seems that JVM tries to find the JRE DLLs in the virtual Cygwin path. I added the the Cygwin's virtual directory path to JRE's DLLs and it works now. I did something like:
SET PATH="/cygdrive/c/Program Files/Java/jdk1.8.0_45";%PATH%
if you want to get an attribute of an HTML element with jQuery you can use .attr();
so $('html').attr('someAttribute');
will give you the value of someAttribute
of the element html
there is a jQuery plugin here: http://plugins.jquery.com/project/getAttributes
that allows you to get all attributes from an HTML element
Instead of "w"
use "a"
(append) mode with open
function:
with open("games.txt", "a") as text_file:
Another solution posted here overriding setPrimaryItem in the pageradapter by kris larson almost worked for me. But this method is called multiple times for each setup. Also I got NPE from views, etc. in the fragment as this is not ready the first few times this method is called. With the following changes this worked for me:
private int mCurrentPosition = -1;
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
if (position == mCurrentPosition) {
return;
}
if (object instanceof MyWhizBangFragment) {
MyWhizBangFragment fragment = (MyWhizBangFragment) object;
if (fragment.isResumed()) {
mCurrentPosition = position;
fragment.doTheThingYouNeedToDoOnBecomingVisible();
}
}
}
I need to add that, if the Module name and the sub name is the same you have such issue. Consider change the Module name to mod_Test instead of "Test" which is the same as the sub.
I would use something similar to this:
DECLARE @DATEFROM AS DATETIME
DECLARE @DATETO AS DATETIME
DECLARE @HOLDER TABLE(DATE DATETIME)
SET @DATEFROM = '2010-08-10'
SET @DATETO = '2010-09-11'
INSERT INTO
@HOLDER
(DATE)
VALUES
(@DATEFROM)
WHILE @DATEFROM < @DATETO
BEGIN
SELECT @DATEFROM = DATEADD(D, 1, @DATEFROM)
INSERT
INTO
@HOLDER
(DATE)
VALUES
(@DATEFROM)
END
SELECT
DATE
FROM
@HOLDER
Then the @HOLDER
Variable table holds all the dates incremented by day between those two dates, ready to join at your hearts content.
dfsq's answer is very nice. I modified it a bit to fit my needs: I actually needed a modal for the case that, after clicking, the user would also be navigated to the corresponding page. Executing the query asynchronously is not always what one needs.
Using Blade
I created the file resources/views/includes/confirmation_modal.blade.php
:
<div class="modal fade" id="confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="confirmation-modal-label" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>{{ $headerText }}</h4>
</div>
<div class="modal-body">
{{ $bodyText }}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<form action="" method="POST" style="display:inline">
{{ method_field($verb) }}
{{ csrf_field() }}
<input type="submit" class="btn btn-danger btn-ok" value="{{ $confirmButtonText }}" />
</form>
</div>
</div>
</div>
</div>
<script>
$('#confirmation-modal').on('show.bs.modal', function(e) {
href = $(e.relatedTarget).data('href');
// change href of button to corresponding target
$(this).find('form').attr('action', href);
});
</script>
Now, using it is straight-forward:
<a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>
Not much changed here and the modal can be included like this:
@include('includes.confirmation_modal', ['headerText' => 'Delete Data?', 'bodyText' => 'Do you really want to delete these data? This operation is irreversible.',
'confirmButtonText' => 'Remove Data', 'verb' => 'DELETE'])
Just by putting the verb in there, it uses it. This way, CSRF is also utilized.
Helped me, maybe it helps someone else.
For the tags, you should be able to just set the content with .text()
instead of .html()
.
Example: http://jsfiddle.net/Phf4u/1/
var textarea = $('textarea').val().replace(/<br\s?\/?>/, '\n');
$("#output").text(textarea);
...or if you just wanted to remove the <br>
elements, you could get rid of the .replace()
, and temporarily make them DOM elements.
Example: http://jsfiddle.net/Phf4u/2/
var textarea = $('textarea').val();
textarea = $('<div>').html(textarea).find('br').remove().end().html();
$("#output").text(textarea);
Since SQL Server Version 2012 you can use:
SELECT format(getdate(),'yyyyMMddHHmmssffff')
You will get it by tag type="date"...then it will render beautiful calendar and all...
@Html.TextBoxFor(model => model.EndTime, new { type = "date" })
Vibur DBCP is another library for that purpose. Several examples showing how to configure it for use with Hibernate, Spring+Hibernate, or programatically, can be found on its website: http://www.vibur.org/
Also, see the disclaimer here.
You can't do exactly what you want in Python (if I read you correctly). You need to put values in for each element of the list (or as you called it, array).
But, try this:
a = [0 for x in range(N)] # N = size of list you want
a[i] = 5 # as long as i < N, you're okay
For lists of other types, use something besides 0. None
is often a good choice as well.
Try running this on Anaconda prompt
pip install xgboost
This worked for me on Spyder with Python 3.5
Because you must add colorControlNormal
, colorControlActivated
, colorControlHighLight
items to main application theme:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="colorControlActivated">@color/yellow_bright</item>
<item name="colorControlNormal">@color/yellow_black</item>
</style>
Look here http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#deriveFont%28float%29
JComponent has a setFont() method. You will control the font there, not on the String.
Such as
JButton b = new JButton();
b.setFont(b.getFont().deriveFont(18.0f));
Here is my version of code. Hope it helps!
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = NSCharacterSet(charactersInString: "0123456789").invertedSet
if let range = string.rangeOfCharacterFromSet(invalidCharacters, options: nil, range:Range<String.Index>(start: string.startIndex, end: string.endIndex))
{
return false
}
if (count(textField.text) > 10 && range.length == 0)
{
self.view.makeToast(message: "Amount entry is limited to ten digits", duration: 0.5, position: HRToastPositionCenter)
return false
}
else
{
}
return true
}
A jquery solution has been implemented, and source code is available in github at: https://github.com/jackmoore/autosize .
I went off of peter.petrov's answer but let me explain where you make the file edits to change it to a relative path.
Simply edit "AXLAPIService.java" and change
url = new URL("file:C:users..../schema/current/AXLAPI.wsdl");
to
url = new URL("file:./schema/current/AXLAPI.wsdl");
or where ever you want to store it.
You can still work on packaging the wsdl file into the meta-inf folder in the jar but this was the simplest way to get it working for me.
SELECT ROUND(SUM(amount)::numeric, 2) AS total_amount
FROM transactions
Gives: 200234.08
They are called the Positional Parameters.
3.4.1 Positional Parameters
A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).
When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.
You could use the Add-Content cmdlet. Maybe it is a little faster than the other solutions, because I don't retrieve the content of the first file.
gc .\file2.txt| Add-Content -Path .\file1.txt
Use of Hive, Hbase and Pig w.r.t. my real time experience in different projects.
Hive is used mostly for:
Analytics purpose where you need to do analysis on history data
Generating business reports based on certain columns
Efficiently managing the data together with metadata information
Joining tables on certain columns which are frequently used by using bucketing concept
Efficient Storing and querying using partitioning concept
Not useful for transaction/row level operations like update, delete, etc.
Pig is mostly used for:
Frequent data analysis on huge data
Generating aggregated values/counts on huge data
Generating enterprise level key performance indicators very frequently
Hbase is mostly used:
For real time processing of data
For efficiently managing Complex and nested schema
For real time querying and faster result
For easy Scalability with columns
Useful for transaction/row level operations like update, delete, etc.
Adding overflow:auto
before setting overflow-y
seems to do the trick in Google Chrome.
{
width:249px;
height:299px;
background-color:Gray;
overflow: auto;
overflow-y: scroll;
max-width:230px;
max-height:100px;
}
None of previous answers worked for me.
I noticed that my project was referencing another project using the System.Web.Mvc
reference from the .NET Framework.
I just deleted that assembly and added the "Microsoft.AspNet.Mvc" NuGet package and that fixed my problem.
Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).
To specifically address your problem, you should remove the brackets after donothing
in your setTimeout
call, and make waitsecs
a number not a string:
console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');
But that won't stop execution; "after" will be logged before your function runs.
To wait properly, you can use anonymous functions:
console.log('before');
setTimeout(function(){
console.log('after');
},500);
All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval
/ clearInterval
if it needs to loop.
No, you can not add background color to SVG elements. You can do it programmatically with d3.
var text = d3.select("text");
var bbox = text.node().getBBox();
var padding = 2;
var rect = self.svg.insert("rect", "text")
.attr("x", bbox.x - padding)
.attr("y", bbox.y - padding)
.attr("width", bbox.width + (padding*2))
.attr("height", bbox.height + (padding*2))
.style("fill", "red");
ng-if="select.name.indexOf('?') !== -1"
Have a try:
function stop(){_x000D_
var video = document.getElementById("video");_x000D_
video.load();_x000D_
}
_x000D_
Here is what I was trying to do and how I did it. I think you wanted to do something similar. I had a table with several rows and on each row I had an input with type image. I wanted to pass an id when the user clicked that image button. As you noticed the value in the tag is ignored. Instead I added a hidden input at the top of my table and using javascript I put the correct id there before I post the form.
<input type="image" onclick="$('#hiddenInput').val(rowId) src="...">
This way the correct id will be submitted with your form.
fatal error: unexpectedly found nil while unwrapping an Optional value
:) hopes it will help for some struggled people .
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
First, to convert a Categorical column to its numerical codes, you can do this easier with: dataframe['c'].cat.codes
.
Further, it is possible to select automatically all columns with a certain dtype in a dataframe using select_dtypes
. This way, you can apply above operation on multiple and automatically selected columns.
First making an example dataframe:
In [75]: df = pd.DataFrame({'col1':[1,2,3,4,5], 'col2':list('abcab'), 'col3':list('ababb')})
In [76]: df['col2'] = df['col2'].astype('category')
In [77]: df['col3'] = df['col3'].astype('category')
In [78]: df.dtypes
Out[78]:
col1 int64
col2 category
col3 category
dtype: object
Then by using select_dtypes
to select the columns, and then applying .cat.codes
on each of these columns, you can get the following result:
In [80]: cat_columns = df.select_dtypes(['category']).columns
In [81]: cat_columns
Out[81]: Index([u'col2', u'col3'], dtype='object')
In [83]: df[cat_columns] = df[cat_columns].apply(lambda x: x.cat.codes)
In [84]: df
Out[84]:
col1 col2 col3
0 1 0 0
1 2 1 1
2 3 2 0
3 4 0 1
4 5 1 1
If you are looking for a rapid, normalized cross correlation in either one or two dimensions
I would recommend the openCV library (see http://opencv.willowgarage.com/wiki/ http://opencv.org/). The cross-correlation code maintained by this group is the fastest you will find, and it will be normalized (results between -1 and 1).
While this is a C++ library the code is maintained with CMake and has python bindings so that access to the cross correlation functions is convenient. OpenCV also plays nicely with numpy. If I wanted to compute a 2-D cross-correlation starting from numpy arrays I could do it as follows.
import numpy
import cv
#Create a random template and place it in a larger image
templateNp = numpy.random.random( (100,100) )
image = numpy.random.random( (400,400) )
image[:100, :100] = templateNp
#create a numpy array for storing result
resultNp = numpy.zeros( (301, 301) )
#convert from numpy format to openCV format
templateCv = cv.fromarray(numpy.float32(template))
imageCv = cv.fromarray(numpy.float32(image))
resultCv = cv.fromarray(numpy.float32(resultNp))
#perform cross correlation
cv.MatchTemplate(templateCv, imageCv, resultCv, cv.CV_TM_CCORR_NORMED)
#convert result back to numpy array
resultNp = np.asarray(resultCv)
For just a 1-D cross-correlation create a 2-D array with shape equal to (N, 1 ). Though there is some extra code involved to convert to an openCV format the speed-up over scipy is quite impressive.
try this:
=(RIGHT(E9;3))+(MID(E9;7;2)*1000)+(MID(E9;5;2)*3600000)+(LEFT(E9;2)*216000000)
Maybe you need to change semi-colon by coma...
There are several rules ( applied in this order ) :
!important
always takes precedence.In your case its rule 3 that applies.
Specificity for single selectors from highest to lowest:
#main
selects <div id="main">
).myclass
), attribute selectors (ex.: [href=^https:]
) and pseudo-classes (ex.: :hover
)div
) and pseudo-elements (ex.: ::before
)To compare the specificity of two combined selectors, compare the number of occurences of single selectors of each of the specificity groups above.
Example: compare #nav ul li a:hover
to #nav ul li.active a::after
#nav
):hover
and .active
)ul li a
) for the first and 4 for the second (ul li a ::after
), thus the second combined selector is more specific.Uri is serializable, so you can save strings and convert it back when loading
when saving
String str = myUri.toString();
and when loading
Uri myUri = Uri.parse(str);
You can do this through straight javascript and DOM, but I really recommend learning JQuery. Here is a function you can use to actually toggle that object.
EDIT: Adding the actual code:
Solution:
HTML snippet:
<a href="#" id="showAll" title="Show Tags">Show All Tags</a>
<ul id="tags" class="subforums" style="display:none;overflow-x: visible; overflow-y: visible; ">
<li>Tag 1</li>
<li>Tag 2</li>
<li>Tag 3</li>
<li>Tag 4</li>
<li>Tag 5</li>
</ul>
Javascript code using JQuery from Google's Content Distribution Network: https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
$(function() {
$('#showAll').click(function(){ //Adds click event listener
$('#tags').toggle('slow'); // Toggles visibility. Use the 'slow' parameter to add a nice effect.
});
});
You can test directly from this link: http://jsfiddle.net/vssJr/5/
Additional Comments on JQuery:
Someone has suggested that using JQuery for something like this is wrong because it is a 50k Library. I have a strong opinion against that.
JQuery is widely used because of the huge advantages it offers (like many other javascript frameworks). Additionally, JQuery is hosted by Content Distribution Networks (CDNs) like Google's CDN that will guarantee that the library is cached in the client's browser. It will have minimal impact on the client.
Additionally, with JQuery you can use powerful selectors, adding event listener, and use functions that are for the most part guaranteed to be cross-browser.
If you are a beginner and want to learn Javascript, please don't discount frameworks like JQuery. It will make your life so much easier.
No, you shouldn't call it explicitly because it would be called twice. Once for the manual call and another time when the scope in which the object is declared ends.
Eg.
{
Class c;
c.~Class();
}
If you really need to perform the same operations you should have a separate method.
There is a specific situation in which you may want to call a destructor on a dynamically allocated object with a placement new
but it doesn't sound something you will ever need.
According to the following article: https://www.percona.com/blog/2007/08/28/to-sql_calc_found_rows-or-not-to-sql_calc_found_rows/
If you have an INDEX on your where clause (if id is indexed in your case), then it is better not to use SQL_CALC_FOUND_ROWS and use 2 queries instead, but if you don't have an index on what you put in your where clause (id in your case) then using SQL_CALC_FOUND_ROWS is more efficient.
This code works to insert both header and footer on the first page with header center aligned and footer left aligned
\makeatletter
\let\old@ps@headings\ps@headings
\let\old@ps@IEEEtitlepagestyle\ps@IEEEtitlepagestyle
\def\confheader#1{%
% for the first page
\def\ps@IEEEtitlepagestyle{%
\old@ps@IEEEtitlepagestyle%
\def\@oddhead{\strut\hfill#1\hfill\strut}%
\def\@evenhead{\strut\hfill#1\hfill\strut}%
\def\@oddfoot{\mycopyrightnotice}
\def\@evenfoot{}
}%
\ps@headings%
}
\makeatother
\confheader{%
5$^{th}$ IEEE International Conference on Recent Advances and Innovations in Engineering - ICRAIE 2020 (IEEE Record\#51050) %EDIT HERE
}
\def\mycopyrightnotice{
{\footnotesize XXX-1-7281-8867-6/20/\$31.00~\copyright~2020 IEEE\hfill} % EDIT HERE
\gdef\mycopyrightnotice{}
}
\newcommand*{\affmark}[1][*]{\textsuperscript{#1}}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\newcommand{\ma}[1]{\mbox{\boldmath$#1$}} ```
There is no way to do so. Either use an HTML table, or put the same text on several cells.
like this:
| Can Reorder | 2nd operation |2nd operation |2nd operation |
| :---: | --- |
|1st operation|Normal Load <br/>Normal Store| Volatile Load <br/>MonitorEnter|Volatile Store<br/> MonitorExit|
|Normal Load <br/> Normal Store| | | No|
|Volatile Load <br/> MonitorEnter| No|No|No|
|Volatile store <br/> MonitorExit| | No|No|
which looks like
I know it's a little off-topic, but following up with the solution presented by Jonas Bøhmer, actually I think that MOD is the best solution to your example.
If your intention was to limit the result to one digit, MOD is the best approach to achieve it.
ie. Let's suppose that VLOOKUP(A1, B:B, 1, 0) returns 23. Your IF formula would simply make this calculation: 23 - 10 and return 13 as the result.
On the other hand, MOD(VLOOKUP(A1, B:B, 1, 0), 10) would divide 23 by 10 and show the remainder: 3.
Back to the main topic, when I need to use a formula that repeats some part, I usually put it on another cell and then hide it as some people already suggested.
PostgreSQL 9.5 and newer support INSERT ... ON CONFLICT (key) DO UPDATE
(and ON CONFLICT (key) DO NOTHING
), i.e. upsert.
Comparison with ON DUPLICATE KEY UPDATE
.
For usage see the manual - specifically the conflict_action clause in the syntax diagram, and the explanatory text.
Unlike the solutions for 9.4 and older that are given below, this feature works with multiple conflicting rows and it doesn't require exclusive locking or a retry loop.
The commit adding the feature is here and the discussion around its development is here.
If you're on 9.5 and don't need to be backward-compatible you can stop reading now.
PostgreSQL doesn't have any built-in UPSERT
(or MERGE
) facility, and doing it efficiently in the face of concurrent use is very difficult.
This article discusses the problem in useful detail.
In general you must choose between two options:
Using individual row upserts in a retry loop is the reasonable option if you want many connections concurrently trying to perform inserts.
The PostgreSQL documentation contains a useful procedure that'll let you do this in a loop inside the database. It guards against lost updates and insert races, unlike most naive solutions. It will only work in READ COMMITTED
mode and is only safe if it's the only thing you do in the transaction, though. The function won't work correctly if triggers or secondary unique keys cause unique violations.
This strategy is very inefficient. Whenever practical you should queue up work and do a bulk upsert as described below instead.
Many attempted solutions to this problem fail to consider rollbacks, so they result in incomplete updates. Two transactions race with each other; one of them successfully INSERT
s; the other gets a duplicate key error and does an UPDATE
instead. The UPDATE
blocks waiting for the INSERT
to rollback or commit. When it rolls back, the UPDATE
condition re-check matches zero rows, so even though the UPDATE
commits it hasn't actually done the upsert you expected. You have to check the result row counts and re-try where necessary.
Some attempted solutions also fail to consider SELECT races. If you try the obvious and simple:
-- THIS IS WRONG. DO NOT COPY IT. It's an EXAMPLE.
BEGIN;
UPDATE testtable
SET somedata = 'blah'
WHERE id = 2;
-- Remember, this is WRONG. Do NOT COPY IT.
INSERT INTO testtable (id, somedata)
SELECT 2, 'blah'
WHERE NOT EXISTS (SELECT 1 FROM testtable WHERE testtable.id = 2);
COMMIT;
then when two run at once there are several failure modes. One is the already discussed issue with an update re-check. Another is where both UPDATE
at the same time, matching zero rows and continuing. Then they both do the EXISTS
test, which happens before the INSERT
. Both get zero rows, so both do the INSERT
. One fails with a duplicate key error.
This is why you need a re-try loop. You might think that you can prevent duplicate key errors or lost updates with clever SQL, but you can't. You need to check row counts or handle duplicate key errors (depending on the chosen approach) and re-try.
Please don't roll your own solution for this. Like with message queuing, it's probably wrong.
Sometimes you want to do a bulk upsert, where you have a new data set that you want to merge into an older existing data set. This is vastly more efficient than individual row upserts and should be preferred whenever practical.
In this case, you typically follow the following process:
CREATE
a TEMPORARY
table
COPY
or bulk-insert the new data into the temp table
LOCK
the target table IN EXCLUSIVE MODE
. This permits other transactions to SELECT
, but not make any changes to the table.
Do an UPDATE ... FROM
of existing records using the values in the temp table;
Do an INSERT
of rows that don't already exist in the target table;
COMMIT
, releasing the lock.
For example, for the example given in the question, using multi-valued INSERT
to populate the temp table:
BEGIN;
CREATE TEMPORARY TABLE newvals(id integer, somedata text);
INSERT INTO newvals(id, somedata) VALUES (2, 'Joe'), (3, 'Alan');
LOCK TABLE testtable IN EXCLUSIVE MODE;
UPDATE testtable
SET somedata = newvals.somedata
FROM newvals
WHERE newvals.id = testtable.id;
INSERT INTO testtable
SELECT newvals.id, newvals.somedata
FROM newvals
LEFT OUTER JOIN testtable ON (testtable.id = newvals.id)
WHERE testtable.id IS NULL;
COMMIT;
MERGE
on the PostgreSQL wikiMERGE
?SQL-standard MERGE
actually has poorly defined concurrency semantics and is not suitable for upserting without locking a table first.
It's a really useful OLAP statement for data merging, but it's not actually a useful solution for concurrency-safe upsert. There's lots of advice to people using other DBMSes to use MERGE
for upserts, but it's actually wrong.
INSERT ... ON DUPLICATE KEY UPDATE
in MySQLMERGE
from MS SQL Server (but see above about MERGE
problems)MERGE
from Oracle (but see above about MERGE
problems)The answer is already posted but note that this will pass the ArrayList by reference. So if you make any changes to the list in the function it will be affected to the original list also.
<access-modfier> <returnType> AnalyseArray(ArrayList<Integer> list)
{
//analyse the list
//return value
}
call it like this:
x=AnalyseArray(list);
or pass a copy of ArrayList:
x=AnalyseArray(list.clone());
A possible CSS ONLY solution can be achived with position: sticky;
The browser support is actually really good: https://caniuse.com/#search=position%3A%20sticky
here is an example: https://jsfiddle.net/0vcoa43L/7/
You can generate a stack trace and use the informations in the StackTraceElements.
For example an utility class can return you the calling class name :
public class KDebug {
public static String getCallerClassName() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
for (int i=1; i<stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().equals(KDebug.class.getName()) && ste.getClassName().indexOf("java.lang.Thread")!=0) {
return ste.getClassName();
}
}
return null;
}
}
If you call KDebug.getCallerClassName()
from bar()
, you'll get "foo"
.
Now supposing you want to know the class of the method calling bar
(which is more interesting and maybe what you really wanted). You could use this method :
public static String getCallerCallerClassName() {
StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
String callerClassName = null;
for (int i=1; i<stElements.length; i++) {
StackTraceElement ste = stElements[i];
if (!ste.getClassName().equals(KDebug.class.getName())&& ste.getClassName().indexOf("java.lang.Thread")!=0) {
if (callerClassName==null) {
callerClassName = ste.getClassName();
} else if (!callerClassName.equals(ste.getClassName())) {
return ste.getClassName();
}
}
}
return null;
}
Is that for debugging ? If not, there may be a better solution to your problem.