public class testCrop extends AppCompatActivity {
ImageView iv;
String imagePath = "https://style.pk/wp-content/uploads/2015/07/omer-Shahzad-performed-umrah-600x548.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testcrpop);
iv = (ImageView) findViewById(R.id.testCrop);
imageDownload image = new imageDownload(testCrop.this, iv);
image.execute(imagePath);
}
class imageDownload extends AsyncTask<String, Integer, Bitmap> {
Context context;
ImageView imageView;
Bitmap bitmap;
InputStream in = null;
int responseCode = -1;
//constructor.
public imageDownload(Context context, ImageView imageView) {
this.context = context;
this.imageView = imageView;
}
@Override
protected void onPreExecute() {
}
@Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
in = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(in);
in.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap data) {
imageView.setImageBitmap(data);
saveImage(data);
}
private void saveImage(Bitmap data) {
File createFolder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"test");
createFolder.mkdir();
File saveImage = new File(createFolder,"downloadimage.jpg");
try {
OutputStream outputStream = new FileOutputStream(saveImage);
data.compress(Bitmap.CompressFormat.JPEG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Make sure you added permission to write data in memory
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
In a ASP.NET Core project you can use the QueryHelpers
class, available in the Microsoft.AspNetCore.WebUtilities
namespace for ASP.NET Core, or the .NET Standard 2.0 NuGet package for other consumers:
// using Microsoft.AspNetCore.WebUtilities;
var query = new Dictionary<string, string>
{
["foo"] = "bar",
["foo2"] = "bar2",
// ...
};
var response = await client.GetAsync(QueryHelpers.AddQueryString("/api/", query));
128 characters. This is the max length of the sysname
datatype (nvarchar(128)
).
5623125698541159
is treated as a single number (out of range of int
on most architecture). You need to write numbers in your file as
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
for 16 numbers.
If your file has input
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
then change %d
specifier in your fscanf
to %d,
.
fscanf(myFile, "%d,", &numberArray[i] );
Here is your full code after few modifications:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
Three steps needed:
Explicitly mark SSL2.0, TLS1.0, TLS1.1 as forbidden on your server machine, by adding Enabled=0
and DisabledByDefault=1
to your registry (the full path is HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols
). See screen for details
Explicitly enable TLS1.2
by following the steps from 1. Just use Enabled=1
and DisabledByDefault=0
respectively.
NOTE: verify server version: Windows Server 2003
does not support the TLS 1.2
protocol
Enable TLS1.2
only on app level, like @John Wu suggested above.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
Hope this guide helps.
UPDATE As @Subbu mentioned: Official guide
If it is a the end of the string, you can also use chomp
:
"hello".chomp("llo") #=> "he"
It is better to use the for...of statement, if the string contains unicode characters, because of the different byte size.
for(var c of "tree ?") { console.log(c); }
//"A".length === 3
My best advise when having the error is to use [] braquets to sorround table names, the abbreviation of tables causes sometimes errors, (sometime table abbreviations just work fine...weird)
This is what you're looking for.
I had this problem too. And like you, the answer is very hard to find. But there IS an easy way to get the ViewHolder from a specific position (something you'll probably do a lot in the Adapter).
myRecyclerView.findViewHolderForAdapterPosition(pos);
NOTE: If the View has been recycled, this will return null
. Thanks to Michael for quickly catching my important omission.
There's a short overview at MinGW-w64 Wiki:
Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?
The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.
The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.
GCC GNU about Exception Handling:
GCC supports two methods for exception handling (EH):
- DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
- A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.
[...]
Structured Exception Handling (SEH)
Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]
See also:
I had a problem once where the Global.asax and Global.asax.cs were not actually copied to IIS folder by the deployment scripts... So it worked when debugging on the development server, but not under IIS.
You can use standard STL function distance as mentioned before
index = std::distance(s.begin(), it);
Also, you can access string and some other containers with the c-like interface:
for (i=0;i<string1.length();i++) string1[i];
download this app from here it will help you to rum all commands. I have run netcfg and it gives the result as attached in screen.
To remove the default text, on clicking the element:
$('input:text').click(
function(){
$(this).val('');
});
I would, though, suggest using focus()
instead:
$('input:text').focus(
function(){
$(this).val('');
});
Which responds to keyboard events too (the tab key, for example). Also, you could use the placeholder
attribute in the element:
<input type="text" placeholder="default text" />
Which will clear on focus of the element, and reappear if the element remains empty/user doesn't input anything.
You can use the properties tab in eclipse to set various values.
here are all the possible values
Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType
Use sqlalchemy's text function to remove the interpretation of special characters:
Note the use of the function text("your_insert_statement")
below. What it does is communicate to sqlalchemy that all of the questionmarks and percent signs in the passed in string should be considered as literals.
import sqlalchemy
from sqlalchemy import text
from sqlalchemy.orm import sessionmaker
from datetime import datetime
import re
engine = sqlalchemy.create_engine("mysql+mysqlconnector://%s:%s@%s/%s"
% ("your_username", "your_password", "your_hostname_mysql_server:3306",
"your_database"),
pool_size=3, pool_recycle=3600)
conn = engine.connect()
myfile = open('access2.log', 'r')
lines = myfile.readlines()
penguins = []
for line in lines:
elements = re.split('\s+', line)
print "item: " + elements[0]
linedate = datetime.fromtimestamp(float(elements[0]))
mydate = linedate.strftime("%Y-%m-%d %H:%M:%S.%f")
penguins.append(text(
"insert into your_table (foobar) values('%%%????')"))
for penguin in penguins:
print penguin
conn.execute(penguin)
conn.close()
What to do to correct this is create a file called php.ini and save it in the same location as your .htaccess file and enter the following code instead:
upload_max_filesize = "250M"
post_max_size = "250M"
You need to add the path to Tomcat's /lib/servlet-api.jar
file to the compile time classpath.
javac -cp .;/path/to/Tomcat/lib/servlet-api.jar com/example/MyServletClass.java
The classpath is where Java needs to look for imported dependencies. It will otherwise default to the current folder which is included as .
in the above example. The ;
is the path separator for Windows; if you're using an Unix based OS, then you need to use :
instead.
If you're still facing the same complation error, and you're actually using Tomcat 10 or newer, then you should be migrating the imports in your source code from javax.*
to jakarta.*
.
import jakarta.servlet.*;
import jakarta.servlet.http.*;
faced the same issue, the solution that worked for me:
Instead of mocking the service interface, I used @InjectMocks to mock the service implementation:
@InjectMocks
private exampleServiceImpl exampleServiceMock;
instead of :
@Mock
private exampleService exampleServiceMock;
Amazon's CloudFront content delivery network can now be configured to pass this information through as a header. Given Amazon's size (they're big and stable, not going anywhere) and this is configuration over code (no third-party API to learn or code to maintain), all around believe this to be the best option.
If you do not use AWS CloudFront, I'd look into seeing if your CDN has a similar header option that can be turned on. Usually the large providers are quick to push for feature parity. And if you are not using a CDN, you could put CloudFront in front of your infrastructure and simply set the origin to resolve to whatever you are currently using.
Additionally, it also makes sense to resolve this at the CDN level. Your CDN is already having to figure out geo location to route the user to the nearest content node, might as well pass this information along and not figure it out twice through a third party API (this becomes chokepoint for your app, waiting for a geo location lookup to resolve). No need to do this work twice (and the second time, arguably less resilient [e.g., 3rd party geo lookup]).
https://aws.amazon.com/blogs/aws/enhanced-cloudfront-customization/
Geo-Targeting – CloudFront will detect the user’s country of origin and pass along the county code to you in the
CloudFront-Viewer-Country
header. You can use this information to customize your responses without having to use URLs that are specific to each country.
just wanna add another easy way to do this: If your ImageButton remains its background and you don't set it to null, it will work like a normal button and will show the click animation while clicking exactly like other buttons.The way to hide the background while it is still there:
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="1dp"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:paddingTop="1dp"
android:src="@drawable/squareicon" />
The paddings won't let the background be visible and make the button act like other buttons.
You can try this function
/**
* Gets the request parameter.
*
* @param string $key The query parameter
* @param string $default The default value to return if not found
*
* @return string The request parameter.
*/
function get_request_parameter( $key, $default = '' ) {
// If not request set
if ( ! isset( $_REQUEST[ $key ] ) || empty( $_REQUEST[ $key ] ) ) {
return $default;
}
// Set so process it
return strip_tags( (string) wp_unslash( $_REQUEST[ $key ] ) );
}
Here is what is happening in the function
Here three things are happening.
All of this information plus more info on the thinking behind the function can be found on this link https://www.intechgrity.com/correct-way-get-url-parameter-values-wordpress/
Async:
fs.readFile('test.txt', 'utf8', callback);
Sync:
var content = fs.readFileSync('test.txt', 'utf8');
In order to use my example,Your file "abc.txt" needs to look like:
[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"
Then in your software you can use the config parser:
import ConfigParser
and then in you code:
configParser = ConfigParser.RawConfigParser()
configFilePath = r'c:\abc.txt'
configParser.read(configFilePath)
Use case:
self.path = configParser.get('your-config', 'path1')
*Edit (@human.js)
in python 3, ConfigParser is renamed to configparser (as described here)
One extra note: it seems that all public ways of creating a new String
instance involves necessarily the copy of whatever buffer you are working with, be it a char[]
, a StringBuffer
or a StringBuilder
. From the String
javadoc (and is repeated in the respective toString
methods from the other classes):
The contents of the character array are copied; subsequent modification of the character array does not affect the newly created string.
So you'll end up having a possibly big memory copy operation after the "fast filling" of the array. The only solution that may avoid this issue is the one from @mlk, if you can manage working directly with the proposed CharSequence
implementation (what may be the case).
PS: I would post this as a comment but I don't have enough reputation to do that yet.
Note: If you have written any crash handler yourself, then the core might not get generated. So search for code with something on the line:
signal(SIGSEGV, <handler> );
so the SIGSEGV will be handled by handler and you will not get the core dump.
What's a "block scheme"?
If I were drawing it, I might draw a box with "for each x in y" written in it.
If you're drawing a flowchart, there's always a loop with a decision box.
Nassi-Schneiderman diagrams have a loop construct you could use.
Changing my header to the following solve the problem:
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
Try this:
var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));
This should return true
.
UPDATED: Added isNaN
check to handle the case commented by Julian H. Lam
Given an OnTouchListener
private View.OnTouchListener handleTouch = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "touched down");
break;
case MotionEvent.ACTION_MOVE:
Log.i("TAG", "moving: (" + x + ", " + y + ")");
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "touched up");
break;
}
return true;
}
};
set on some view:
myView.setOnTouchListener(handleTouch);
This gives you the touch event coordinates relative to the view that has the touch listener assigned to it. The top left corner of the view is (0, 0)
. If you move your finger above the view, then y
will be negative. If you move your finger left of the view, then x
will be negative.
int x = (int)event.getX();
int y = (int)event.getY();
If you want the coordinates relative to the top left corner of the device screen, then use the raw values.
int x = (int)event.getRawX();
int y = (int)event.getRawY();
I know this question is for Bootstrap 3, but as some Bootstrap 4 related question are redirected to this one as duplicates, here's the snippet Bootstrap 4-compatible:
$.validator.setDefaults({
highlight: function(element) {
$(element).closest('.form-group').addClass('has-danger');
},
unhighlight: function(element) {
$(element).closest('.form-group').removeClass('has-danger');
},
errorElement: 'small',
errorClass: 'form-control-feedback d-block',
errorPlacement: function(error, element) {
if(element.parent('.input-group').length) {
error.insertAfter(element.parent());
} else if(element.prop('type') === 'checkbox') {
error.appendTo(element.parent().parent().parent());
} else if(element.prop('type') === 'radio') {
error.appendTo(element.parent().parent().parent());
} else {
error.insertAfter(element);
}
},
});
The few differences are:
has-danger
instead of has-error
Forward declare class B
and swap order of A
and B
definitions: 1st B
and 2nd A
. You can not call methods of forward declared B
class.
I think it's very fun to come up with ways to solve this. Below are some.
(All functions below assume argument is a single character. Change to n[0]
to enforce it)
function isCharDigit(n){
return !!n.trim() && n > -1;
}
function isCharDigit(n){
return !!n.trim() && n*0==0;
}
function isCharDigit(n){
return !!n.trim() && !!Number(n+.1); // "+.1' to make it work with "." and "0" Chars
}
var isCharDigit = (function(){
var a = [1,1,1,1,1,1,1,1,1,1];
return function(n){
return !!a[n] // check if `a` Array has anything in index 'n'. Cast result to boolean
}
})();
function isCharDigit(n){
return !!n.trim() && !isNaN(+n);
}
var str = ' 90ABcd#?:.+', char;
for( char of str )
console.log( char, isCharDigit(char) );
finalize()
is called just before garbage collection. It is not called when an object goes out of scope. This means that you cannot know when or even if finalize()
will be executed.
Example:
If your program end before garbage collector occur, then finalize()
will not execute. Therefore, it should be used as backup procedure to ensure the proper handling of other resources, or for special use applications, not as the means that your program uses in its normal operation.
The accepted answer is close... but no cigar!
Use textContent
instead of innerHTML
if you strictly want a string to be returned to you.
innerHTML
can have the side effect of giving you a node element if there's other dom elements in there. textContent
will guard against this possibility.
You can check it by regular expression
public boolean isValid(String strEmail)
{
pattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
matcher = pattern.matcher(strEmail);
if (strEmail.isEmpty()) {
return false;
} else if (!matcher.matches()) {
return false;
}
else
{
return true;
}
}
I also had a working system that suddenly stopped working with the described error.
After furtling around in my /lib/modules it would appear that the vboxvfs
module is no more. Instead modprobe vboxsf
was the required incantation to get things restarted.
Not sure when that change ocurred, but it caught me out.
This can also be done in the GUI:
Kotlin version would be
fun getHeaderInterceptor():Interceptor{
return object : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request =
chain.request().newBuilder()
.header(Headers.KEY_AUTHORIZATION, "Bearer.....")
.build()
return chain.proceed(request)
}
}
}
private fun createOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.apply {
if(BuildConfig.DEBUG){
this.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
}
}
.addInterceptor(getHeaderInterceptor())
.build()
}
Change the .find
to .filter
...
After doing some search i got solution from android developer guide
PendingIntent contentIntent ;
Intent intent = new Intent(this,TestActivity.class);
intent.putExtra("extra","Test");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ArticleDetailedActivity.class);
contentIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
To Get Intent extra value in Test Activity class you need to write following code :
Intent intent = getIntent();
String extra = intent.getStringExtra("extra") ;
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
$('#timePicker').datetimepicker({
// dateFormat: 'dd-mm-yy',
format:'DD/MM/YYYY HH:mm:ss',
minDate: getFormattedDate(new Date())
});
function getFormattedDate(date) {
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear().toString().slice(2);
return day + '-' + month + '-' + year;
}
You need to pass datepicker() the date formatted correctly.
Cookies are your best bet. Look for the jquery cookie plugin.
Cookies are designed for this sort of situation -- you want to keep some information about this client on client side. Just be aware that cookies are passed back and forth on every web request so you can't store large amounts of data in there. But just a simple answer to a question should be fine.
If "sudo apt-get install php-curl" command doesnt work and display error We should run this code before install curl.
I know this a very much late reply but I saw this query recently And found a working scenario,
OnClick of Submit use the below code:
$('#Submit').click(function ()
{ $(this).html('<img src="icon-loading.gif" />'); // A GIF Image of Your choice
return false });
To Stop the Gif use the below code:
$('#Submit').ajaxStop();
The python interpreter compiles the *.py script file and saves the results of the compilation to the __pycache__
directory.
When the project is executed again, if the interpreter identifies that the *.py script has not been modified, it skips the compile step and runs the previously generated *.pyc file stored in the __pycache__
folder.
When the project is complex, you can make the preparation time before the project is run shorter. If the program is too small, you can ignore that by using python -B abc.py
with the B
option.
The lazy/hurry alternative (Dotnet Core 2.2):
[HttpGet("method1-{item}")]
public string Method1(var item) {
return "hello" + item;}
[HttpGet("method2-{item}")]
public string Method2(var item) {
return "world" + item;}
Calling them :
localhost:5000/api/controllername/method1-42
"hello42"
localhost:5000/api/controllername/method2-99
"world99"
Using pathlib
I came up this one-liner to get the size of a folder:
sum(file.stat().st_size for file in Path(folder).rglob('*'))
And this is what I came up with for a nicely formatted output:
from pathlib import Path
def get_folder_size(folder):
return ByteSize(sum(file.stat().st_size for file in Path(folder).rglob('*')))
class ByteSize(int):
_kB = 1024
_suffixes = 'B', 'kB', 'MB', 'GB', 'PB'
def __new__(cls, *args, **kwargs):
return super().__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
self.bytes = self.B = int(self)
self.kilobytes = self.kB = self / self._kB**1
self.megabytes = self.MB = self / self._kB**2
self.gigabytes = self.GB = self / self._kB**3
self.petabytes = self.PB = self / self._kB**4
*suffixes, last = self._suffixes
suffix = next((
suffix
for suffix in suffixes
if 1 < getattr(self, suffix) < self._kB
), last)
self.readable = suffix, getattr(self, suffix)
super().__init__()
def __str__(self):
return self.__format__('.2f')
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, super().__repr__())
def __format__(self, format_spec):
suffix, val = self.readable
return '{val:{fmt}} {suf}'.format(val=val, fmt=format_spec, suf=suffix)
def __sub__(self, other):
return self.__class__(super().__sub__(other))
def __add__(self, other):
return self.__class__(super().__add__(other))
def __mul__(self, other):
return self.__class__(super().__mul__(other))
def __rsub__(self, other):
return self.__class__(super().__sub__(other))
def __radd__(self, other):
return self.__class__(super().__add__(other))
def __rmul__(self, other):
return self.__class__(super().__rmul__(other))
Usage:
>>> size = get_folder_size("c:/users/tdavis/downloads")
>>> print(size)
5.81 GB
>>> size.GB
5.810891855508089
>>> size.gigabytes
5.810891855508089
>>> size.PB
0.005674699077644618
>>> size.MB
5950.353260040283
>>> size
ByteSize(6239397620)
I also came across this question, which has some more compact and probably more performant strategies for printing file sizes.
TouchableOpacity
extents TouchableWithoutFeedback
, so you can just use the disabled
property :
<TouchableOpacity disabled={true}>
<Text>I'm disabled</Text>
</TouchableOpacity>
React Native TouchableWithoutFeedback #disabled documentation
The new Pressable API has a disabled
option too :
<Pressable disable={true}>
{({ pressed }) => (
<Text>I'm disabled</Text>
)}
</Pressable>
SQLDataReaders are forward-only. You're essentially doing this:
count++; // initially 1
.DataBind(); //consuming all the records
//next iteration on
.Read()
//we've now come to end of resultset, thanks to the DataBind()
//count is still 1
You could do this instead:
if (reader.HasRows)
{
rep.DataSource = reader;
rep.DataBind();
}
int count = rep.Items.Count; //somehow count the num rows/items `rep` has.
Before you run a select query, run this:
SET SERVEROUT ON SIZE 6000
SELECT XMLAGG(XMLELEMENT(E,SUPLR_SUPLR_ID||',')).EXTRACT('//text()') "SUPPLIER"
FROM SUPPLIERS;
In Windows 10 preview build with PowerShell 5, I can see that you can do:
$info = Get-Package -Name YourInstalledProduct
$info.Metadata["ProductCode"]
Not familiar with even not sure if all products has UpgradeCode, but according to this post you need to search UpgradeCode from this registry path:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Installer\UpgradeCodes
Unfortunately, the registry key values are the ProductCode and the registry keys are the UpgradeCode.
Using the re
module:
import re
re.sub('\s+', '_', "This should be connected") # This_should_be_connected
re.sub('\s+', '_', 'And so\tshould this') # And_so_should_this
Unless you have multiple spaces or other whitespace possibilities as above, you may just wish to use string.replace
as others have suggested.
This should fulfill your requirements.
ABC:\s*(\(\D+\)\s*.*?)\\n
Here it is with some tests http://www.regexplanet.com/cookbook/ahJzfnJlZ2V4cGxhbmV0LWhyZHNyDgsSBlJlY2lwZRiEjiUM/index.html
Futher reading on regular expressions: http://www.regular-expressions.info/characters.html
You can use the &
operator on the Method
instance of your method to convert the method to a block.
Example:
def foo(arg)
p arg
end
def bar(&block)
p 'bar'
block.call('foo')
end
bar(&method(:foo))
More details at http://weblog.raganwald.com/2008/06/what-does-do-when-used-as-unary.html
inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,
android:screenOrientation="landscape"
for landscape orientation and for portrait add the following code,
android:screenOrientation="portrait"
Solution to resolve issue in Local env's
I had my front-end code running in http://localhost:3000 and my API(Backend code) running at http://localhost:5000
Was using fetch API to call the API. Initially, it was throwing "cors" error. Then added this below code in my Backend API code, allowing origin and header from anywhere.
let allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Headers', "*");
next();
}
app.use(allowCrossDomain);
However you must restrict origins in case of other environments like stage, prod.
Strictly NO for higher environments.
JSONP is JSON with padding. That is, you put a string at the beginning and a pair of parentheses around it. For example:
//JSON
{"name":"stackoverflow","id":5}
//JSONP
func({"name":"stackoverflow","id":5});
The result is that you can load the JSON as a script file. If you previously set up a function called func
, then that function will be called with one argument, which is the JSON data, when the script file is done loading. This is usually used to allow for cross-site AJAX with JSON data. If you know that example.com is serving JSON files that look like the JSONP example given above, then you can use code like this to retrieve it, even if you are not on the example.com domain:
function func(json){
alert(json.name);
}
var elm = document.createElement("script");
elm.setAttribute("type", "text/javascript");
elm.src = "http://example.com/jsonp";
document.body.appendChild(elm);
Rather than placing an extra scanner.nextLine()
each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)
import java.util.Scanner;
class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\n");
System.out.print("Enter an index: ");
int index = scanner.nextInt();
System.out.print("Enter a sentence: ");
String sentence = scanner.next();
System.out.println("\nYour sentence: " + sentence);
System.out.println("Your index: " + index);
}
}
Thus, to read a line of input, you only need scanner.next()
that has the same behavior delimiter-wise of next{Int, Double, ...}
The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3
, 3<space>
and 3<space>whatever
while the former only accepts 3
on a line on its own
After working through a couple of issues in dependent projects, like the accepted answer says, I was still getting this error. I could see the file did indeed exist at the location it was looking in, but for some reason Visual Studio would not recognize it. Rebuilding the solution would clear all dependent projects and then would not rebuild them, but building individually would generate the .dll's. I used msbuild <project-name>.csproj
in the developer PowerShell terminal in Visual Studio, meaning to get some more detailed debugging information--but it built for me instead! Try using msbuild
against persistant build errors; you can use the --verbosity:
option to get more output, as outlined in the docs.
Here is a shell script that uses Awk's gsub function to replace the text you're searching for with the proper escape sequence to display it in bright red:
#! /bin/bash
awk -vstr=$1 'BEGIN{repltext=sprintf("%c[1;31;40m&%c[0m", 0x1B,0x1B);}{gsub(str,repltext); print}' $2
Use it like so:
$ ./cgrep pattern [file]
Unfortunately, it doesn't have all the functionality of grep.
For more information , you can refer to an article "So You Like Color" in Linux Journal
It depends on your requirements.
Page Load : Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data. See Handling Inherited Events.
Prerender :Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost. See Handling Inherited Events.
Reference: Control Execution Lifecycle MSDN
Try to read about
ASP.NET Page Life Cycle Overview ASP.NET
Regards
They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.
File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish
But if you do not have samples loaded, then download it using the below steps
Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install
To escape the backslash, simply use 2 of them, like this:
\\
Fast, simple, but maybe not always right:
>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']
More traditional if you need to get numbers:
new_list = []
for value in mylist:
try:
new_list.append(int(value))
except ValueError:
continue
Note: The result has integers. Convert them back to strings if needed, replacing the lines above with:
try:
new_list.append(str(int(value)))
You need to use MM
as mm
stands for minutes.
There are two ways of producing month pattern.
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); //outputs month in numeric way, 2013-02-01
SimpleDateFormat sdf2 = new SimpleDateFormat("dd-MMM-yyyy"); // Outputs months as follows, 2013-Feb-01
Full coding snippet:
String startDate="01-Feb-2013"; // Input String
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
System.out.println(sqlStartDate); // Outputs : 2013-02-01
Object.keys(obj).map(k => `${encodeURIComponent(k)}=${encodeURIComponent(obj[k])}`).join('&')
This worked for me
For folks using MongoClient
try this:
MongoClient.connect(connectionurl,
{useUnifiedTopology: true, useNewUrlParser: true}, callback() {
For mongoose:
mongoose.connect(connectionurl,
{useUnifiedTopology: true, useNewUrlParser: true}).then(()=>{
Remove other connectionOptions
If you want ripple when tapped, it can be given by this code :
<ImageView
...
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
...
</ImageView>
Similarly, you can implement click effect for TextView
<TextView
...
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
...
</TextView>
The compiler is complaining because you currently have the 'if(exist)' block inside of your for loop. It needs to be outside of it.
for(int i=0;i<this.customers.size();i++){
if(this.customers.get(i).getId() == id){
exist=true;
break;
}
}
if(exist) {
return this.customers.get(id);
} else {
return this.customers.get(id);
}
That being said, there are better ways to perform this search. Personally, if I were using an ArrayList, my solution would look like the one that Jon Skeet has posted.
I'm a security engineer at Facebook and this is my fault. We're testing this for some users to see if it can slow down some attacks where users are tricked into pasting (malicious) JavaScript code into the browser console.
Just to be clear: trying to block hackers client-side is a bad idea in general; this is to protect against a specific social engineering attack.
If you ended up in the test group and are annoyed by this, sorry. I tried to make the old opt-out page (now help page) as simple as possible while still being scary enough to stop at least some of the victims.
The actual code is pretty similar to @joeldixon66's link; ours is a little more complicated for no good reason.
Chrome wraps all console code in
with ((console && console._commandLineAPI) || {}) {
<code goes here>
}
... so the site redefines console._commandLineAPI
to throw:
Object.defineProperty(console, '_commandLineAPI',
{ get : function() { throw 'Nooo!' } })
This is not quite enough (try it!), but that's the main trick.
Epilogue: The Chrome team decided that defeating the console from user-side JS was a bug and fixed the issue, rendering this technique invalid. Afterwards, additional protection was added to protect users from self-xss.
I also had the same issue. Tried all ways and it didn't work out until I added the following in app.module.ts
import { Ng4LoadingSpinnerModule } from 'ng4-loading-spinner';
And add the following in your imports in app.module.ts
Ng4LoadingSpinnerModule.forRoot()
This case might be rare but I hope this helps someone out there
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
There's a method on the DataGridView called "Sort":
this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);
This will programmatically sort your datagridview.
For raw files, you should consider creating a raw folder inside res directory and then call getResources().openRawResource(resourceName)
from your activity.
That is, all-space strings are retained:
slist = list(filter(None, slist))
PROs:
slist = ' '.join(slist).split()
PROs:
slist = list(filter(str.strip, slist))
PROs:
## Build test-data
#
import random, string
nwords = 10000
maxlen = 30
null_ratio = 0.1
rnd = random.Random(0) # deterministic results
words = [' ' * rnd.randint(0, maxlen)
if rnd.random() > (1 - null_ratio)
else
''.join(random.choices(string.ascii_letters, k=rnd.randint(0, maxlen)))
for _i in range(nwords)
]
## Test functions
#
def nostrip_filter(slist):
return list(filter(None, slist))
def nostrip_comprehension(slist):
return [s for s in slist if s]
def strip_filter(slist):
return list(filter(str.strip, slist))
def strip_filter_map(slist):
return list(filter(None, map(str.strip, slist)))
def strip_filter_comprehension(slist): # waste memory
return list(filter(None, [s.strip() for s in slist]))
def strip_filter_generator(slist):
return list(filter(None, (s.strip() for s in slist)))
def strip_join_split(slist): # words without(!) spaces
return ' '.join(slist).split()
## Benchmarks
#
%timeit nostrip_filter(words)
142 µs ± 16.8 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
%timeit nostrip_comprehension(words)
263 µs ± 19.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit strip_filter(words)
653 µs ± 37.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit strip_filter_map(words)
642 µs ± 36 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit strip_filter_comprehension(words)
693 µs ± 42.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit strip_filter_generator(words)
750 µs ± 28.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
%timeit strip_join_split(words)
796 µs ± 103 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
First
Make a dir c:\command
Second Make a ll.bat
ll.bat
dir
Open project in android studio click file and click Invalidate Caches/Restart
Alternatively, can use for particular table
<table style="width:1000px; height:100px;">
<tr>
<td align="center" valign="top">Text</td> //Remove it
<td class="tableFormatter">Text></td>
</tr>
</table>
Add this css in external file
.tableFormatter
{
width:100%;
vertical-align:top;
text-align:center;
}
The Address property of a cell can get this for you:
MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
returns A1
.
The other way around can be done with the Row
and Column
property of Range
:
MsgBox Range("A1").Row & ", " & Range("A1").Column
returns 1,1
.
Padding means space between widget and widget original frame. But the margin is space between widget's original frame to boundaries other widget's frame..
Another method utilizing the dplyr package:
library(dplyr)
df <- mtcars %>%
filter(mpg > 25)
Without the chain (%>%) operator:
library(dplyr)
df <- filter(mtcars, mpg > 25)
Writing JSON to a File
import json
data = {}
data['people'] = []
data['people'].append({
'name': 'Scott',
'website': 'stackabuse.com',
'from': 'Nebraska'
})
data['people'].append({
'name': 'Larry',
'website': 'google.com',
'from': 'Michigan'
})
data['people'].append({
'name': 'Tim',
'website': 'apple.com',
'from': 'Alabama'
})
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
Reading JSON from a File
import json
with open('data.txt') as json_file:
data = json.load(json_file)
for p in data['people']:
print('Name: ' + p['name'])
print('Website: ' + p['website'])
print('From: ' + p['from'])
print('')
I've seen some terrible observer patterns here that cause memory leaks on large applications.
I might be a little late but it's as simple as this.
The watch function watches for reference changes (primitive types) if you want to watch something like array push simply use:
someArray.push(someObj); someArray = someArray.splice(0);
This will update the reference and update the watch from anywhere. Including a services getter method. Anything that's a primitive will be updated automatically.
Try it:
if (Objects.equals(gender, "Male")) {
salutation ="Mr.";
} else if (Objects.equals(gender, "Female")) {
salutation ="Ms.";
}
I have the similar problem but when I tried to remove the datatype:'json' I still have the problem. My error is executing instead of the Success
function cmd(){
var data = JSON.stringify(display1());
$.ajax({
type: 'POST',
url: '/cmd',
contentType:'application/json; charset=utf-8',
//dataType:"json",
data: data,
success: function(res){
console.log('Success in running run_id ajax')
//$.ajax({
// type: "GET",
// url: "/runid",
// contentType:"application/json; charset=utf-8",
// dataType:"json",
// data: data,
// success:function display_runid(){}
// });
},
error: function(req, err){ console.log('my message: ' + err); }
});
}
mongoDB -repair is not recommended in case of sharded cluster.
If using replica set sharded cluster, use compact command, it will rewrites and defragments all data and index files of all collections. syntax:
db.runCommand( { compact : "collection_name" } )
when used with force:true, compact runs on primary of replica set.
e.g. db.runCommand ( { command : "collection_name", force : true } )
Other points to consider: -It blocks the operations. so recommended to execute in maintenance window. -If replica sets running on different servers, needs to be execute on each member separately - In case of sharded cluster, compact needs to execute on each shard member separately. Cannot execute against mongos instance.
the $.Browser.msie is not on the latest JQuery anymore... you have to use the $.support
like below:
<script>
(function ($) {
$.support.placeholder = ('placeholder' in document.createElement('input'));
})(jQuery);
//fix for IE7 and IE8
$(function () {
if (!$.support.placeholder) {
$("[placeholder]").focus(function () {
if ($(this).val() == $(this).attr("placeholder")) $(this).val("");
}).blur(function () {
if ($(this).val() == "") $(this).val($(this).attr("placeholder"));
}).blur();
$("[placeholder]").parents("form").submit(function () {
$(this).find('[placeholder]').each(function() {
if ($(this).val() == $(this).attr("placeholder")) {
$(this).val("");
}
});
});
}
});
</script>
Set 2 properties below:
It works for me.
I will add my upgraded version of filter which able to supports next syntax:
ng-repeat="(id, item) in $ctrl.modelData | orderObjectBy:'itemProperty.someOrder':'asc'
app.filter('orderObjectBy', function(){
function byString(o, s) {
s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
s = s.replace(/^\./, ''); // strip a leading dot
var a = s.split('.');
for (var i = 0, n = a.length; i < n; ++i) {
var k = a[i];
if (k in o) {
o = o[k];
} else {
return;
}
}
return o;
}
return function(input, attribute, direction) {
if (!angular.isObject(input)) return input;
var array = [];
for(var objectKey in input) {
if (input.hasOwnProperty(objectKey)) {
array.push(input[objectKey]);
}
}
array.sort(function(a, b){
a = parseInt(byString(a, attribute));
b = parseInt(byString(b, attribute));
return direction == 'asc' ? a - b : b - a;
});
return array;
}
})
Thanks to Armin and Jason for their answers in this thread, and Alnitak in this thread.
You can also use the addClass and removeClass methods to toggle between items such as tabs.
e.g.
if($(element).hasClass("selected"))
$(element).removeClass("selected");
With Visual Studio versions 2017 and 2015, you can do this with the Code Map feature, but this feature is only available in the Enterprise Edition, not the Community or Professional versions.
Right-click on the project node in the solution explorer and select 'Show on Code Map.' This will display your .dll as a single node in a blank graph. Right-click on that node in the Code Map and select "Show Assemblies This References." This will add an additional node called "Externals" which can be expanded to show only the assemblies that are actually referenced.
I do not like method with regex, because regex can not check ranges (Integer.MIN_VALUE
, Integer.MAX_VALUE
).
If you expect int value in most cases, and not int is something uncommon, then I suggest version with Integer.valueOf
or Integer.parseInt
with NumberFormatException
catching. Advantage of this approach - your code has good readability:
public static boolean isInt(String s) {
try {
Integer.parseInt(s);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
If you need to check if String is integer, and care about perfomance then the best way will be to use java jdk implementation of Integer.parseInt
, but little modified (replacing throw with return false):
This function has good perfomence and garantee right result:
public static boolean isInt(String s) {
int radix = 10;
if (s == null) {
return false;
}
if (radix < Character.MIN_RADIX) {
return false;
}
if (radix > Character.MAX_RADIX) {
return false;
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int limit = -Integer.MAX_VALUE;
int multmin;
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+')
return false;
if (len == 1) // Cannot have lone "+" or "-"
return false;
i++;
}
multmin = limit / radix;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++), radix);
if (digit < 0) {
return false;
}
if (result < multmin) {
return false;
}
result *= radix;
if (result < limit + digit) {
return false;
}
result -= digit;
}
} else {
return false;
}
return true;
}
Just found that .Net Framework 4.5 now supports TLSv1.2
http://msdn.microsoft.com/en-us/library/system.security.authentication.sslprotocols(v=vs.110).aspx
There are two ways to use this variable:
passing it as a command line argument just like Job mentioned:
cmake -DCMAKE_INSTALL_PREFIX=< install_path > ..
assigning value to it in CMakeLists.txt
:
SET(CMAKE_INSTALL_PREFIX < install_path >)
But do remember to place it BEFORE PROJECT(< project_name>)
command, otherwise it will not work!
document.getElementById("EDTVALOR").addEventListener("change", function() {
this.value = this.value.replace(",", ".");
this.value = parseFloat(this.value).toFixed(2);
if (this.value < 0) {
this.value = 0;
}
this.value = this.value.replace(".", ",");
this.value = this.value.replace("NaN", "0");
});
Different W3C specifications define different sets of "Node" types.
Thus, the DOM spec defines the following types of nodes:
Document
-- Element
(maximum of
one), ProcessingInstruction
,
Comment
, DocumentType
DocumentFragment
-- Element
, ProcessingInstruction
,
Comment
, Text
, CDATASection
, EntityReference
DocumentType
--
no children
EntityReference
-- Element
, ProcessingInstruction
,
Comment
, Text
, CDATASection
, EntityReference
Element
-- Element
, Text
, Comment
, ProcessingInstruction
,
CDATASection
, EntityReference
Attr
-- Text
, EntityReference
ProcessingInstruction
-- no children
Comment
-- no
children
Text
-- no
children
CDATASection
--
no children
Entity
-- Element
, ProcessingInstruction
,
Comment
, Text
, CDATASection
, EntityReference
Notation
-- no
children The XML Infoset (used by XPath) has a smaller set of nodes:
XPath has the following Node types:
The answer to your question "What is the difference between an element and a node" is:
An element is a type of node. Many other types of nodes exist and serve different purposes.
This is for the text form of a timestamp that can be used in your text files. (The title of the question was different in the past, so the introduction to this answer was changed to clarify how it could be interpreted as the time. [updated 2016-01-14])
You can get the timestamp as a string using the .now()
or .utcnow()
of the datetime.datetime
:
>>> import datetime
>>> print datetime.datetime.utcnow()
2012-12-15 10:14:51.898000
The now
differs from utcnow
as expected -- otherwise they work the same way:
>>> print datetime.datetime.now()
2012-12-15 11:15:09.205000
You can render the timestamp to the string explicitly:
>>> str(datetime.datetime.now())
'2012-12-15 11:15:24.984000'
Or you can be even more explicit to format the timestamp the way you like:
>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Saturday, 15. December 2012 11:19AM'
If you want the ISO format, use the .isoformat()
method of the object:
>>> datetime.datetime.now().isoformat()
'2013-11-18T08:18:31.809000'
You can use these in variables for calculations and printing without conversions.
>>> ts = datetime.datetime.now()
>>> tf = datetime.datetime.now()
>>> te = tf - ts
>>> print ts
2015-04-21 12:02:19.209915
>>> print tf
2015-04-21 12:02:30.449895
>>> print te
0:00:11.239980
People gave good answers but forgot to mention the most important part in my opinion:
In the second example the X
of the list comprehension is NOT the same as the X
of the lambda
function, they are totally unrelated.
So the second example is actually the same as:
[Lambda X: X*X for I in range(10)]
The internal iterations on range(10)
are only responsible for creating 10 similar lambda functions in a list (10 separate functions but totally similar - returning the power 2 of each input).
On the other hand, the first example works totally different, because the X of the iterations DO interact with the results, for each iteration the value is X*X
so the result would be [0,1,4,9,16,25, 36, 49, 64 ,81]
I slightly modified the printer example to make it more explainable
1 document which had 2 pages content was sent to printer
Transaction - document sent to printer
Hope this helps someone to get the hang of the concept of ACID
You can't achieve text size change with a state list drawable. To change text color and text size do this:
Text color
To change the text color, you can create color state list resource. It will be a separate resource located in res/color/
directory. In layout xml you have to set it as the value for android:textColor
attribute. The color selector will then contain something like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/text_pressed" />
<item android:color="@color/text_normal" />
</selector>
Text size
You can't change the size of the text simply with resources. There's no "dimen selector". You have to do it in code. And there is no straightforward solution.
Probably the easiest solution might be utilizing View.onTouchListener()
and handle the up and down events accordingly. Use something like this:
view.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// change text size to the "pressed value"
return true;
case MotionEvent.ACTION_UP:
// change text size to the "normal value"
return true;
default:
return false;
}
}
});
A different solution might be to extend the view and override the setPressed(Boolean)
method. The method is internally called when the change of the pressed state happens. Then change the size of the text accordingly in the method call (don't forget to call the super).
Another option, without dropping or filtering in a loop:
import numpy as np
import pandas as pd
# Create a dataframe with columns A,B,C and D
df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))
# include the columns you want
df[df.columns[df.columns.isin(['A', 'B'])]]
# or more simply include columns:
df[['A', 'B']]
# exclude columns you don't want
df[df.columns[~df.columns.isin(['C','D'])]]
# or even simpler since 0.24
# with the caveat that it reorders columns alphabetically
df[df.columns.difference(['C', 'D'])]
For those working in Titanium Studio, the item is a little different: It's under the "Titanium Studio" Themes tab.
The color to change is the "Selection" one in the top right.
Character.isDigit(string.charAt(0))
Note that this will allow any Unicode digit, not just 0-9. You might prefer:
char c = string.charAt(0);
isDigit = (c >= '0' && c <= '9');
Or the slower regex solutions:
s.substring(0, 1).matches("\\d")
// or the equivalent
s.substring(0, 1).matches("[0-9]")
However, with any of these methods, you must first be sure that the string isn't empty. If it is, charAt(0)
and substring(0, 1)
will throw a StringIndexOutOfBoundsException
. startsWith
does not have this problem.
To make the entire condition one line and avoid length checks, you can alter the regexes to the following:
s.matches("\\d.*")
// or the equivalent
s.matches("[0-9].*")
If the condition does not appear in a tight loop in your program, the small performance hit for using regular expressions is not likely to be noticeable.
Here is a quick little Python program that will display the information about your multi-monitor setup:
import gtk
window = gtk.Window()
# the screen contains all monitors
screen = window.get_screen()
print "screen size: %d x %d" % (gtk.gdk.screen_width(),gtk.gdk.screen_height())
# collect data about each monitor
monitors = []
nmons = screen.get_n_monitors()
print "there are %d monitors" % nmons
for m in range(nmons):
mg = screen.get_monitor_geometry(m)
print "monitor %d: %d x %d" % (m,mg.width,mg.height)
monitors.append(mg)
# current monitor
curmon = screen.get_monitor_at_window(screen.get_active_window())
x, y, width, height = monitors[curmon]
print "monitor %d: %d x %d (current)" % (curmon,width,height)
Here's an example of its output:
screen size: 5120 x 1200
there are 3 monitors
monitor 0: 1600 x 1200
monitor 1: 1920 x 1200
monitor 2: 1600 x 1200
monitor 1: 1920 x 1200 (current)
You should just use "+" before $(this)
. That's going to convert the string to number, so:
var votevalue = +$(this).data('votevalue');
Oh and I recommend to use closest()
method just in case :)
var votevalue = +$(this).closest('.btn-group').data('votevalue');
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
You can do something like that :
"/installers/services/".replace(/^\/+/g,'').replace(/\/+$/g,'')
This regex is a common way to have the same behaviour of the trim
function used in many languages.
A possible implementation of trim function is :
function trim(string, char){
if(!char) char = ' '; //space by default
char = char.replace(/([()[{*+.$^\\|?])/g, '\\$1'); //escape char parameter if needed for regex syntax.
var regex_1 = new RegExp("^" + char + "+", "g");
var regex_2 = new RegExp(char + "+$", "g");
return string.replace(regex_1, '').replace(regex_2, '');
}
Which will delete all /
at the beginning and the end of the string. It handles cases like ///installers/services///
You can also simply do :
"/installers/".substring(1, string.length-1);
Yes, just delete the branch by running git push origin :branchname
. To fix a new issue later, branch off from master again.
Read this https://docs.djangoproject.com/en/dev/howto/static-files/:
For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.
And try:
~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp
Then add 'myapp'
to INSTALLED_APPS
(myprj/settings.py
).
~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html
Edit myprj/urls.py
:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
class HelloView(TemplateView):
template_name = "hello.html"
urlpatterns = patterns('',
url(r'^$', HelloView.as_view(), name='hello'),
)
And run it:
~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver
It works!
I would use:
val, idx = min((val, idx) for (idx, val) in enumerate(my_list))
Then val
will be the minimum value and idx
will be its index.
This is a variation on Robert's answer that allows a single decimal point to be entered. If a decimal point has already been entered, only numbers are accepted as input.
JSFiddle - decimal number input
// Allow only decimal number input
$('#decimalInput').keypress(function (e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
// allow a max of 1 decimal point to be entered
if (this.value.indexOf(".") === -1) {
a.push(46);
}
if (!(a.indexOf(k) >= 0)) e.preventDefault();
$('span').text('KeyCode: ' + k);
});
This will easily handle migration problems. You can migrate selected tables of selected databases between MySql and SqlServer. You should give it a try definitely.
I changed a hard disk, installed Windows. When tried to upload files received this command window.
I pressed "y", then Ctrl + C. Opened putty.exe
, added an old key ther returned to git and pushed files.
A few years late but this might help someone if you are using eval or backtick substitution:
postDataJson="{\"guid\":\"$guid\",\"auth_token\":\"$token\"}"
Using sed to strip quotes from beginning and end of response
$(curl --silent -H "Content-Type: application/json" https://${target_host}/runs/get-work -d ${postDataJson} | sed -e 's/^"//' -e 's/"$//')
A slight improvement of the above accepted answer, that I think is more pythonic (asking for forgiveness is better than asking for permission)
column_widths = []
for row in workSheet.iter_rows():
for i, cell in enumerate(row):
try:
column_widths[i] = max(column_widths[i], len(str(cell.value)))
except IndexError:
column_widths.append(len(str(cell.value)))
for i, column_width in enumerate(column_widths):
workSheet.column_dimensions[get_column_letter(i + 1)].width = column_width
Like this: .
The .
means any character except newline (which sometimes is but often isn't included, check your regex flavour).
You can rewrite your expression as ^.{1,35}$
, which should match any line of length 1-35.
This would be better as a comment, sorry I do not have commenting permissions.
@mar10 comment was the missing piece I needed to do this.
Note that '/path/to/old/mercurial_repo' must be a path on the file system (not a URL), so you have to clone the original repository before. – mar10 Dec 27 '13 at 16:30
This comment was in regards to the answer that solved this for me, https://stackoverflow.com/a/10710294/2148757 which is the same answer as the one marked correct here, https://stackoverflow.com/a/16037861/2148757
This moved our hg project to git with the commit history intact.
How about std::remove()
instead:
#include <algorithm>
...
vec.erase(std::remove(vec.begin(), vec.end(), 8), vec.end());
This combination is also known as the erase-remove idiom.
Ken, good question. I should be more explicit in the The Definitive Guide about the difference. "install" and "deploy" serve two different purposes in a build. "install" refers to the process of installing an artifact in your local repository. "deploy" refers to the process of deploying an artifact to a remote repository.
Example:
When I run a large multi-module project on a my machine, I'm going to usually run "mvn install". This is going to install all of the generated binary software artifacts (usually JARs) in my local repository. Then when I build individual modules in the build, Maven is going to retrieve the dependencies from the local repository.
When it comes time to deploy snapshots or releases, I'm going to run "mvn deploy". Running this is going to attempt to deploy the files to a remote repository or server. Usually I'm going to be deploying to a repository manager such as Nexus
It is true that running "deploy" is going to require some extra configuration, you are going to have to supply a distributionManagement section in your POM.
optionalUsers.orElseThrow(() -> new UsernameNotFoundException("Username not found"));
SUPER-SHIFT-p > File: Revert File
is the only way
(where SUPER
is Command
on Mac and Ctrl
on PC)
Using CSS3:
<div class="outer">
<div class="inner"/>
</div>
Css:
.outer {
display : flex;
align-items : center;
}
use "justify-content: center;" to align elements horizontally
Note: This might not work in old IE's
You can use the following example to store a query result in a variable using PL/pgSQL:
select * into demo from maintenanceactivitytrack ;
raise notice'p_maintenanceid:%',demo;
You have more than one form tags with runat="server" on your template, most probably you have one in your master page, remove one on your aspx page, it is not needed if already have form in master page file which is surrounding your content place holders.
Try to remove that tag:
<form id="formID" runat="server">
and of course closing tag:
</form>
You can use curl
this way:
curl -OL https://raw.githubusercontent.com/<username>/<repo-name>/<branch-name>/path/to/file
O
means that curl downloads the content
L
means that curl follows the redirection
Try this
console.log(moment().format("MM ddd, YYYY HH:mm:ss a"));
console.log(moment().format("MM ddd, YYYY hh:mm:ss a"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
requests
does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.
Python comes with built-in XML parsers. I recommend you use the ElementTree API:
import requests
from xml.etree import ElementTree
response = requests.get(url)
tree = ElementTree.fromstring(response.content)
or, if the response is particularly large, use an incremental approach:
response = requests.get(url, stream=True)
# if the server sent a Gzip or Deflate compressed response, decompress
# as we read the raw stream:
response.raw.decode_content = True
events = ElementTree.iterparse(response.raw)
for event, elem in events:
# do something with `elem`
The external lxml project builds on the same API to give you more features and power still.
Future version of node will allow you to fork a process and pass messages to it and Ryan has stated he wants to find some way to also share file handlers, so it won't be a straight forward Web Worker implementation.
At this time there is not an easy solution for this but it's still very early and node is one of the fastest moving open source projects I've ever seen so expect something awesome in the near future.
To add to Oleg's answer:
I was able to find the DLL at runtime by appending Visual Studio's $(ExecutablePath)
to the PATH environment variable in Configuration Properties->Debugging. This macro is exactly what's defined in the Configuration Properties->VC++ Directories->Executable Directories field*, so if you have that setup to point to any DLLs you need, simply adding this to your PATH makes finding the DLLs at runtime easy!
* I actually don't know if the $(ExecutablePath)
macro uses the project's Executable Directories setting or the global Property Pages' Executable Directories setting. Since I have all of my libraries that I often use configured through the Property Pages, these directories show up as defaults for any new projects I create.
*&
signifies the receiving the pointer by reference. It means it is an alias for the passing parameter. So, it affects the passing parameter.
#include <iostream>
using namespace std;
void foo(int *ptr)
{
ptr = new int(50); // Modifying the pointer to point to a different location
cout << "In foo:\t" << *ptr << "\n";
delete ptr ;
}
void bar(int *& ptr)
{
ptr = new int(80); // Modifying the pointer to point to a different location
cout << "In bar:\t" << *ptr << "\n";
// Deleting the pointer will result the actual passed parameter dangling
}
int main()
{
int temp = 100 ;
int *p = &temp ;
cout << "Before foo:\t" << *p << "\n";
foo(p) ;
cout << "After foo:\t" << *p << "\n";
cout << "Before bar:\t" << *p << "\n";
bar(p) ;
cout << "After bar:\t" << *p << "\n";
delete p;
return 0;
}
Output:
Before foo: 100
In foo: 50
After foo: 100
Before bar: 100
In bar: 80
After bar: 80
I worked around this by using UriBuilder instead.
UriBuilder builder = new UriBuilder(slct.Text);
if (DeleteFileOnServer(builder.Uri))
{
...
}
a = [2 3 5];
b = [1 1 0];
c = a+b;
starts = zeros(3,3);
ends = [a;b;c];
quiver3(starts(:,1), starts(:,2), starts(:,3), ends(:,1), ends(:,2), ends(:,3))
axis equal
You could use imagemagick and write a script that fires everytime you load a webpage.
Try the code mentioned below
public static void main(String[] args) {
int smallest=0; int large=0; int num;
System.out.println("enter the number");
Scanner input=new Scanner(System.in);
int n=input.nextInt();
num=input.nextInt();
smallest = num;
for(int i=0;i<n-1;i++)
{
num=input.nextInt();
if(num<smallest)
{
smallest=num;
}
}
System.out.println("the smallest is:"+smallest);
}
class LinksParser(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.recording = 0
self.data = []
def handle_starttag(self, tag, attributes):
if tag != 'div':
return
if self.recording:
self.recording += 1
return
for name, value in attributes:
if name == 'id' and value == 'remository':
break
else:
return
self.recording = 1
def handle_endtag(self, tag):
if tag == 'div' and self.recording:
self.recording -= 1
def handle_data(self, data):
if self.recording:
self.data.append(data)
self.recording
counts the number of nested div
tags starting from a "triggering" one. When we're in the sub-tree rooted in a triggering tag, we accumulate the data in self.data
.
The data at the end of the parse are left in self.data
(a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.
The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above, 'div'
, 'id'
, and 'remository'
, instance attributes self.tag
, self.attname
and self.attvalue
, set by __init__
from arguments passed to it -- I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).
You could use prop
as well. Check the following code below.
$(document).ready(function(){
$('.staff_on_site').click(function(){
var rBtnVal = $(this).val();
if(rBtnVal == "yes"){
$("#no_of_staff").prop("readonly", false);
}
else{
$("#no_of_staff").prop("readonly", true);
}
});
});
If you can re-create or parse your input data, you can specify an escape character for the CREATE TABLE:
ROW FORMAT DELIMITED FIELDS TERMINATED BY "," ESCAPED BY '\\';
Will accept this line as 4 fields
1,some text\, with comma in it,123,more text
Yes using Option Explicit
is a good habit. Using .Select
however is not :) it reduces the speed of the code. Also fully justify sheet names else the code will always run for the Activesheet
which might not be what you actually wanted.
Is this what you are trying?
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
Else
Exit For
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
NOTE
If if you have data from Row 2 till Row 10 and row 11 is blank and then you have data again from Row 12 then the above code will only copy data from Row 2 till Row 10
If you want to copy all rows which have data then use this code.
Option Explicit
Sub Sample()
Dim lastRow As Long, i As Long
Dim CopyRange As Range
'~~> Change Sheet1 to relevant sheet name
With Sheets("Sheet1")
lastRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lastRow
If Len(Trim(.Range("A" & i).Value)) <> 0 Then
If CopyRange Is Nothing Then
Set CopyRange = .Rows(i)
Else
Set CopyRange = Union(CopyRange, .Rows(i))
End If
End If
Next
If Not CopyRange Is Nothing Then
'~~> Change Sheet2 to relevant sheet name
CopyRange.Copy Sheets("Sheet2").Rows(1)
End If
End With
End Sub
Hope this is what you wanted?
Sid
While inserting multiple rows with a single INSERT
statement is generally faster, it leads to a more complicated and often unsafe code. Below I present the best practices when it comes to inserting multiple records in one go using PHP.
To insert multiple new rows into the database at the same time, one needs to follow the following 3 steps:
INSERT
statementUsing database transactions ensures that the data is saved in one piece and significantly improves performance.
PDO is the most common choice of database extension in PHP and inserting multiple records with PDO is quite simple.
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
// Start transaction
$pdo->beginTransaction();
// Prepare statement
$stmt = $pdo->prepare('INSERT
INTO `pxlot` (realname,email,address,phone,status,regtime,ip)
VALUES (?,?,?,?,?,?,?)');
// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
// All seven parameters are passed into the execute() in a form of an array
$stmt->execute([$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
}
// Commit the data into the database
$pdo->commit();
The mysqli extension is a little bit more cumbersome to use but operates on very similar principles. The function names are different and take slightly different parameters.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'user', 'password', 'database');
$mysqli->set_charset('utf8mb4');
// Start transaction
$mysqli->begin_transaction();
// Prepare statement
$stmt = $mysqli->prepare('INSERT
INTO `pxlot` (realname,email,address,phone,status,regtime,ip)
VALUES (?,?,?,?,?,?,?)');
// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
// mysqli doesn't accept bind in execute yet, so we have to bind the data first
// The first argument is a list of letters denoting types of parameters. It's best to use 's' for all unless you need a specific type
// bind_param doesn't accept an array so we need to unpack it first using '...'
$stmt->bind_param('sssssss', ...[$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
$stmt->execute();
}
// Commit the data into the database
$mysqli->commit();
Both extensions offer the ability to use transactions. Executing prepared statement with transactions greatly improves performance, but it's still not as good as a single SQL query. However, the difference is so negligible that for the sake of conciseness and clean code it is perfectly acceptable to execute prepared statements multiple times. If you need a faster option to insert many records into the database at once, then chances are that PHP is not the right tool.
The input in the markup is missing "type"
, the input (text I assume) has the attribute name="name"
and ID="cname"
, the provided code by Ayo calls the input named "cname"* where it should be "name".
adb is in android-sdks/tools directory. You simply type this command: adb logcat
.
If you want to your stack traces in a text file use this command: adb logcat > trace.txt.
Now your traces are copied into that file.
If it is not working then go to android-sdks/platform-tools then put this command: ./adb logcat > trace.txt.
Hope it will helps to you.
Important question. The server I use (Ubuntu 12.04) had easy_install3
but not pip3
. This is how I installed Pip and then other packages to my home folder
Asked admin to install Ubuntu package python3-setuptools
Installed pip
Like this:
easy_install3 --prefix=$HOME/.local pip
mkdir -p $HOME/.local/lib/python3.2/site-packages
easy_install3 --prefix=$HOME/.local pip
Like this:
PATH="$HOME/.local/bin:$PATH"
echo PATH="$HOME/.local/bin:$PATH" > $HOME/.profile
like this
pip3 install --user httpie
# test httpie package
http httpbin.org
On the user action:
// you have to do something along the lines of
myJFrame.getContentPane().removeAll()
myJFrame.getContentPane().invalidate()
myJFrame.getContentPane().add(newContentPanel)
myJFrame.getContentPane().revalidate()
Then you can resize your wndow as needed.
This answer is a bit late but I hope it helps someone out there all the same.
In my case, it was because the repository had been moved. I recloned the project and everything became alright afterwards. A better alternative would have been to re-initialize git.
I hope this helps.. Merry coding!
The key here I guess is to round up correctly first, then you can convert it to String.
function roundOf(n, p) {
const n1 = n * Math.pow(10, p + 1);
const n2 = Math.floor(n1 / 10);
if (n1 >= (n2 * 10 + 5)) {
return (n2 + 1) / Math.pow(10, p);
}
return n2 / Math.pow(10, p);
}
// All edge cases listed in this thread
roundOf(95.345, 2); // 95.35
roundOf(95.344, 2); // 95.34
roundOf(5.0364342423, 2); // 5.04
roundOf(0.595, 2); // 0.60
roundOf(0.335, 2); // 0.34
roundOf(0.345, 2); // 0.35
roundOf(551.175, 2); // 551.18
roundOf(0.3445434, 2); // 0.34
Now you can safely format this value with toFixed(p). So with your specific case:
roundOf(0.3445434, 2).toFixed(2); // 0.34
I have resolved this one by creating the POJO class (Student.class) of the JSON and Main Class is used for read the values from the JSON in the problem.
**Main Class**
public static void main(String[] args) throws JsonParseException,
JsonMappingException, IOException {
String jsonStr = "[ \r\n" + " {\r\n" + " \"firstName\" : \"abc\",\r\n"
+ " \"lastName\" : \"xyz\"\r\n" + " }, \r\n" + " {\r\n"
+ " \"firstName\" : \"pqr\",\r\n" + " \"lastName\" : \"str\"\r\n" + " } \r\n" + "]";
ObjectMapper mapper = new ObjectMapper();
List<Student> details = mapper.readValue(jsonStr, new
TypeReference<List<Student>>() { });
for (Student itr : details) {
System.out.println("Value for getFirstName is: " +
itr.getFirstName());
System.out.println("Value for getLastName is: " +
itr.getLastName());
}
}
**RESULT:**
Value for getFirstName is: abc
Value for getLastName is: xyz
Value for getFirstName is: pqr
Value for getLastName is: str
**Student.class:**
public class Student {
private String lastName;
private String firstName;
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
} }
SELECT TIMEDIFF('2007-12-31 10:02:00','2007-12-30 12:01:01');
-- result: 22:00:59, the difference in HH:MM:SS format
SELECT TIMESTAMPDIFF(SECOND,'2007-12-30 12:01:01','2007-12-31 10:02:00');
-- result: 79259 the difference in seconds
So, you can use TIMESTAMPDIFF
for your purpose.
just do this
@Override
public void onBackPressed() {
super.onBackPressed();
}
My url is like this http://www.default-search.net/?sid=503 . I want to get 503 . I wrote the following code .
var baseUrl = (window.location).href; // You can also use document.URL
var koopId = baseUrl.substring(baseUrl.lastIndexOf('=') + 1);
alert(koopId)//503
If you use
var v = window.location.pathname;
console.log(v)
You will get only "/";
Thought i should add here, that if you want to access rows or columns to loop through them, you do this:
import pandas as pd
# open the file
xlsx = pd.ExcelFile("PATH\FileName.xlsx")
# get the first sheet as an object
sheet1 = xlsx.parse(0)
# get the first column as a list you can loop through
# where the is 0 in the code below change to the row or column number you want
column = sheet1.icol(0).real
# get the first row as a list you can loop through
row = sheet1.irow(0).real
Edit:
The methods icol(i)
and irow(i)
are deprecated now. You can use sheet1.iloc[:,i]
to get the i-th col and sheet1.iloc[i,:]
to get the i-th row.
You can use the following library:
https://github.com/pnowy/NativeCriteria
The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).
You can find the examples on github page, the library is available at Maven central of course.
NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));
Just like Python, in that [::-1]
reverses the array returned by argsort()
and [:n]
gives that last n elements:
>>> avgDists=np.array([1, 8, 6, 9, 4])
>>> n=3
>>> ids = avgDists.argsort()[::-1][:n]
>>> ids
array([3, 1, 2])
The advantage of this method is that ids
is a view of avgDists:
>>> ids.flags
C_CONTIGUOUS : False
F_CONTIGUOUS : False
OWNDATA : False
WRITEABLE : True
ALIGNED : True
UPDATEIFCOPY : False
(The 'OWNDATA' being False indicates this is a view, not a copy)
Another way to do this is something like:
(-avgDists).argsort()[:n]
The problem is that the way this works is to create negative of each element in the array:
>>> (-avgDists)
array([-1, -8, -6, -9, -4])
ANd creates a copy to do so:
>>> (-avgDists_n).flags['OWNDATA']
True
So if you time each, with this very small data set:
>>> import timeit
>>> timeit.timeit('(-avgDists).argsort()[:3]', setup="from __main__ import avgDists")
4.2879798610229045
>>> timeit.timeit('avgDists.argsort()[::-1][:3]', setup="from __main__ import avgDists")
2.8372560259886086
The view method is substantially faster (and uses 1/2 the memory...)
Multi cursor edit is natively supported in Visual Studio starting from version 2017 Update 8. The following is an extract of the documentation:
Some of those commands are also available in the Edit
menu:
TextBox1.ForeColor = Color.Red;
TextBox1.Font.Bold = True;
Or this can be done using a CssClass (recommended):
.highlight
{
color:red;
font-weight:bold;
}
TextBox1.CssClass = "highlight";
Or the styles can be added inline:
TextBox1.Attributes["style"] = "color:red; font-weight:bold;";
The param ?v=1.123
indicates a query string, and the browser will therefore think it is a new path from, say, ?v=1.0
. Thus causing it to load from file, not from cache. As you want.
And, the browser will assume that the source will stay the same next time you call ?v=1.123
and should cache it with that string. So it will remain cached, however your server is set up, until you move to ?v=1.124
or so on.
On windows
......\Android\sdk\tools\bin\avdmanager list avds
......\Android\sdk\tools\emulator.exe -avd Nexus_5X_API_27
You use PHP_EOL
when you want a new line, and you want to be cross-platform.
This could be when you are writing files to the filesystem (logs, exports, other).
You could use it if you want your generated HTML to be readable. So you might follow your <br />
with a PHP_EOL
.
You would use it if you are running php as a script from cron and you needed to output something and have it be formatted for a screen.
You might use it if you are building up an email to send that needed some formatting.
To filter a list of dicts you can use the selectattr filter together with the equalto test:
network.addresses.private_man | selectattr("type", "equalto", "fixed")
The above requires Jinja2 v2.8 or later (regardless of Ansible version).
Ansible also has the tests match
and search
, which take regular expressions:
match
will require a complete match in the string, whilesearch
will require a match inside of the string.
network.addresses.private_man | selectattr("type", "match", "^fixed$")
To reduce the list of dicts to a list of strings, so you only get a list of the addr
fields, you can use the map filter:
... | map(attribute='addr') | list
Or if you want a comma separated string:
... | map(attribute='addr') | join(',')
Combined, it would look like this.
- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}
<ul class="col col-double clearfix">
<li class="col__item" ng-repeat="location in searchLocations">
<label>
<input type="checkbox" ng-click="onLocationSelectionClicked($event)" checklist-model="selectedAuctions.locations" checklist-value="location.code" checklist-change="auctionSelectionChanged()" id="{{location.code}}"> {{location.displayName}}
</label>
$scope.onLocationSelectionClicked = function($event) {
if($scope.limitSelectionCountTo && $scope.selectedAuctions.locations.length == $scope.limitSelectionCountTo) {
$event.currentTarget.checked=false;
}
};
So you need to use what we call promise. Read how angular handles it here, https://docs.angularjs.org/api/ng/service/$q. Turns our $http support promises inherently so in your case we'll do something like this,
(function() {
"use strict";
var serviceCallJson = function($http) {
this.getCustomers = function() {
// http method anyways returns promise so you can catch it in calling function
return $http({
method : 'get',
url : '../viewersData/userPwdPair.json'
});
}
}
var validateIn = function (serviceCallJson, $q) {
this.called = function(username, password) {
var deferred = $q.defer();
serviceCallJson.getCustomers().then(
function( returnedData ) {
console.log(returnedData); // you should get output here this is a success handler
var i = 0;
angular.forEach(returnedData, function(value, key){
while (i < 10) {
if(value[i].username == username) {
if(value[i].password == password) {
alert("Logged In");
}
}
i = i + 1;
}
});
},
function() {
// this is error handler
}
);
return deferred.promise;
}
}
angular.module('assignment1App')
.service ('serviceCallJson', serviceCallJson)
angular.module('assignment1App')
.service ('validateIn', ['serviceCallJson', validateIn])
}())
Currency pipe uses the number
one internally for number formatting. So you can use it like this:
{{ number | number : '1.2-2'}}
You use a self join when a table references data in itself.
E.g., an Employee
table may have a SupervisorID
column that points to the employee that is the boss of the current employee.
To query the data and get information for both people in one row, you could self join like this:
select e1.EmployeeID,
e1.FirstName,
e1.LastName,
e1.SupervisorID,
e2.FirstName as SupervisorFirstName,
e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID
Create a list in Python and also a set which doesn't allow any duplicates. Solution1 :
def fix(string):
s = set()
list = []
for ch in string:
if ch not in s:
s.add(ch)
list.append(ch)
return ''.join(list)
string = "Protiijaayiiii"
print(fix(string))
Method 2 :
s = "Protijayi"
aa = [ ch for i, ch in enumerate(s) if ch not in s[:i]]
print(''.join(aa))
Yes, s
stands for string. The json.loads
function does not take the file path, but the file contents as a string. Look at the documentation at https://docs.python.org/2/library/json.html!
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
None of the above answers were complete for me.
If your field is named field
, so the selector should be the following one:
IFNULL(`field`,0) AS field
For example in a SELECT query:
SELECT IFNULL(`field`,0) AS field, `otherfield` FROM `mytable`
Hope this can help someone to not waste time.
Use argon2i. The argon2 password hashing function has won the Password Hashing Competition.
Other reasonable choices, if using argon2 is not available, are scrypt, bcrypt and PBKDF2. Wikipedia has pages for these functions:
MD5, SHA1 and SHA256 are message digests, not password-hashing functions. They are not suitable for this purpose.
Switching from MD5 to SHA1 or SHA512 will not improve the security of the construction so much. Computing a SHA256 or SHA512 hash is very fast. An attacker with common hardware could still try tens of millions (with a single CPU) or even billions (with a single GPU) of hashes per second. Good password hashing functions include a work factor to slow down dictionary attacks.
Here is a suggestion for PHP programmers: read the PHP FAQ then use password_hash().
In my recent work with LINUX is one thing to be aware of is libraries. If you are using threads make sure any libraries you may use across threads are thread-safe. This burned me a couple of times. Notably libxml2 is not thread-safe out of the box. It can be compiled with thread safe but that is not what you get with aptitude install.
In Swift 4 you can set the border color and width to UIControls using below code.
let yourColor : UIColor = UIColor( red: 0.7, green: 0.3, blue:0.1, alpha: 1.0 )
yourControl.layer.masksToBounds = true
yourControl.layer.borderColor = yourColor.CGColor
yourControl.layer.borderWidth = 1.0
< Swift 4, You can set UIView's border width and border color using the below code.
yourView.layer.borderWidth = 1
yourView.layer.borderColor = UIColor.red.cgColor
It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:
[...] when looping through the
Iterable
value list, each Object instance is re-used, so it only keeps one instance around at a given time.
This is the best solution I have found for the error 404 on IIS 7.5 and .NET Framework 4.5 environment, and without using: runAllManagedModulesForAllRequests="true".
I followed this thread: https://forums.asp.net/t/2070064.aspx?Web+API+2+URL+routing+404+error+on+IIS+7+5+IIS+Express+works+fine and I have modified my web.config accordingly, and now the MVC web app works well on IIS 7.5 and .NET Framework 4.5 environment.
You can also have several workspaces - so you can connect to one and have set "A" of projects - and then connect to a different set when ever you like.
You can enable connection logging. For SQL Server 2008, you can enable Login Auditing. In SQL Server Management Studio, open SQL Server Properties > Security > Login Auditing select "Both failed and successful logins".
Make sure to restart the SQL Server service.
Once you've done that, connection attempts should be logged into SQL's error log. The physical logs location can be determined here.
for latest Jquery. Simply:
<script src="https://code.jquery.com/jquery-latest.min.js"></script>
The error is a stack overflow. That should ring a bell on this site, right? It occurs because a call to poruszanie
results in another call to poruszanie
, incrementing the recursion depth by 1. The second call results in another call to the same function. That happens over and over again, each time incrementing the recursion depth.
Now, the usable resources of a program are limited. Each function call takes a certain amount of space on top of what is called the stack. If the maximum stack height is reached, you get a stack overflow error.
Just because I did not see it mentioned.
If 2016+, here is yet another option to dynamically unpivot data without actually using Dynamic SQL.
Example
Declare @YourTable Table ([ID] varchar(50),[Col1] varchar(50),[Col2] varchar(50))
Insert Into @YourTable Values
(1,'A','B')
,(2,'R','C')
,(3,'X','D')
Select A.[ID]
,Item = B.[Key]
,Value = B.[Value]
From @YourTable A
Cross Apply ( Select *
From OpenJson((Select A.* For JSON Path,Without_Array_Wrapper ))
Where [Key] not in ('ID','Other','Columns','ToExclude')
) B
Returns
ID Item Value
1 Col1 A
1 Col2 B
2 Col1 R
2 Col2 C
3 Col1 X
3 Col2 D
The core concept of Docker is to make it easy to create "machines" which in this case can be considered containers. The container aids in reusability, allowing you to create and drop containers with ease.
Images depict the state of a container at every point in time. So the basic workflow is:
Add this
node_modules/
to .gitignore
file to ignore all directories called node_modules
in current folder and any subfolders
The objects that form the backbone of your application and that are managed by the Spring IoC* container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML
<bean/>
definitions.
More to learn about beans and scope from SpringSource:
When you create a bean definition what you are actually creating is a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, just like a class, you can potentially have many object instances created from a single recipe.
You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to 'bake in' the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes
*IoC: Inversion of Control
When using java.net.URI.relativize you should be aware of Java bug: JDK-6226081 (URI should be able to relativize paths with partial roots)
At the moment, the
relativize()
method ofURI
will only relativize URIs when one is a prefix of the other.
Which essentially means java.net.URI.relativize
will not create ".."'s for you.
Use this XPath expression:
/*/*/X/node()
This selects any node (element, text node, comment or processing instruction) that is a child of any X
element that is a grand-child of the top element of the XML document.
To verify what is selected, here is this XSLT transformation that outputs exactly the selected nodes:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:copy-of select="/*/*/X/node()"/>
</xsl:template>
</xsl:stylesheet>
and it produces exactly the wanted, correct result:
First Text Node #1
<y> Y can Have Child Nodes #
<child> deep to it </child>
</y> Second Text Node #2
<z />
Explanation:
As defined in the W3 XPath 1.0 Spec, "child::node()
selects all the children of the context node, whatever their node type." This means that any element, text-node, comment-node and processing-instruction node children are selected by this node-test.
node()
is an abbreviation of child::node()
(because child::
is the primary axis and is used when no axis is explicitly specified).
You can use two methods in jQuery as given below-
Using jQuery :nth-child Selector You have put the position of an element as its argument which is 2 as you want to select the second li element.
$( "ul li:nth-child(2)" ).click(function(){_x000D_
//do something_x000D_
});
_x000D_
Using jQuery :eq() Selector
If you want to get the exact element, you have to specify the index value of the item. A list element starts with an index 0. To select the 2nd element of li, you have to use 2 as the argument.
$( "ul li:eq(1)" ).click(function(){_x000D_
//do something_x000D_
});
_x000D_
See Example: Get Second Child Element of List in jQuery
There is another way to count the number of characters in each string.
Assuming we have a String as
String str = "abfdvdvdfv"
We can then count the number of times each character appears by traversing only once as
for (int i = 0; i < str.length(); i++)
{
if(null==map.get(str.charAt(i)+""))
{
map.put(str.charAt(i)+"", new Integer(1));
}
else
{
Integer count = map.get(str.charAt(i)+"");
map.put(str.charAt(i)+"", count+1);
}
}
We can then check the output by traversing the Map as
for (Map.Entry<String, Integer> entry:map.entrySet())
{
System.out.println(entry.getKey()+" count is : "+entry.getValue())
}
You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.
String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
Output :
14:10
14:20
If you install Big Cat Scripts (http://www.ranchero.com/bigcat/) you can add your own contextual menu (right click) items. I don't think it comes with an Open Terminal Here applescript but I use this script (which I don't honestly remember if I wrote myself, or lifted from someone else's example):
on main(filelist)
tell application "Finder"
try
activate
set frontWin to folder of front window as string
set frontWinPath to (get POSIX path of frontWin)
tell application "Terminal"
activate
do script with command "cd \"" & frontWinPath & "\""
end tell
on error error_message
beep
display dialog error_message buttons ¬
{"OK"} default button 1
end try
end tell
end main
Similar scripts can also get you the complete path to a file on right-click, which is even more useful, I find.
<?php
// Replace with the real server API key from Google APIs
$apiKey = "your api key";
// Replace with the real client registration IDs
$registrationIDs = array( "reg id1","reg id2");
// Message to be sent
$message = "hi Shailesh";
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message ),
);
$headers = array(
'Authorization: key=' . $apiKey,
'Content-Type: application/json'
);
// Open connection
$ch = curl_init();
// Set the URL, number of POST vars, POST data
curl_setopt( $ch, CURLOPT_URL, $url);
curl_setopt( $ch, CURLOPT_POST, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($ch, CURLOPT_POST, true);
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode( $fields));
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
echo $result;
//print_r($result);
//var_dump($result);
?>
In VB, math.round has additional arguments to specify number of decimal places and rounding method. Math.Round(10.665, 2, MidpointRounding.AwayFromZero) will return 10.67 . If the number is a decimal or single data type, math.round returns a decimal data type. If it is double, it returns double data type. That might be important if option strict is on.
The result of (10.665).ToString("n2") rounds away from zero to give "10.67". without additional arguments math.round returns 10.66, which could lead to unwanted discrepancies.
Store the firstVisibleItem and on the next onScroll check if the new firstVisibleItem is smaller or greater than the previous one.
Example pseudocode (not tested):
int lastVisibleItem = 0;
boolean isScrollingDown = false;
void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem > lastVisibleItem) {
isScrollingDown = true;
}
else {
isScrollingDown = false;
}
lastVisibleItem = firstVisibleItem;
}
Tray this short way
var lower = (str+"").toLowerCase();
you can't do a "while(done)" loop because that would require blocking on input, something node.js doesn't like to do.
Instead set up a callback to be called each time something is entered:
var stdin = process.openStdin();
stdin.addListener("data", function(d) {
// note: d is an object, and when converted to a string it will
// end with a linefeed. so we (rather crudely) account for that
// with toString() and then trim()
console.log("you entered: [" +
d.toString().trim() + "]");
});
You can use dir()
in a list comprehension to get the attribute names:
names = [p for p in dir(myobj) if not p.startswith('_')]
Use getattr()
to get the attributes themselves:
attrs = [getattr(myobj, p) for p in dir(myobj) if not p.startswith('_')]
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history
object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState
. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState
to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}