Use a computed column instead. It is almost always a better idea to use a computed column than a trigger.
See Example below of a computed column using the UPPER function:
create table #temp (test varchar (10), test2 AS upper(test))
insert #temp (test)
values ('test')
select * from #temp
And not to sound like a broken record or anything, but this is critically important. Never write a trigger that will not work correctly on multiple record inserts/updates/deletes. This is an extremely poor practice as sooner or later one of these will happen and your trigger will cause data integrity problems asw it won't fail precisely it will only run the process on one of the records. This can go a long time until someone discovers the mess and by themn it is often impossible to correctly fix the data.
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
Using the path /inout-tracker
without a trailing /
doesn't fetch index.php
. Instead the server will issue a 302
redirect to the version with the trailing /
.
Doing a 302 will typically cause clients to convert a POST to a GET request.
This will convert a time to seconds in a double format, which is more precise than an integer value:
double elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS) / 1000.0;
You've nearly got it:
DECLARE @myVariable nvarchar(max) = 'hello world';
See here for the docs
For the quotes, SQL Server uses apostrophes, not quotes:
DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';
Use double apostrophes if you need them in a string:
DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';
If you are using Selenium web driver with Python, you can use PyVirtualDisplay, a Python wrapper for Xvfb and Xephyr.
PyVirtualDisplay needs Xvfb as a dependency. On Ubuntu, first install Xvfb:
sudo apt-get install xvfb
Then install PyVirtualDisplay from PyPI:
pip install pyvirtualdisplay
Sample Selenium script in Python in a headless mode with PyVirtualDisplay:
#!/usr/bin/env python
from pyvirtualdisplay import Display
from selenium import webdriver
display = Display(visible=0, size=(800, 600))
display.start()
# Now Firefox will run in a virtual display.
# You will not see the browser.
browser = webdriver.Firefox()
browser.get('http://www.google.com')
print browser.title
browser.quit()
display.stop()
EDIT
The initial answer was posted in 2014 and now we are at the cusp of 2018. Like everything else, browsers have also advanced. Chrome has a completely headless version now which eliminates the need to use any third-party libraries to hide the UI window. Sample code is as follows:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
CHROME_PATH = '/usr/bin/google-chrome'
CHROMEDRIVER_PATH = '/usr/bin/chromedriver'
WINDOW_SIZE = "1920,1080"
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=%s" % WINDOW_SIZE)
chrome_options.binary_location = CHROME_PATH
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
chrome_options=chrome_options
)
driver.get("https://www.google.com")
driver.get_screenshot_as_file("capture.png")
driver.close()
As said, numpy.empty() is the way to go. However, for objects, fill() might not do exactly what you think it does:
In[36]: a = numpy.empty(5,dtype=object)
In[37]: a.fill([])
In[38]: a
Out[38]: array([[], [], [], [], []], dtype=object)
In[39]: a[0].append(4)
In[40]: a
Out[40]: array([[4], [4], [4], [4], [4]], dtype=object)
One way around can be e.g.:
In[41]: a = numpy.empty(5,dtype=object)
In[42]: a[:]= [ [] for x in range(5)]
In[43]: a[0].append(4)
In[44]: a
Out[44]: array([[4], [], [], [], []], dtype=object)
if it works when you do :
python
>>> import requests
then it might be a mismatch between a previous version of python on your computer and the one you are trying to use
in that case : check the location of your working python:
which python
And get sure it is matching the first line in your python code
#!<path_from_which_python_command>
I was facing the same issue; and the following worked well for me. Hope this helps someone landing here:
<div class="row">
<div class="col-md-6">
<div class="col-md-12">
Set room heater temperature
</div>
</div>
<div class="col-md-6">
<div class="col-md-12">
Set room heater temperature
</div>
</div>
</div>
This will automatically render some space between the 2 divs.
Like this.
.divContainer input[type="text"] {
width:150px;
}
.divContainer input[type="radio"] {
width:20px;
}
You can use Newtonsoft.Json
, it's a dependency of Microsoft.AspNet.Mvc.ModelBinding
which is a dependency of Microsoft.AspNet.Mvc
. So, you don't need to add a dependency in your project.json.
#using Newtonsoft.Json
....
JsonConvert.DeserializeObject(json);
Note, using a WebAPI controller you don't need to deal with JSON.
Json.NET has been removed from the ASP.NET Core 3.0 shared framework.
You can use the new JSON serializer layers on top of the high-performance Utf8JsonReader
and Utf8JsonWriter
. It deserializes objects from JSON and serializes objects to JSON. Memory allocations are kept minimal and includes support for reading and writing JSON with Stream asynchronously.
To get started, use the JsonSerializer
class in the System.Text.Json.Serialization
namespace. See the documentation for information and samples.
To use Json.NET in an ASP.NET Core 3.0 project:
services.AddMvc()
.AddNewtonsoftJson();
Read Json.NET support in Migrate from ASP.NET Core 2.2 to 3.0 Preview 2 for more information.
ImageArtist is a pure gd wrapper authored by me, this enables you to do complex image manipulations insanely easy, for your question solution can be done using very few steps using this powerful library.
here is a sample code.
$img1 = new Image("./cover.jpg");
$img2 = new Image("./box.png");
$img2->merge($img1,9,9);
$img2->save("./merged.png",IMAGETYPE_PNG);
This is how my result looks like.
To get all divs under 'container', use the following:
$(".container>div") //or
$(".container").children("div");
You can stipulate a specific #id
instead of div
to get a particular one.
You say you want a div with an 'undefined' id. if I understand you right, the following would achieve this:
$(".container>div[id=]")
If you have <repositories/>
defined in your pom.xml apparently your local repository is ignored.
SELECT (to_date('02-JAN-2013') - to_date('02-JAN-2012')) days_between
FROM dual
/
I agree with rpd, this is the answer and can be done on a regular basis to clean up your id column that is getting bigger with only a few hundred rows of data, but maybe an id of 34444543!, as the data is deleted out regularly but id is incremented automatically.
ALTER TABLE users DROP id
The above sql can be run via sql query or as php. This will delete the id column.
Then re add it again, via the code below:
ALTER TABLE `users` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST
Place this in a piece of code that may get run maybe in an admin panel, so when anyone enters that page it will run this script that auto cleans your database, and tidys it.
Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.
But more importantly why do you want to read an HTTPOnly
cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly
flag and "secure flag" (which forces the cookie to be sent over https) should always be set.
If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly
flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.
People have too much faith in the HTTPOnly
flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.
echo -n "$PROC_NAME $(printf '\055%.0s' {1..40})" | head -c 40 ; echo -n " [UP]"
Explanation:
printf '\055%.0s' {1..40}
- Create 40 dashes"$PROC_NAME ..."
- Concatenate $PROC_NAME and dashes| head -c 40
- Trim string to first 40 charsI developed a solution based on the proposal of Kresimir Nesek. I added a new annotation @EnableMockedBean in order to make the code a bit cleaner and modular.
@EnableMockedBean
@SpringBootApplication
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=MockedBeanTest.class)
public class MockedBeanTest {
@MockedBean
private HelloWorldService helloWorldService;
@Autowired
private MiddleComponent middleComponent;
@Test
public void helloWorldIsCalledOnlyOnce() {
middleComponent.getHelloMessage();
// THEN HelloWorldService is called only once
verify(helloWorldService, times(1)).getHelloMessage();
}
}
I have written a post explaining it.
int()
is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an integer:
>>> int("1") + 1
2
If you know the structure of your list, T1 (that it simply contains lists, only one level), you could do this in Python 3:
T2 = [list(map(int, x)) for x in T1]
In Python 2:
T2 = [map(int, x) for x in T1]
Simple solution:
array_unique($array, SORT_REGULAR)
You could also use Regular Expressions:
SELECT * FROM TABLE WHERE REGEXP_LIKE (TABLE.NAME,'IgNoReCaSe','i');
One approach you could take is the following method:
// Counts how many of a certain character occurs in the given string
public static int CharCountInString(char chr, string str)
{
return str.Split(chr).Length-1;
}
As per the parameters this method returns the count of a specific character within a specific string.
This method works by splitting the string into an array by the specified character and then returning the length of that array -1.
if you use isset like the answer posted already by singles, just make sure there is a bracket at the end like so:
$query_age = (isset($_GET['query_age']) ? $_GET['query_age'] : null);
Check this article for the 5 laws of API dates and times HERE:
More info in the docs.
I will be adding some more information here. The latest Android developments have made it pretty easy to handle a lot of cases in status bar. Following are my observations from the styles.xml
<item name="android:windowTranslucentStatus">true</item>
will make the status bar transparent and show in front of UI. Your Activity will take the whole space of the top.Background color: again,for SDK 21+, <item name="android:statusBarColor">@color/your_color</item>
will simply give a color to your status bar, without affecting anything else.
However, in later devices (Android M/+), the icons started coming in different shades. The OS can give a darker shade of gray to the icons for SDK 23/+ , if you override your styles.xml
file in values-23
folder and add <item name="android:windowLightStatusBar">true</item>
.
This way, you will be providing your user with a more visible status bar, if your status bar has a light color( think of how a lot of google apps have light background yet the icons are visible there in a greyish color).
I would suggest you to use this, if you are giving color to your status bar via point #2
In the most recent devices, SDK 29/+ comes with a system wide light and dark theme, controllable by the user. As devs, we are also supposed to override our style file in a new values-night
folder, to give user 2 different experiences.
Here again, I have found the point #2 to be effective in providing the "background color to status bar". But system was not changing the color of status bar icons for my app. since my day version of style consisted of lighter theme, this means that users will suffer from low visibility ( white icons on lighter background)
This problem can be solved by using the point #3 approach or by overriding style file in values-29
folder and using a newer api <item name="android:enforceStatusBarContrast">true</item>
. This will automatically enforce the grayish tint to icons, if your background color is too light.
Like @g-eorge mention, you can make it like this:
module.config(['$routeProvider', function($routeProvider) {
$routeProvider.
when('/users/:userId?', {templateUrl: 'template.tpl.html', controller: myCtrl})
}]);
You can also make as much as u need optional parameters.
function dob ($birthday){
list($day,$month,$year) = explode("/",$birthday);
$year_diff = date("Y") - $year;
$month_diff = date("m") - $month;
$day_diff = date("d") - $day;
if ($day_diff < 0 || $month_diff < 0)
$year_diff--;
return $year_diff;
}
You can use npm i y-websockets-server
and then use the below command
y-websockets-server --port 11000
and here in my case, the port No is 11000.
Combining the answers above, you can implement something that works like the gem colorize without needing another dependency.
class String
# colorization
def colorize(color_code)
"\e[#{color_code}m#{self}\e[0m"
end
def red
colorize(31)
end
def green
colorize(32)
end
def yellow
colorize(33)
end
def blue
colorize(34)
end
def pink
colorize(35)
end
def light_blue
colorize(36)
end
end
Difference between Read(),Readline() and ReadKey() in C#
Read()
-Accept the string value and return the string value.
Readline()
-Accept the string and return Integer
ReadKey()
-Accept the character and return Character
Summary:
1.The above mentioned three methods are mainly used in Console application and these are used for return the different values . 2.If we use Read line or Read() we need press Enter button to come back to code. 3.If we using Read key() we can press any key to come back code in application
Beyond the gitk recommendation in Is it possible to preview stash contents in git? you can install tig and call tig stash
. This free/open console program also allows you to choose which stash to compare
You can FAKE transitions between gradients, using transitions in the opacity of a few stacked gradients, as described in a few of the answers here:
CSS3 animation with gradients.
You can also transition the position instead, as described here:
CSS3 gradient transition with background-position.
Some more techniques here:
I tried all, but this worked for me. In a class I have another class named "crimeScene
", and want to sort by a property of "crimeScene
".
This works like a charm:
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"crimeScene.distance" ascending:YES];
[self.arrAnnotations sortUsingDescriptors:[NSArray arrayWithObject:sorter]];
Since I didn't like some of the code in the other answers, here's my simple solution. This solution is meant to be usable in an Activity or Service to track the location. It makes sure that it never returns data that's too stale unless you explicitly request stale data. It can be run in either a callback mode to get updates as we receive them, or in poll mode to poll for the most recent info.
Generic LocationTracker interface. Allows us to have multiple types of location trackers and plug the appropriate one in easily:
package com.gabesechan.android.reusable.location;
import android.location.Location;
public interface LocationTracker {
public interface LocationUpdateListener{
public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime);
}
public void start();
public void start(LocationUpdateListener update);
public void stop();
public boolean hasLocation();
public boolean hasPossiblyStaleLocation();
public Location getLocation();
public Location getPossiblyStaleLocation();
}
ProviderLocationTracker- this class will track the location for either GPS or NETWORK.
package com.gabesechan.android.reusable.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class ProviderLocationTracker implements LocationListener, LocationTracker {
// The minimum distance to change Updates in meters
private static final long MIN_UPDATE_DISTANCE = 10;
// The minimum time between updates in milliseconds
private static final long MIN_UPDATE_TIME = 1000 * 60;
private LocationManager lm;
public enum ProviderType{
NETWORK,
GPS
};
private String provider;
private Location lastLocation;
private long lastTime;
private boolean isRunning;
private LocationUpdateListener listener;
public ProviderLocationTracker(Context context, ProviderType type) {
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if(type == ProviderType.NETWORK){
provider = LocationManager.NETWORK_PROVIDER;
}
else{
provider = LocationManager.GPS_PROVIDER;
}
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//The provider is on, so start getting updates. Update current location
isRunning = true;
lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
lastLocation = null;
lastTime = 0;
return;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
lm.removeUpdates(this);
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
if(lastLocation == null){
return false;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return false; //stale
}
return true;
}
public boolean hasPossiblyStaleLocation(){
if(lastLocation != null){
return true;
}
return lm.getLastKnownLocation(provider)!= null;
}
public Location getLocation(){
if(lastLocation == null){
return null;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return null; //stale
}
return lastLocation;
}
public Location getPossiblyStaleLocation(){
if(lastLocation != null){
return lastLocation;
}
return lm.getLastKnownLocation(provider);
}
public void onLocationChanged(Location newLoc) {
long now = System.currentTimeMillis();
if(listener != null){
listener.onUpdate(lastLocation, lastTime, newLoc, now);
}
lastLocation = newLoc;
lastTime = now;
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
The is the FallbackLocationTracker, which will track by both GPS and NETWORK, and use whatever location is more accurate.
package com.gabesechan.android.reusable.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
public class FallbackLocationTracker implements LocationTracker, LocationTracker.LocationUpdateListener {
private boolean isRunning;
private ProviderLocationTracker gps;
private ProviderLocationTracker net;
private LocationUpdateListener listener;
Location lastLoc;
long lastTime;
public FallbackLocationTracker(Context context) {
gps = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.GPS);
net = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.NETWORK);
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//Start both
gps.start(this);
net.start(this);
isRunning = true;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
gps.stop();
net.stop();
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
//If either has a location, use it
return gps.hasLocation() || net.hasLocation();
}
public boolean hasPossiblyStaleLocation(){
//If either has a location, use it
return gps.hasPossiblyStaleLocation() || net.hasPossiblyStaleLocation();
}
public Location getLocation(){
Location ret = gps.getLocation();
if(ret == null){
ret = net.getLocation();
}
return ret;
}
public Location getPossiblyStaleLocation(){
Location ret = gps.getPossiblyStaleLocation();
if(ret == null){
ret = net.getPossiblyStaleLocation();
}
return ret;
}
public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime) {
boolean update = false;
//We should update only if there is no last location, the provider is the same, or the provider is more accurate, or the old location is stale
if(lastLoc == null){
update = true;
}
else if(lastLoc != null && lastLoc.getProvider().equals(newLoc.getProvider())){
update = true;
}
else if(newLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
update = true;
}
else if (newTime - lastTime > 5 * 60 * 1000){
update = true;
}
if(update){
if(listener != null){
listener.onUpdate(lastLoc, lastTime, newLoc, newTime);
}
lastLoc = newLoc;
lastTime = newTime;
}
}
}
Since both implement the LocationTracker interface, you can easily change your mind about which one to use. To run the class in poll mode, just call start(). To run it in update mode, call start(Listener).
Also take a look at my blog post on the code
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
Better solution is to introduce another interface for async operations. New interface must inherit from original interface.
Example:
interface IIO
{
void DoOperation();
}
interface IIOAsync : IIO
{
Task DoOperationAsync();
}
class ClsAsync : IIOAsync
{
public void DoOperation()
{
DoOperationAsync().GetAwaiter().GetResult();
}
public async Task DoOperationAsync()
{
//just an async code demo
await Task.Delay(1000);
}
}
class Program
{
static void Main(string[] args)
{
IIOAsync asAsync = new ClsAsync();
IIO asSync = asAsync;
Console.WriteLine(DateTime.Now.Second);
asAsync.DoOperation();
Console.WriteLine("After call to sync func using Async iface: {0}",
DateTime.Now.Second);
asAsync.DoOperationAsync().GetAwaiter().GetResult();
Console.WriteLine("After call to async func using Async iface: {0}",
DateTime.Now.Second);
asSync.DoOperation();
Console.WriteLine("After call to sync func using Sync iface: {0}",
DateTime.Now.Second);
Console.ReadKey(true);
}
}
P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.
Since version 5.6.3 Gradle documentation provides simple rules of thumb to identify whether an old compile
dependency (or a new one) should be replaced with an implementation
or an api
dependency:
- Prefer the
implementation
configuration overapi
when possibleThis keeps the dependencies off of the consumer’s compilation classpath. In addition, the consumers will immediately fail to compile if any implementation types accidentally leak into the public API.
So when should you use the
api
configuration? An API dependency is one that contains at least one type that is exposed in the library binary interface, often referred to as its ABI (Application Binary Interface). This includes, but is not limited to:
- types used in super classes or interfaces
- types used in public method parameters, including generic parameter types (where public is something that is visible to compilers. I.e. , public, protected and package private members in the Java world)
- types used in public fields
- public annotation types
By contrast, any type that is used in the following list is irrelevant to the ABI, and therefore should be declared as an
implementation
dependency:
- types exclusively used in method bodies
- types exclusively used in private members
- types exclusively found in internal classes (future versions of Gradle will let you declare which packages belong to the public API)
I think you want to change the setting called "DropDownStyle" to be "DropDownList".
For my case on Ubuntu 14.04 installed with postgres 10.3. I need to follow the following steps
su - postgres
to switch user to postgres
psql
to enter postgres shell\password
then enter your password\q
to quit the shell sessionThen you switch back to root by executing exit
and configure your pg_hba.conf
(mine is at /etc/postgresql/10/main/pg_hba.conf
) by making sure you have the following line
local all postgres md5
service postgresql restart
postgres
user and enter postgres shell again. It will prompt you with password.http://en.wikipedia.org/wiki/Post/Redirect/Get
The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)
Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.
Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.
Be careful, the solution proposed with $a = array_combine($a, $a);
will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384)
to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
It looks like you have to set the option for the format with data-date-*. This example works for me with 24h support.
<div class="form-group">
<div class="input-group date timepicker"
data-date-format="HH:mm"
data-date-useseconds="false"
data-date-pickDate="false">
<input type="text" name="" />
<div class="input-group-addon">
<i class="fa fa-clock-o"></i>
</div>
</div>
</div>
The C++ String Toolkit Library (Strtk) has the following solution to your problem:
#include <string>
#include <deque>
#include <vector>
#include "strtk.hpp"
int main()
{
std::string int_string = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
std::vector<int> int_list;
strtk::parse(int_string,",",int_list);
std::string double_string = "123.456|789.012|345.678|901.234|567.890";
std::deque<double> double_list;
strtk::parse(double_string,"|",double_list);
return 0;
}
More examples can be found Here
Try this:
function SelectAnimal() {
var sel = document.getElementById('Animals');
var val = document.getElementById('AnimalToFind').value;
for(var i = 0, j = sel.options.length; i < j; ++i) {
if(sel.options[i].innerHTML === val) {
sel.selectedIndex = i;
break;
}
}
}
You can get Current timestamp in Android by trying below code
time.setText(String.valueOf(System.currentTimeMillis()));
and timeStamp to time format
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateString = formatter.format(new Date(Long.parseLong(time.getText().toString())));
time.setText(dateString);
<!--This yearpicker development from Zlatko Borojevic_x000D_
html elemnts can generate with java function_x000D_
and then declare as custom type for easy use in all html documents _x000D_
For this version for implementacion in your document can use:_x000D_
1. Save this code for example: "yearonly.html"_x000D_
2. creaate one div with id="yearonly"_x000D_
3. Include year picker with function: $("#yearonly").load("yearonly.html"); _x000D_
_x000D_
<div id="yearonly"></div>_x000D_
<script>_x000D_
$("#yearonly").load("yearonly.html"); _x000D_
</script>_x000D_
-->_x000D_
_x000D_
_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<meta name="viewport" content="text-align:center; width=device-width, initial-scale=1.0">_x000D_
<html>_x000D_
<body>_x000D_
<style>_x000D_
.ydiv {_x000D_
border:solid 1px;_x000D_
width:200px;_x000D_
//height:150px;_x000D_
background-color:#D8D8D8;_x000D_
display:none;_x000D_
position:absolute;_x000D_
top:40px;_x000D_
}_x000D_
_x000D_
.ybutton {_x000D_
_x000D_
border: none;_x000D_
width:35px;_x000D_
height:35px;_x000D_
background-color:#D8D8D8;_x000D_
font-size:100%;_x000D_
}_x000D_
_x000D_
.yhr {_x000D_
background-color:black;_x000D_
color:black;_x000D_
height:1px">_x000D_
}_x000D_
_x000D_
.ytext {_x000D_
border:none;_x000D_
text-align:center;_x000D_
width:118px;_x000D_
font-size:100%;_x000D_
background-color:#D8D8D8;_x000D_
font-weight:bold;_x000D_
_x000D_
}_x000D_
</style>_x000D_
<p>_x000D_
<!-- input text for display result of yearpicker -->_x000D_
<input type = "text" id="yeardate"><button style="width:21px;height:21px"onclick="enabledisable()">V</button></p>_x000D_
_x000D_
<!-- yearpicker panel for change only year-->_x000D_
<div class="ydiv" id = "yearpicker">_x000D_
<button class="ybutton" style="font-weight:bold;"onclick="changedecade('back')"><</button>_x000D_
_x000D_
<input class ="ytext" id="dec" type="text" value ="2018" >_x000D_
_x000D_
<button class="ybutton" style="font-weight:bold;" onclick="changedecade('next')">></button>_x000D_
<hr></hr>_x000D_
_x000D_
_x000D_
_x000D_
<!-- subpanel with one year 0-9 -->_x000D_
<button class="ybutton" onclick="yearone = 0;setyear()">0</button>_x000D_
<button class="ybutton" onclick="yearone = 1;setyear()">1</button>_x000D_
<button class="ybutton" onclick="yearone = 2;setyear()">2</button>_x000D_
<button class="ybutton" onclick="yearone = 3;setyear()">3</button>_x000D_
<button class="ybutton" onclick="yearone = 4;setyear()">4</button><br>_x000D_
<button class="ybutton" onclick="yearone = 5;setyear()">5</button>_x000D_
<button class="ybutton" onclick="yearone = 6;setyear()">6</button>_x000D_
<button class="ybutton" onclick="yearone = 7;setyear()">7</button>_x000D_
<button class="ybutton" onclick="yearone = 8;setyear()">8</button>_x000D_
<button class="ybutton" onclick="yearone = 9;setyear()">9</button>_x000D_
</div>_x000D_
<!-- end year panel -->_x000D_
_x000D_
_x000D_
_x000D_
<script>_x000D_
var date = new Date();_x000D_
var year = date.getFullYear(); //get current year_x000D_
//document.getElementById("yeardate").value = year;// can rem if filing text from database_x000D_
_x000D_
var yearone = 0;_x000D_
_x000D_
function changedecade(val1){ //change decade for year_x000D_
_x000D_
var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
if (val1 == "next"){_x000D_
document.getElementById('dec').value = x + 10;_x000D_
}else{_x000D_
document.getElementById('dec').value = x - 10;_x000D_
}_x000D_
}_x000D_
_x000D_
function setyear(){ //set full year as sum decade and one year in decade_x000D_
var x = parseInt(document.getElementById("dec").value.substring(0,3)+"0");_x000D_
var y = parseFloat(yearone);_x000D_
_x000D_
var suma = x + y;_x000D_
var d = new Date();_x000D_
d.setFullYear(suma);_x000D_
var year = d.getFullYear();_x000D_
document.getElementById("dec").value = year;_x000D_
document.getElementById("yeardate").value = year;_x000D_
document.getElementById("yearpicker").style.display = "none";_x000D_
yearone = 0;_x000D_
}_x000D_
_x000D_
function enabledisable(){ //enable/disable year panel_x000D_
if (document.getElementById("yearpicker").style.display == "block"){_x000D_
document.getElementById("yearpicker").style.display = "none";}else{_x000D_
document.getElementById("yearpicker").style.display = "block";_x000D_
}_x000D_
_x000D_
}_x000D_
</script>_x000D_
</body>_x000D_
</html>
_x000D_
The builtin copy(dst, src)
copies min(len(dst), len(src))
elements.
So if your dst
is empty (len(dst) == 0
), nothing will be copied.
Try tmp := make([]int, len(arr))
(Go Playground):
arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)
Output (as expected):
[1 2 3]
[1 2 3]
Unfortunately this is not documented in the builtin
package, but it is documented in the Go Language Specification: Appending to and copying slices:
The number of elements copied is the minimum of
len(src)
andlen(dst)
.
Edit:
Finally the documentation of copy()
has been updated and it now contains the fact that the minimum length of source and destination will be copied:
Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).
lines
is a list of strings, re.findall
doesn't work with that. try:
import re, sys
f = open('findallEX.txt', 'r')
lines = f.read()
match = re.findall('[A-Z]+', lines)
print match
In my case, there was no process to kill.
Updating docker fixed the problem.
You can use the keys
function from the underscore.js library to get the keys, then the sort()
array method to sort them:
var sortedKeys = _.keys(dict).sort();
The keys
function in the underscore's source code:
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys.push(key);
return keys;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
Simple method using System.Data.DataSetExtensions
:
table.AsEnumerable().Select(row => new TankReading{
TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
TankID = Convert.ToInt32(row["TankID"]),
ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
ReadingInches = Convert.ToInt32(row["ReadingInches"]),
MaterialNumber = row["MaterialNumber"].ToString(),
EnteredBy = row["EnteredBy"].ToString(),
ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
MaterialID = Convert.ToInt32(row["MaterialID"]),
Submitted = Convert.ToBoolean(row["Submitted"]),
});
Or:
TankReading TankReadingFromDataRow(DataRow row){
return new TankReading{
TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
TankID = Convert.ToInt32(row["TankID"]),
ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
ReadingInches = Convert.ToInt32(row["ReadingInches"]),
MaterialNumber = row["MaterialNumber"].ToString(),
EnteredBy = row["EnteredBy"].ToString(),
ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
MaterialID = Convert.ToInt32(row["MaterialID"]),
Submitted = Convert.ToBoolean(row["Submitted"]),
};
}
// Now you can do this
table.AsEnumerable().Select(row => return TankReadingFromDataRow(row));
Or, better yet, create a TankReading(DataRow r)
constructor, then this becomes:
table.AsEnumerable().Select(row => return new TankReading(row));
HTTP_CLIENT_IP is the most reliable way of getting the user's IP address. Next is HTTP_X_FORWARDED_FOR, followed by REMOTE_ADDR. Check all three, in that order, assuming that the first one that is set (isset($_SERVER['HTTP_CLIENT_IP'])
returns true if that variable is set) is correct. You can independently check if the user is using a proxy using various methods. Check this out.
require(gdata)
keep(object_1,...,object_n,sure=TRUE)
ls()
int i = 65;
char c = Convert.ToChar(i);
Kernel resides in OS.Actually it is a memory space specially provided for handling the os functions.Some even say OS handles Resources of system and Kernel is one which is heart of os and maintain,manage i.e.keep track of os.
Multiple things can cause this, I didn't bother to check your entire repository, so I'm going out on a limb here.
First off, you could be missing an annotation (@Service or @Component) from the implementation of com.example.my.services.user.UserService
, if you're using annotations for configuration. If you're using (only) xml, you're probably missing the <bean>
-definition for the UserService-implementation.
If you're using annotations and the implementation is annotated correctly, check that the package where the implementation is located in is scanned (check your <context:component-scan base-package=
-value).
10.0.2.2 is alis made for base machine localhost.
port number same : 1521 no need to change
abs works fine for me ..
I tried to create an online concept of CSS/HTML analyzer tool:
http://www.motobit.com/util/base64/css-images-to-base64.asp
It can:
Comments/suggestions are welcome.
Antonin
After using a find
-based solution for years, I found myself wanting the ability to exclude directories like .git
.
I switched to this rsync
-based solution. Put this in ~/bin/findlatest
:
#!/bin/sh
# Finds most recently modified files.
rsync -rL --list-only "$@" | grep -v '^d' | sort -k3,4r | head -5
Now findlatest .
will list the 5 most recently modified files, and findlatest --exclude .git .
will list the 5 excluding ones in .git
.
This works by taking advantage of some little-used rsync functionality: "if a single source arg is specified [to rsync] without a destination, the files are listed in an output format similar to ls -l" (rsync
man page).
The ability to take rsync args is useful in conjunction with rsync-based backup tools. For instance I use rsnapshot
, and I back up an application directory with rsnapshot.conf
line:
backup /var/atlassian/application-data/jira/current/ home +rsync_long_args=--archive --filter="merge /opt/atlassian/jira/current/backups/rsync-excludes"
where rsync-excludes
lists directories I don't want to backup:
- log/
- logs/
- analytics-logs/
- tmp/
- monitor/*.rrd4j
I can see now the latest files that will be backed up with:
findlatest /var/atlassian/application-data/jira/current/ --filter="merge /opt/atlassian/jira/current/backups/rsync-excludes"
A more general method to create an arbitrary size data frame is to create a n-by-1 data-frame from a matrix of the same dimension. Then, you can immediately drop the first row:
> v <- data.frame(matrix(NA, nrow=1, ncol=10))
> v <- v[-1, , drop=FALSE]
> v
[1] X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
<0 rows> (or 0-length row.names)
This query is for add data from one table to another table using foreign key
let qry = "INSERT INTO `tb_customer_master` (`My_Referral_Code`, `City_Id`, `Cust_Name`, `Reg_Date_Time`, `Mobile_Number`, `Email_Id`, `Gender`, `Cust_Age`, `Profile_Image`, `Token`, `App_Type`, `Refer_By_Referral_Code`, `Status`) values ('" + randomstring.generate(7) + "', '" + req.body.City_Id + "', '" + req.body.Cust_Name + "', '" + req.body.Reg_Date_Time + "','" + req.body.Mobile_Number + "','" + req.body.Email_Id + "','" + req.body.Gender + "','" + req.body.Cust_Age + "','" + req.body.Profile_Image + "','" + req.body.Token + "','" + req.body.App_Type + "','" + req.body.Refer_By_Referral_Code + "','" + req.body.Status + "')";
connection.query(qry, (err, rows) => {
if (err) { res.send(err) } else {
let insert = "INSERT INTO `tb_customer_and_transaction_master` (`Cust_Id`)values ('" + rows.insertId + "')";
connection.query(insert, (err) => {
if (err) {
res.json(err)
} else {
res.json("Customer added")
}
})
}
})
}
}
}
})
})
Linux dotnet core doesn't support namedpipes!
Try TcpListener if you deploy to Linux
This NamedPipe Client/Server code round trips a byte to a server.
DotNet Core 2.0 Server ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Server
{
class Program
{
static void Main(string[] args)
{
var server = new NamedPipeServerStream("A", PipeDirection.InOut);
server.WaitForConnection();
for (int i =0; i < 10000; i++)
{
var b = new byte[1];
server.Read(b, 0, 1);
Console.WriteLine("Read Byte:" + b[0]);
server.Write(b, 0, 1);
}
}
}
}
DotNet Core 2.0 Client ConsoleApp
using System;
using System.IO.Pipes;
using System.Threading.Tasks;
namespace Client
{
class Program
{
public static int threadcounter = 1;
public static NamedPipeClientStream client;
static void Main(string[] args)
{
client = new NamedPipeClientStream(".", "A", PipeDirection.InOut, PipeOptions.Asynchronous);
client.Connect();
var t1 = new System.Threading.Thread(StartSend);
var t2 = new System.Threading.Thread(StartSend);
t1.Start();
t2.Start();
}
public static void StartSend()
{
int thisThread = threadcounter;
threadcounter++;
StartReadingAsync(client);
for (int i = 0; i < 10000; i++)
{
var buf = new byte[1];
buf[0] = (byte)i;
client.WriteAsync(buf, 0, 1);
Console.WriteLine($@"Thread{thisThread} Wrote: {buf[0]}");
}
}
public static async Task StartReadingAsync(NamedPipeClientStream pipe)
{
var bufferLength = 1;
byte[] pBuffer = new byte[bufferLength];
await pipe.ReadAsync(pBuffer, 0, bufferLength).ContinueWith(async c =>
{
Console.WriteLine($@"read data {pBuffer[0]}");
await StartReadingAsync(pipe); // read the next data <--
});
}
}
}
verbose: Integer
. 0, 1, or 2. Verbosity mode.
Verbose=0 (silent)
Verbose=1 (progress bar)
Train on 186219 samples, validate on 20691 samples
Epoch 1/2
186219/186219 [==============================] - 85s 455us/step - loss: 0.5815 - acc:
0.7728 - val_loss: 0.4917 - val_acc: 0.8029
Train on 186219 samples, validate on 20691 samples
Epoch 2/2
186219/186219 [==============================] - 84s 451us/step - loss: 0.4921 - acc:
0.8071 - val_loss: 0.4617 - val_acc: 0.8168
Verbose=2 (one line per epoch)
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
- 88s - loss: 0.5746 - acc: 0.7753 - val_loss: 0.4816 - val_acc: 0.8075
Train on 186219 samples, validate on 20691 samples
Epoch 1/1
- 88s - loss: 0.4880 - acc: 0.8076 - val_loss: 0.5199 - val_acc: 0.8046
When using dag
instead of thin
, the syntax below pointing to service name worked for me. The jdbc:thin
solutions above did not work.
jdbc:dag:oracle://HOSTNAME:1521;ServiceName=SERVICE_NAME
There are lots of answers, but none explained nicely what else can be done. Looking into man pages for dd, it is possible to better specify the size of a file.
This is going to create /tmp/zero_big_data_file.bin filled with zeros, that has size of 20 megabytes :
dd if=/dev/zero of=/tmp/zero_big_data_file.bin bs=1M count=20
This is going to create /tmp/zero_1000bytes_data_file.bin filled with zeros, that has size of 1000 bytes :
dd if=/dev/zero of=/tmp/zero_1000bytes_data_file.bin bs=1kB count=1
or
dd if=/dev/zero of=/tmp/zero_1000bytes_data_file.bin bs=1000 count=1
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
Well at the place of openssl ... you have to put actually the path to your openssl folder that you have downloaded. Your actual command should look like:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | "C:\Users\abc\openssl\bin\openssl.exe" sha1 -binary | "C:\Users\abc\openssl\bin\openssl.exe" base64
Remember, path that you will enter will be the path where you have installed the openssl...hope this helps..:-)
Edit:
you can download openssl for windows 32 and 64 bit from the respective links below:
I have a small script interruptableloop.py that runs the code at an interval (default 1sec), it pumps out a message to the screen while it's running, and traps an interrupt signal that you can send with CTL-C:
#!/usr/bin/python3
from interruptableLoop import InterruptableLoop
loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
# some python code that I want
# to keep on running
pass
When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):
[py36]$ ./interruptexample.py
CTL-C to stop (or $kill -s SIGINT pid)
......^C
Exiting at 2018-07-28 14:58:40.359331
interruptableLoop.py:
"""
Use to create a permanent loop that can be stopped ...
... from same terminal where process was started and is running in foreground:
CTL-C
... from same user account but through a different terminal
$ kill -2 <pid>
or $ kill -s SIGINT <pid>
"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
def __init__(self,intervalSecs=1,printStatus=True):
self.intervalSecs=intervalSecs
self.shouldContinue=True
self.printStatus=printStatus
self.interrupted=False
if self.printStatus:
print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
signal.signal(signal.SIGINT, self._StopRunning)
signal.signal(signal.SIGQUIT, self._Abort)
signal.signal(signal.SIGTERM, self._Abort)
def _StopRunning(self, signal, frame):
self.shouldContinue = False
def _Abort(self, signal, frame):
raise
def ShouldContinue(self):
time.sleep(self.intervalSecs)
if self.shouldContinue and self.printStatus:
print( ".",end="",flush=True)
elif not self.shouldContinue and self.printStatus:
print ("Exiting at ",dtt.now())
return self.shouldContinue
I don't know why you think there's no constructor. See the API.
You can get the actual height of called layout with this code:
public int getLayoutSize() {
// Get the layout id
final LinearLayout root = (LinearLayout) findViewById(R.id.mainroot);
final AtomicInteger layoutHeight = new AtomicInteger();
root.post(new Runnable() {
public void run() {
Rect rect = new Rect();
Window win = getWindow(); // Get the Window
win.getDecorView().getWindowVisibleDisplayFrame(rect);
// Get the height of Status Bar
int statusBarHeight = rect.top;
// Get the height occupied by the decoration contents
int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
// Calculate titleBarHeight by deducting statusBarHeight from contentViewTop
int titleBarHeight = contentViewTop - statusBarHeight;
Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop);
// By now we got the height of titleBar & statusBar
// Now lets get the screen size
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int screenHeight = metrics.heightPixels;
int screenWidth = metrics.widthPixels;
Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);
// Now calculate the height that our layout can be set
// If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also
layoutHeight.set(screenHeight - (titleBarHeight + statusBarHeight));
Log.i("MY", "Layout Height = " + layoutHeight);
// Lastly, set the height of the layout
FrameLayout.LayoutParams rootParams = (FrameLayout.LayoutParams)root.getLayoutParams();
rootParams.height = layoutHeight.get();
root.setLayoutParams(rootParams);
}
});
return layoutHeight.get();
}
Just to add to the answers above that all use Console.WriteLine
: to change colour on the same line of text, write for example:
Console.Write("This test ");
Console.BackgroundColor = bTestSuccess ? ConsoleColor.DarkGreen : ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine((bTestSuccess ? "PASSED" : "FAILED"));
Console.ResetColor();
If your Dialog is creating on the adapter:
Pass the Activity to the Adapter Constructor:
adapter = new MyAdapter(getActivity(),data);
Receive on the Adapter:
public MyAdapter(Activity activity, List<Data> dataList){
this.activity = activity;
}
Now you can use on your Builder
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:
<StackPanel>
<Label Foreground="Red">Red text</Label>
<Label Foreground="Blue">Blue text</Label>
</StackPanel>
In summary, No, there was nothing wrong with your snippet.
If you're using Blend, to make it extra easy and not have any trouble getting the correct path for the Source attribute, just drag and drop the image from the Project panel onto the designer.
You could also make use of the default case like this:
switch (name) {
case 't':
return filter.getType();
case 'c':
return (filter.getCategory());
default:
if (name.startsWith('f-')) {
return filter.getFeatures({type: name})
}
}
You can check the String.match
() or the String.indexOf()
methods.
Just for the purpose of mentioning underscore's find method works in IE with no problem.
None of those are precisely the same, though they will all have the same net effect.
The difference between the first and the second is that if you happen to be on the main application thread when executing the code, the first one (runOnUiThread()
) will execute the Runnable
immediately. The second one (post()
) always puts the Runnable
at the end of the event queue, even if you are already on the main application thread.
The third one, assuming you create and execute an instance of BackgroundTask
, will waste a lot of time grabbing a thread out of the thread pool, to execute a default no-op doInBackground()
, before eventually doing what amounts to a post()
. This is by far the least efficient of the three. Use AsyncTask
if you actually have work to do in a background thread, not just for the use of onPostExecute()
.
Angular is based on observable instead of promise base as of angularjs 1.x, so when we try to get data using http
it returns observable instead of promise, like you did
return this.http
.get(this.configEndPoint)
.map(res => res.json());
then to get data and show on view we have to convert it into desired form using RxJs functions like .map() function and .subscribe()
.map() is used to convert the observable (received from http request)to any form like .json(), .text()
as stated in Angular's official website,
.subscribe() is used to subscribe those observable response and ton put into some variable so from which we display it into the view
this.myService.getConfig().subscribe(res => {
console.log(res);
this.data = res;
});
ES6 will provide Map.prototype.forEach(callback) which can be used like this
myMap.forEach(function(value, key, myMap) {
// Do something
});
Use asp:image
<asp:Image id="Image1" runat="server"
AlternateText="Image text"
ImageAlign="left"
ImageUrl="images/image1.jpg"/>
and codebehind to change image url
Image1.ImageUrl = "/MyProject;component/Images/down.png";
Your project path contains Chinese characters,
em: F:\??\Yourproject
Please rename the path English characters:
em: F:\Data\Yourproject
How about .delay()
?
$("#test").animate({"top":"-=80px"},1500)
.delay(1000)
.animate({"opacity":"0"},500);
{{value | number : fractionSize}}
like {{12.52311 | number : 2}}
so this will print 12.52
You can try doing:
String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
::-webkit-input-placeholder { /* WebKit browsers */
color: #999;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: #999;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
color: #999;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
color: #999;
}
You can read from stdin and then store inputs into "data" as follows:
data = ""
for line in sys.stdin:
data += line
There should be no difference, but your tuple method is wrong, try:
a_list.append(tuple([3, 4]))
Here is syntax for showing hours and minutes for a field coming out of a SELECT statement. In this example, the SQL field is named "UpdatedOnAt" and is a DateTime. Tested with MS SQL 2014.
SELECT Format(UpdatedOnAt ,'hh:mm') as UpdatedOnAt from MyTable
I like the format that shows the day of the week as a 3-letter abbreviation, and includes the seconds:
SELECT Format(UpdatedOnAt ,'ddd hh:mm:ss') as UpdatedOnAt from MyTable
The "as UpdatedOnAt" suffix is optional. It gives you a column heading equal tot he field you were selecting to begin with.
for this error : conq: repository access denied. access via a deployment key is read-only.
I change the name of my key, example
cd /home/try/.ssh/
mv try id_rsa
mv try.pub id_rsa.pub
I work on my own key on bitbucket
You will get the structure by typing the command:
.schema <tableName>
Just use
$('#SelectBoxId option:selected').text();
For Getting text as listed
$('#SelectBoxId').val();
For Getting selected Index value
What worked for me was to drag the folder into Visual Studio, then right click the folder and select "Open Folder in File Explorer". Then select all and drag them into the folder in Visual Studio.
You can't alter the existing columns for identity.
You have 2 options,
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL
IDENTITY(1, 1),
Name varchar(50) NULL
)
ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS ( SELECT *
FROM dbo.Names )
INSERT INTO dbo.Tmp_Names ( Id, Name )
SELECT Id,
Name
FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
DROP TABLE dbo.Names
go
Exec sp_rename 'Tmp_Names', 'Names'
Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.
Alter Table Names
Add Id_new Int Identity(1, 1)
Go
Alter Table Names Drop Column ID
Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'
See the following Microsoft SQL Server Forum post for more details:
use for loop. like this:
for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
new_list.append(my_list[i + x])
Source article: Java: Calling super()
Yes. super(...)
will invoke the constructor of the super-class.
Illustration:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints:
Constructing an animal: From Dog constructor
Constructing a dog.
With python 3.6, these two lines return a list (may be empty)
>>[int(x) for x in re.findall('\d+', your_string)]
Similar to
>>list(map(int, re.findall('\d+', your_string))
There is also strptime() which expects exactly one format:
$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900);
After a few years and many attempts (I tried all the answers given here, but all of them had minor drawbacks at the end), now I realize that there is a better way than wanting to start, stop, restart a daemon directly from Python: use the OS tools instead.
For example, for Linux, instead of doing python myapp start
and python myapp stop
, I do this to start the app:
screen -S myapp python myapp.py
CTRL+A, D to detach
or screen -dmS myapp python myapp.py
to start and detach it in one command.
Then:
screen -r myapp
to attach to this terminal again. Once in the terminal, it's possible to use CTRL+C to stop it.
It's even easier to use parent > child selector relationship so the inner div do not need to have their css classes to be defined explicitly:
.display-table {_x000D_
display: table; _x000D_
}_x000D_
.display-table > div { _x000D_
display: table-row; _x000D_
}_x000D_
.display-table > div > div { _x000D_
display: table-cell;_x000D_
padding: 5px;_x000D_
}
_x000D_
<div class="display-table">_x000D_
<div>_x000D_
<div>0, 0</div>_x000D_
<div>0, 1</div>_x000D_
</div>_x000D_
<div>_x000D_
<div>1, 0</div>_x000D_
<div>1, 1</div>_x000D_
</div>_x000D_
</div>
_x000D_
Well, an application may have a lot of threads running in parallel. Some are run by you, the coder, some are run by framework classes (espacially if you are in a GUI environnement).
When a thread has finished its task, it exits and stops to exist. There ie nothing alarming in this and you should not care.
Set Clickable as false and change the backgroung color as:
callButton.setClickable(false);
callButton.setBackgroundColor(Color.parseColor("#808080"));
Most of my needs were satisfied by this answer https://stackoverflow.com/a/2989277/3001007 by krzysztof. But one issue with that code (i faced was), the binding won't work with multiple controls. So I changed _recursionProtection
with a Guid
based implementation. So it's working for Multiple controls in same window as well.
public class RichTextBoxHelper : DependencyObject
{
private static List<Guid> _recursionProtection = new List<Guid>();
public static string GetDocumentXaml(DependencyObject obj)
{
return (string)obj.GetValue(DocumentXamlProperty);
}
public static void SetDocumentXaml(DependencyObject obj, string value)
{
var fw1 = (FrameworkElement)obj;
if (fw1.Tag == null || (Guid)fw1.Tag == Guid.Empty)
fw1.Tag = Guid.NewGuid();
_recursionProtection.Add((Guid)fw1.Tag);
obj.SetValue(DocumentXamlProperty, value);
_recursionProtection.Remove((Guid)fw1.Tag);
}
public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(
"DocumentXaml",
typeof(string),
typeof(RichTextBoxHelper),
new FrameworkPropertyMetadata(
"",
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
(obj, e) =>
{
var richTextBox = (RichTextBox)obj;
if (richTextBox.Tag != null && _recursionProtection.Contains((Guid)richTextBox.Tag))
return;
// Parse the XAML to a document (or use XamlReader.Parse())
try
{
string docXaml = GetDocumentXaml(richTextBox);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(docXaml));
FlowDocument doc;
if (!string.IsNullOrEmpty(docXaml))
{
doc = (FlowDocument)XamlReader.Load(stream);
}
else
{
doc = new FlowDocument();
}
// Set the document
richTextBox.Document = doc;
}
catch (Exception)
{
richTextBox.Document = new FlowDocument();
}
// When the document changes update the source
richTextBox.TextChanged += (obj2, e2) =>
{
RichTextBox richTextBox2 = obj2 as RichTextBox;
if (richTextBox2 != null)
{
SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));
}
};
}
)
);
}
For completeness sake, let me add few more lines from original answer https://stackoverflow.com/a/2641774/3001007 by ray-burns. This is how to use the helper.
<RichTextBox local:RichTextBoxHelper.DocumentXaml="{Binding Autobiography}" />
Here is another way to do it.
import webbrowser
webbrowser.open("foobar.com")
Here is how one can do it. I will give an example with joining so that it becomes super clear to someone.
$products = DB::table('products AS pr')
->leftJoin('product_families AS pf', 'pf.id', '=', 'pr.product_family_id')
->select('pr.id as id', 'pf.name as product_family_name', 'pf.id as product_family_id')
->orderBy('pr.id', 'desc')
->get();
Hope this helps.
if SQL comes naturally to you, sqldf
package handles ORDER BY
as Codd intended.
The easiest way to do it is using Storyboard and a Segue.
Just create a Segue from the FirstViewController (not the Navigation Controller) of your TabBarController to a LoginViewController with the login UI and name it "showLogin".
Create a method that returns a BOOL to validate if the user logged in and/or his/her session is valid... preferably on the AppDelegate. Call it isSessionValid.
On your FirstViewController.m override the method viewDidAppear as follows:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if([self isSessionValid]==NO){
[self performSegueWithIdentifier:@"showLogin" sender:self];
}
}
Then if the user logged in successfully, just dismiss or pop-out the LoginViewController to show your tabs.
Works 100%!
Hope it helps!
The code pasted by Rivers is great. Thanks a lot! I'm new here and can't comment, I'd just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as I've lost a lot of time to figure it out.
You need to add the parameters both to the URL and to the signature creating process. Creating a signature is the article that helped me. Here is my code:
$oauth = array(
'screen_name' => 'DwightHoward',
'count' => 2,
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$options = array(
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
);
Somehow using Raja's approach worked for me only once, after a reboot, it seems gone.
To make it persistent across Mac OS reboot, I added this line into my ~/.zshrc
since I'm using zsh:
export PATH=/Applications/Visual\ Studio\ Code.app/Contents/Resources/app/bin:$PATH
then
source ~/.zshrc
now, I could just do
code .
even after I reboot my Mac.
This is very simple. Add a button in the layout file like
<Button
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Login with facebook"
android:textColor="#ffff"
android:layout_gravity="center"
android:textStyle="bold"
android:onClick="fbLogin"
android:background="@color/colorPrimary"/>
And in the onClick place the LoginManager's registercallback() method Becuse the this method automatically executes.
public void fbLogin(View view)
{
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("user_photos", "email", "public_profile", "user_posts" , "AccessToken"));
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>()
{
@Override
public void onSuccess(LoginResult loginResult)
{
// App code
}
@Override
public void onCancel()
{
// App code
}
@Override
public void onError(FacebookException exception)
{
// App code
}
});
}
Try this:
select CONVERT(VARCHAR(5), ' 4:07PM', 108) + ' ' + RIGHT(CONVERT(VARCHAR(30), ' 4:07PM', 9),2) as ConvertedTime
I feel compelled to provide a counterpoint to Ashwini Chaudhary's answer. Despite appearances, the two-argument form of the round
function does not round a Python float to a given number of decimal places, and it's often not the solution you want, even when you think it is. Let me explain...
The ability to round a (Python) float to some number of decimal places is something that's frequently requested, but turns out to be rarely what's actually needed. The beguilingly simple answer round(x, number_of_places)
is something of an attractive nuisance: it looks as though it does what you want, but thanks to the fact that Python floats are stored internally in binary, it's doing something rather subtler. Consider the following example:
>>> round(52.15, 1)
52.1
With a naive understanding of what round
does, this looks wrong: surely it should be rounding up to 52.2
rather than down to 52.1
? To understand why such behaviours can't be relied upon, you need to appreciate that while this looks like a simple decimal-to-decimal operation, it's far from simple.
So here's what's really happening in the example above. (deep breath) We're displaying a decimal representation of the nearest binary floating-point number to the nearest n
-digits-after-the-point decimal number to a binary floating-point approximation of a numeric literal written in decimal. So to get from the original numeric literal to the displayed output, the underlying machinery has made four separate conversions between binary and decimal formats, two in each direction. Breaking it down (and with the usual disclaimers about assuming IEEE 754 binary64 format, round-ties-to-even rounding, and IEEE 754 rules):
First the numeric literal 52.15
gets parsed and converted to a Python float. The actual number stored is 7339460017730355 * 2**-47
, or 52.14999999999999857891452847979962825775146484375
.
Internally as the first step of the round
operation, Python computes the closest 1-digit-after-the-point decimal string to the stored number. Since that stored number is a touch under the original value of 52.15
, we end up rounding down and getting a string 52.1
. This explains why we're getting 52.1
as the final output instead of 52.2
.
Then in the second step of the round
operation, Python turns that string back into a float, getting the closest binary floating-point number to 52.1
, which is now 7332423143312589 * 2**-47
, or 52.10000000000000142108547152020037174224853515625
.
Finally, as part of Python's read-eval-print loop (REPL), the floating-point value is displayed (in decimal). That involves converting the binary value back to a decimal string, getting 52.1
as the final output.
In Python 2.7 and later, we have the pleasant situation that the two conversions in step 3 and 4 cancel each other out. That's due to Python's choice of repr
implementation, which produces the shortest decimal value guaranteed to round correctly to the actual float. One consequence of that choice is that if you start with any (not too large, not too small) decimal literal with 15 or fewer significant digits then the corresponding float will be displayed showing those exact same digits:
>>> x = 15.34509809234
>>> x
15.34509809234
Unfortunately, this furthers the illusion that Python is storing values in decimal. Not so in Python 2.6, though! Here's the original example executed in Python 2.6:
>>> round(52.15, 1)
52.200000000000003
Not only do we round in the opposite direction, getting 52.2
instead of 52.1
, but the displayed value doesn't even print as 52.2
! This behaviour has caused numerous reports to the Python bug tracker along the lines of "round is broken!". But it's not round
that's broken, it's user expectations. (Okay, okay, round
is a little bit broken in Python 2.6, in that it doesn't use correct rounding.)
Short version: if you're using two-argument round, and you're expecting predictable behaviour from a binary approximation to a decimal round of a binary approximation to a decimal halfway case, you're asking for trouble.
So enough with the "two-argument round is bad" argument. What should you be using instead? There are a few possibilities, depending on what you're trying to do.
If you're rounding for display purposes, then you don't want a float result at all; you want a string. In that case the answer is to use string formatting:
>>> format(66.66666666666, '.4f')
'66.6667'
>>> format(1.29578293, '.6f')
'1.295783'
Even then, one has to be aware of the internal binary representation in order not to be surprised by the behaviour of apparent decimal halfway cases.
>>> format(52.15, '.1f')
'52.1'
If you're operating in a context where it matters which direction decimal halfway cases are rounded (for example, in some financial contexts), you might want to represent your numbers using the Decimal
type. Doing a decimal round on the Decimal
type makes a lot more sense than on a binary type (equally, rounding to a fixed number of binary places makes perfect sense on a binary type). Moreover, the decimal
module gives you better control of the rounding mode. In Python 3, round
does the job directly. In Python 2, you need the quantize
method.
>>> Decimal('66.66666666666').quantize(Decimal('1e-4'))
Decimal('66.6667')
>>> Decimal('1.29578293').quantize(Decimal('1e-6'))
Decimal('1.295783')
In rare cases, the two-argument version of round
really is what you want: perhaps you're binning floats into bins of size 0.01
, and you don't particularly care which way border cases go. However, these cases are rare, and it's difficult to justify the existence of the two-argument version of the round
builtin based on those cases alone.
$str = trim(preg_replace('/\s+/',' ', $str));
The above line of code will remove extra spaces, as well as leading and trailing spaces.
After spending some time reading over a couple different threads that seemed pretty complicated I came up with this. I needed it for an 8 core machine where I wanted to monitor SQL server. For the code below then I passed in "sqlservr" as appName.
private static void RunTest(string appName)
{
bool done = false;
PerformanceCounter total_cpu = new PerformanceCounter("Process", "% Processor Time", "_Total");
PerformanceCounter process_cpu = new PerformanceCounter("Process", "% Processor Time", appName);
while (!done)
{
float t = total_cpu.NextValue();
float p = process_cpu.NextValue();
Console.WriteLine(String.Format("_Total = {0} App = {1} {2}%\n", t, p, p / t * 100));
System.Threading.Thread.Sleep(1000);
}
}
It seems to correctly measure the % of CPU being used by SQL on my 8 core server.
var args = [ 'p0', 'p1', 'p2' ];
function call_me (param0, param1, param2 ) {
// ...
}
// Calling the function using the array with apply()
call_me.apply(this, args);
And here a link to the original post that I personally liked for its readability
But you might also want to look into a very different approach, listening for file-system events.
checkout: window.print() not working in IE
Working sample: http://jsfiddle.net/Q5Xc9/1/
I just encountered this in my code and it took me a while to figure it out. I was doing an intersection of two sorted lists and was only getting small numbers in my output. I could get it to work by using (x - y == 0)
instead of (x == y)
during comparison.
As of today (27, February 2020) Oracle announced that it has published all JDBC client libraries from version 11.2.0.4 (e.g. ojdbc6) to 19.3.0 (e.g. ojdbc10) on Maven Central under the group id com.oracle.database:
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc10</artifactId>
<version>19.3.0.0</version>
</dependency>
Try this out to execute a command on 30th March 2011 at midnight:
0 0 30 3 ? 2011 /command
WARNING: As noted in comments, the year column is not supported in standard/default implementations of cron. Please refer to TomOnTime answer below, for a proper way to run a script at a specific time in the future in standard implementations of cron.
@Petr Mensik & kensen john
Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:
<%
String callback = request.getParameter("callback");
response.setCharacterEncoding("UTF-8");
if (callback != null) {
// Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
response.setContentType("text/javascript");
} else {
// Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
response.setContentType("application/json");
}
[...]
String output = "";
if (callback != null) {
output += callback + "(";
}
output += jsonObj.toString();
if (callback != null) {
output += ");";
}
%>
<%=output %>
When callback is supplied, returns:
callback({...JSON stuff...});
with content-type "text/javascript"
When callback is NOT supplied, returns:
{...JSON stuff...}
with content-type "application/json"
you should not use a.x for accumulator , Instead you can do like this `arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(a,b){a + b.x},0)`
You need to add uppercase L
at the end like so
long i = 12345678910L;
Same goes true for float with 3.0f
Which should answer both of your questions
If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".
Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".
#include <string.h>
char *token;
char line[] = "SEVERAL WORDS";
char *search = " ";
// Token will point to "SEVERAL".
token = strtok(line, search);
// Token will point to "WORDS".
token = strtok(NULL, search);
Note that on some operating systems, strtok
man page mentions:
This interface is obsoleted by strsep(3).
An example with strsep
is shown below:
char* token;
char* string;
char* tofree;
string = strdup("abc,def,ghi");
if (string != NULL) {
tofree = string;
while ((token = strsep(&string, ",")) != NULL)
{
printf("%s\n", token);
}
free(tofree);
}
Simplest solution seems to be specifying the ylim
range. Here is some code to do this automatically (left default, right - adjusted):
# default y-axis
barplot(dat, beside=TRUE)
# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))
The trick is to use pretty()
which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.
In the example 0 was also added pretty(c(0, dat))
which makes sure that axis starts from 0.
But if i take the piece of sql and run it from sql management studio, it will run without issue.
If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.
The real crux of the issue is:
I use the following to convert -> date.Value.ToString("MM/dd/yyyy HH:mm:ss")
Please start using parameterized queries so that you won't encounter these issues in the future. It is also more robust, predictable and best practice.
The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.
private void watch()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.NotifyFilter = NotifyFilters.LastWrite;
watcher.Filter = "*.*";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
This is a comprehensive list of all liquibase datatypes and how they are converted for different databases:
boolean
MySQLDatabase: BIT(1)
SQLiteDatabase: BOOLEAN
H2Database: BOOLEAN
PostgresDatabase: BOOLEAN
UnsupportedDatabase: BOOLEAN
DB2Database: SMALLINT
MSSQLDatabase: [bit]
OracleDatabase: NUMBER(1)
HsqlDatabase: BOOLEAN
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: BOOLEAN
SybaseDatabase: BIT
SybaseASADatabase: BIT
tinyint
MySQLDatabase: TINYINT
SQLiteDatabase: TINYINT
H2Database: TINYINT
PostgresDatabase: SMALLINT
UnsupportedDatabase: TINYINT
DB2Database: SMALLINT
MSSQLDatabase: [tinyint]
OracleDatabase: NUMBER(3)
HsqlDatabase: TINYINT
FirebirdDatabase: SMALLINT
DerbyDatabase: SMALLINT
InformixDatabase: TINYINT
SybaseDatabase: TINYINT
SybaseASADatabase: TINYINT
int
MySQLDatabase: INT
SQLiteDatabase: INTEGER
H2Database: INT
PostgresDatabase: INT
UnsupportedDatabase: INT
DB2Database: INTEGER
MSSQLDatabase: [int]
OracleDatabase: INTEGER
HsqlDatabase: INT
FirebirdDatabase: INT
DerbyDatabase: INTEGER
InformixDatabase: INT
SybaseDatabase: INT
SybaseASADatabase: INT
mediumint
MySQLDatabase: MEDIUMINT
SQLiteDatabase: MEDIUMINT
H2Database: MEDIUMINT
PostgresDatabase: MEDIUMINT
UnsupportedDatabase: MEDIUMINT
DB2Database: MEDIUMINT
MSSQLDatabase: [int]
OracleDatabase: MEDIUMINT
HsqlDatabase: MEDIUMINT
FirebirdDatabase: MEDIUMINT
DerbyDatabase: MEDIUMINT
InformixDatabase: MEDIUMINT
SybaseDatabase: MEDIUMINT
SybaseASADatabase: MEDIUMINT
bigint
MySQLDatabase: BIGINT
SQLiteDatabase: BIGINT
H2Database: BIGINT
PostgresDatabase: BIGINT
UnsupportedDatabase: BIGINT
DB2Database: BIGINT
MSSQLDatabase: [bigint]
OracleDatabase: NUMBER(38, 0)
HsqlDatabase: BIGINT
FirebirdDatabase: BIGINT
DerbyDatabase: BIGINT
InformixDatabase: INT8
SybaseDatabase: BIGINT
SybaseASADatabase: BIGINT
float
MySQLDatabase: FLOAT
SQLiteDatabase: FLOAT
H2Database: FLOAT
PostgresDatabase: FLOAT
UnsupportedDatabase: FLOAT
DB2Database: FLOAT
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT
HsqlDatabase: FLOAT
FirebirdDatabase: FLOAT
DerbyDatabase: FLOAT
InformixDatabase: FLOAT
SybaseDatabase: FLOAT
SybaseASADatabase: FLOAT
double
MySQLDatabase: DOUBLE
SQLiteDatabase: DOUBLE
H2Database: DOUBLE
PostgresDatabase: DOUBLE PRECISION
UnsupportedDatabase: DOUBLE
DB2Database: DOUBLE
MSSQLDatabase: [float](53)
OracleDatabase: FLOAT(24)
HsqlDatabase: DOUBLE
FirebirdDatabase: DOUBLE PRECISION
DerbyDatabase: DOUBLE
InformixDatabase: DOUBLE PRECISION
SybaseDatabase: DOUBLE
SybaseASADatabase: DOUBLE
decimal
MySQLDatabase: DECIMAL
SQLiteDatabase: DECIMAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL
MSSQLDatabase: [decimal](18, 0)
OracleDatabase: DECIMAL
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL
DerbyDatabase: DECIMAL
InformixDatabase: DECIMAL
SybaseDatabase: DECIMAL
SybaseASADatabase: DECIMAL
number
MySQLDatabase: numeric
SQLiteDatabase: NUMBER
H2Database: NUMBER
PostgresDatabase: numeric
UnsupportedDatabase: NUMBER
DB2Database: numeric
MSSQLDatabase: [numeric](18, 0)
OracleDatabase: NUMBER
HsqlDatabase: numeric
FirebirdDatabase: numeric
DerbyDatabase: numeric
InformixDatabase: numeric
SybaseDatabase: numeric
SybaseASADatabase: numeric
blob
MySQLDatabase: LONGBLOB
SQLiteDatabase: BLOB
H2Database: BLOB
PostgresDatabase: BYTEA
UnsupportedDatabase: BLOB
DB2Database: BLOB
MSSQLDatabase: [varbinary](MAX)
OracleDatabase: BLOB
HsqlDatabase: BLOB
FirebirdDatabase: BLOB
DerbyDatabase: BLOB
InformixDatabase: BLOB
SybaseDatabase: IMAGE
SybaseASADatabase: LONG BINARY
function
MySQLDatabase: FUNCTION
SQLiteDatabase: FUNCTION
H2Database: FUNCTION
PostgresDatabase: FUNCTION
UnsupportedDatabase: FUNCTION
DB2Database: FUNCTION
MSSQLDatabase: [function]
OracleDatabase: FUNCTION
HsqlDatabase: FUNCTION
FirebirdDatabase: FUNCTION
DerbyDatabase: FUNCTION
InformixDatabase: FUNCTION
SybaseDatabase: FUNCTION
SybaseASADatabase: FUNCTION
UNKNOWN
MySQLDatabase: UNKNOWN
SQLiteDatabase: UNKNOWN
H2Database: UNKNOWN
PostgresDatabase: UNKNOWN
UnsupportedDatabase: UNKNOWN
DB2Database: UNKNOWN
MSSQLDatabase: [UNKNOWN]
OracleDatabase: UNKNOWN
HsqlDatabase: UNKNOWN
FirebirdDatabase: UNKNOWN
DerbyDatabase: UNKNOWN
InformixDatabase: UNKNOWN
SybaseDatabase: UNKNOWN
SybaseASADatabase: UNKNOWN
datetime
MySQLDatabase: datetime
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: datetime
DB2Database: TIMESTAMP
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: datetime
time
MySQLDatabase: time
SQLiteDatabase: time
H2Database: time
PostgresDatabase: TIME WITHOUT TIME ZONE
UnsupportedDatabase: time
DB2Database: time
MSSQLDatabase: [time](7)
OracleDatabase: DATE
HsqlDatabase: time
FirebirdDatabase: time
DerbyDatabase: time
InformixDatabase: INTERVAL HOUR TO FRACTION(5)
SybaseDatabase: time
SybaseASADatabase: time
timestamp
MySQLDatabase: timestamp
SQLiteDatabase: TEXT
H2Database: TIMESTAMP
PostgresDatabase: TIMESTAMP WITHOUT TIME ZONE
UnsupportedDatabase: timestamp
DB2Database: timestamp
MSSQLDatabase: [datetime]
OracleDatabase: TIMESTAMP
HsqlDatabase: TIMESTAMP
FirebirdDatabase: TIMESTAMP
DerbyDatabase: TIMESTAMP
InformixDatabase: DATETIME YEAR TO FRACTION(5)
SybaseDatabase: datetime
SybaseASADatabase: timestamp
date
MySQLDatabase: date
SQLiteDatabase: date
H2Database: date
PostgresDatabase: date
UnsupportedDatabase: date
DB2Database: date
MSSQLDatabase: [date]
OracleDatabase: date
HsqlDatabase: date
FirebirdDatabase: date
DerbyDatabase: date
InformixDatabase: date
SybaseDatabase: date
SybaseASADatabase: date
char
MySQLDatabase: CHAR
SQLiteDatabase: CHAR
H2Database: CHAR
PostgresDatabase: CHAR
UnsupportedDatabase: CHAR
DB2Database: CHAR
MSSQLDatabase: [char](1)
OracleDatabase: CHAR
HsqlDatabase: CHAR
FirebirdDatabase: CHAR
DerbyDatabase: CHAR
InformixDatabase: CHAR
SybaseDatabase: CHAR
SybaseASADatabase: CHAR
varchar
MySQLDatabase: VARCHAR
SQLiteDatabase: VARCHAR
H2Database: VARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: VARCHAR
DB2Database: VARCHAR
MSSQLDatabase: [varchar](1)
OracleDatabase: VARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: VARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: VARCHAR
SybaseDatabase: VARCHAR
SybaseASADatabase: VARCHAR
nchar
MySQLDatabase: NCHAR
SQLiteDatabase: NCHAR
H2Database: NCHAR
PostgresDatabase: NCHAR
UnsupportedDatabase: NCHAR
DB2Database: NCHAR
MSSQLDatabase: [nchar](1)
OracleDatabase: NCHAR
HsqlDatabase: CHAR
FirebirdDatabase: NCHAR
DerbyDatabase: NCHAR
InformixDatabase: NCHAR
SybaseDatabase: NCHAR
SybaseASADatabase: NCHAR
nvarchar
MySQLDatabase: NVARCHAR
SQLiteDatabase: NVARCHAR
H2Database: NVARCHAR
PostgresDatabase: VARCHAR
UnsupportedDatabase: NVARCHAR
DB2Database: NVARCHAR
MSSQLDatabase: [nvarchar](1)
OracleDatabase: NVARCHAR2
HsqlDatabase: VARCHAR
FirebirdDatabase: NVARCHAR
DerbyDatabase: VARCHAR
InformixDatabase: NVARCHAR
SybaseDatabase: NVARCHAR
SybaseASADatabase: NVARCHAR
clob
MySQLDatabase: LONGTEXT
SQLiteDatabase: TEXT
H2Database: CLOB
PostgresDatabase: TEXT
UnsupportedDatabase: CLOB
DB2Database: CLOB
MSSQLDatabase: [varchar](MAX)
OracleDatabase: CLOB
HsqlDatabase: CLOB
FirebirdDatabase: BLOB SUB_TYPE TEXT
DerbyDatabase: CLOB
InformixDatabase: CLOB
SybaseDatabase: TEXT
SybaseASADatabase: LONG VARCHAR
currency
MySQLDatabase: DECIMAL
SQLiteDatabase: REAL
H2Database: DECIMAL
PostgresDatabase: DECIMAL
UnsupportedDatabase: DECIMAL
DB2Database: DECIMAL(19, 4)
MSSQLDatabase: [money]
OracleDatabase: NUMBER(15, 2)
HsqlDatabase: DECIMAL
FirebirdDatabase: DECIMAL(18, 4)
DerbyDatabase: DECIMAL
InformixDatabase: MONEY
SybaseDatabase: MONEY
SybaseASADatabase: MONEY
uuid
MySQLDatabase: char(36)
SQLiteDatabase: TEXT
H2Database: UUID
PostgresDatabase: UUID
UnsupportedDatabase: char(36)
DB2Database: char(36)
MSSQLDatabase: [uniqueidentifier]
OracleDatabase: RAW(16)
HsqlDatabase: char(36)
FirebirdDatabase: char(36)
DerbyDatabase: char(36)
InformixDatabase: char(36)
SybaseDatabase: UNIQUEIDENTIFIER
SybaseASADatabase: UNIQUEIDENTIFIER
For reference, this is the groovy script I've used to generate this output:
@Grab('org.liquibase:liquibase-core:3.5.1')
import liquibase.database.core.*
import liquibase.datatype.core.*
def datatypes = [BooleanType,TinyIntType,IntType,MediumIntType,BigIntType,FloatType,DoubleType,DecimalType,NumberType,BlobType,DatabaseFunctionType,UnknownType,DateTimeType,TimeType,TimestampType,DateType,CharType,VarcharType,NCharType,NVarcharType,ClobType,CurrencyType,UUIDType]
def databases = [MySQLDatabase, SQLiteDatabase, H2Database, PostgresDatabase, UnsupportedDatabase, DB2Database, MSSQLDatabase, OracleDatabase, HsqlDatabase, FirebirdDatabase, DerbyDatabase, InformixDatabase, SybaseDatabase, SybaseASADatabase]
datatypes.each {
def datatype = it.newInstance()
datatype.finishInitialization("")
println datatype.name
databases.each { println "$it.simpleName: ${datatype.toDatabaseDataType(it.newInstance())}"}
println ''
}
Use the WebClient
class in System.Net
:
var json = new WebClient().DownloadString("url");
Keep in mind that WebClient
is IDisposable
, so you would probably add a using
statement to this in production code. This would look like:
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("url");
}
import java.text.Normalizer;
import org.apache.commons.lang3.StringUtils;
public class ContainsIgnoreCase {
public static void main(String[] args) {
String in = " Annulée ";
String key = "annulee";
// 100% java
if (Normalizer.normalize(in, Normalizer.Form.NFD).replaceAll("[\\p{InCombiningDiacriticalMarks}]", "").toLowerCase().contains(key)) {
System.out.println("OK");
} else {
System.out.println("KO");
}
// use commons.lang lib
if (StringUtils.containsIgnoreCase(Normalizer.normalize(in, Normalizer.Form.NFD).replaceAll("[\\p{InCombiningDiacriticalMarks}]", ""), key)) {
System.out.println("OK");
} else {
System.out.println("KO");
}
}
}
use directly where you want controller or web.php
Request::getHost();
try to send content type header from server use this just before echoing
header('Content-Type: application/json');
You can use three quotes to do it.
You can use single quotes:
def myfunction(para1,para2):
'''
The stuff inside the function
'''
Or double quotes:
def myfunction(para1,para2):
"""
The stuff inside the function
"""
class String
def integer?
Integer(self)
return true
rescue ArgumentError
return false
end
end
is_
. I find that silly on questionmark methods, I like "04".integer?
a lot better than "foo".is_integer?
."01"
and such.I had to update the proxy settings under Plugins -> Plugin Manager -> Show Plugin Manager -> Settings to see any PlugIns in the "Available" list.
After that, installing "XML Tools" was easy and did the requested job as described above.
You can adjust the plot margins with plot.margin
in theme()
and then move your axis labels and title with the vjust
argument of element_text()
. For example :
library(ggplot2)
library(grid)
qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.title.x=element_text(vjust=-2)) +
theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
theme(plot.title=element_text(size=15, vjust=3)) +
theme(plot.margin = unit(c(1,1,1,1), "cm"))
will give you something like this :
If you want more informations about the different theme()
parameters and their arguments, you can just enter ?theme
at the R prompt.
Maybe your mobile view port is not set.
Add following meta tag inside <head></head>
to allow menu to work on mobiles.
<meta name=viewport content="width=device-width, initial-scale=1">
This one is noteworthy as well
<div ng-repeat="post in posts" ng-if="post.type=='article'">
<h1>{{post.title}}</h1>
</div>
I do recomend doing it in 2 filles (.h .cpp)
But if u lazy just add inline
before the function
So it will look something like this
inline void functionX()
{ }
more about inline functions:
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called. Compiler replaces the definition of inline functions at compile time instead of referring function definition at runtime. NOTE- This is just a suggestion to compiler to make the function inline, if function is big (in term of executable instruction etc) then, compiler can ignore the “inline” request and treat the function as normal function.
more info here
There are multiple methods for handling this problem.
My advice is to use the powerful Windows freeware console application SendEmail.
sendEmail.exe -f [email protected] -o message-file=body.txt -u subject message -t [email protected] -a attachment.zip -s smtp.gmail.com:446 -xu gmail.login -xp gmail.password
Some nice intuition that might help, using any Linux(ish) console.
Create two files:
$ touch foo; touch bar
Enter some Data into them:
$ echo "Cat" > foo
$ echo "Dog" > bar
(Actually, I could have used echo in the first place, as it creates the files if they don't exist... but never mind that.)
And as expected:
$cat foo; cat bar
Cat
Dog
Let's create hard and soft links:
$ ln foo foo-hard
$ ln -s bar bar-soft
Let's see what just happened:
$ ls -l
foo
foo-hard
bar
bar-soft -> bar
Changing the name of foo does not matter:
$ mv foo foo-new
$ cat foo-hard
Cat
foo-hard points to the inode, the contents, of the file - that wasn't changed.
$ mv bar bar-new
$ ls bar-soft
bar-soft
$ cat bar-soft
cat: bar-soft: No such file or directory
The contents of the file could not be found because the soft link points to the name, that was changed, and not to the contents.
Likewise, If foo
is deleted, foo-hard
still holds the contents; if bar
is deleted, bar-soft
is just a link to a non-existing file.
Check this: How to maximize a plt.show() window using Python
The command is different depending on which backend you use. I find that this is the best way to make sure the saved pictures have the same scaling as what I view on my screen.
Since I use Canopy with the QT backend:
pylab.get_current_fig_manager().window.showMaximized()
I then call savefig() as required with an increased DPI per silvado's answer.
I found this to be the best way of doing this (I had an issue with my server not letting me delete).
On the server that hosts the origin
repository, type the following from a directory inside the repository:
git config receive.denyDeleteCurrent ignore
On your workstation:
git branch -m master vabandoned # Rename master on local
git branch -m newBranch master # Locally rename branch newBranch to master
git push origin :master # Delete the remote's master
git push origin master:refs/heads/master # Push the new master to the remote
git push origin abandoned:refs/heads/abandoned # Push the old master to the remote
Back on the server that hosts the origin
repository:
git config receive.denyDeleteCurrent true
Credit to the author of blog post http://www.mslinn.com/blog/?p=772
JAVASCRIPT CODE:
<script>
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var user = getUrlVars()["user"];
var pass = getUrlVars()["pass"];
var sub = getUrlVars()["sub"];
</script>
<script>
var myApp = angular.module('myApp',[]);
myApp.controller('dropdownCtrl', ['$scope','$window','$http', function($scope, $window, $http) {
$http.get('http://dummy.com/app/chapter.php?user='+user+'&pass='+pass)
.then(function (response) {$scope.names = response.data.admin;});
$scope.names = [];
$http.get('http://dummy.com/app/chapter.php?user='+user+'&pass='+pass+'&sub='+sub)
.then(function (response) {$scope.chapter = response.data.chp;});
$scope.chapter = [];
};
}]);
</script>
HTML:
<div ng-controller="dropdownCtrl">
<div ng-repeat="a in chapter">
<a href="topic.html?ch={{a.chapter}}" onClick="location.href=this.href+'&user='+user+'&pass='+pass+'&sub='+sub;return false;">{{a.chapter}}</a>
</div>
In visual studio 2017 we can change the port number from LaunchSetting.json
In Properties-> LaunchSettings.json.
Open LaunchSettings.json and change the Port Number.
Change the port Number in json file
Dictionary<string, Dictionary<string, string>> like = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> first = like.Values.First();
if (pathname.substring(0, 6) == "/sub/1") {
// ...
}
With JavaScript you can create a link 'on the fly' using something like:
var mail = document.createElement("a");
mail.href = "mailto:[email protected]";
mail.click();
This is redirected by the browser to some mail client installed on the machine without losing the content of the current window ... and you would not need any API like 'jQuery'.
Somebody posted quite a few form fields to your page. The new default max introduced by the recent security update is 1000.
Try adding the following setting in your web.config's <appsettings>
block. in this block you are maximizing the MaxHttpCollection values this will override the defaults set by .net Framework. you can change the value accordingly as per your form needs
<appSettings>
<add key="aspnet:MaxHttpCollectionKeys" value="2001" />
</appSettings>
For more information please read this post. For more insight into the security patch by microsoft you can read this Knowledge base article
You need to write this in the command prompt:
set HTTP_PROXY=http://your_proxy:your_port
Try this:
SELECT @@VERSION[server], SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')
I think you need to add some context to your question. However, basic information about these things can be found here:
window.opener
https://developer.mozilla.org/en-US/docs/Web/API/Window.opener
I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.
window.parent
https://developer.mozilla.org/en-US/docs/Web/API/Window.parent
I've used this mostly when working with IFrames that need to communicate with the window object that contains them.
window.top
https://developer.mozilla.org/en-US/docs/Web/API/Window.top
This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.
If you add some more detail to your question, I can supply other more relevant examples.
UPDATE:
There are a few ways you can handle your situation.
You have the following structure:
When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.
So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:
childwindow.appMainWindow = window.opener
After making the assignment above, close dialog 1.
Then from the code running inside dialog2, you should be able to use
window.appMainWindow
to reference the main window, window object.
Hope this helps.
Try putting it in quotes:
find . -name '*test.c'
What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:
-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);
If you are searching a string, go for the LIKE operator (but this will be slow):
-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';
If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:
-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';
Refactor your second.sh
script like this:
function func1 {
fun=$1
book=$2
printf "fun=%s,book=%s\n" "${fun}" "${book}"
}
function func2 {
fun2=$1
book2=$2
printf "fun2=%s,book2=%s\n" "${fun2}" "${book2}"
}
And then call these functions from script first.sh
like this:
source ./second.sh
func1 love horror
func2 ball mystery
fun=love,book=horror
fun2=ball,book2=mystery
Use ChartNew.js instead of Chart.js
...
So, I have re-worked Chart.js. Most of the changes, are associated to requests in "GitHub" issues of Chart.js.
And here is a sample http://jsbin.com/lakiyu/2/edit
var newopts = {
inGraphDataShow: true,
inGraphDataRadiusPosition: 2,
inGraphDataFontColor: 'white'
}
var pieData = [
{
value: 30,
color: "#F38630",
},
{
value: 30,
color: "#F34353",
},
{
value: 30,
color: "#F34353",
}
]
var pieCtx = document.getElementById('pieChart').getContext('2d');
new Chart(pieCtx).Pie(pieData, newopts);
It even provides a GUI editor http://charts.livegap.com/
So sweet.
Edit: I just found out while debugging that the class is instantiated before every test too. I guess the @BeforeClass annotation is the best here.
You can set up on the constructor too, the test class is a class after all. I'm not sure if it's a bad practice because almost all other methods are annotated, but it works. You could create a constructor like that:
public UT () {
// initialize once here
}
@Test
// Some test here...
The ctor will be called before the tests because they are not static.
If you want to access the data in instance B from the instance A. Then this is the query, you can edit your respective credential.
CREATE DATABASE LINK dblink_passport
CONNECT TO xxusernamexx IDENTIFIED BY xxpasswordxx
USING
'(DESCRIPTION=
(ADDRESS=
(PROTOCOL=TCP)
(HOST=xxipaddrxx / xxhostxx )
(PORT=xxportxx))
(CONNECT_DATA=
(SID=xxsidxx)))';
After executing this query access table
SELECT * FROM tablename@dblink_passport;
You can perform any operation DML, DDL, DQL
Not sure what the problem is, this seems to work just fine?
DECLARE @StartDate AS DATETIME
DECLARE @EndDate AS DATETIME
SET @StartDate = NULL
SET @EndDate = NULL
IF (@StartDate IS NOT NULL AND @EndDate IS NOT NULL)
BEGIN
Select 'This works just fine' as Msg
END
Else
BEGIN
Select 'No Lol' as Msg
END
It helps not to focus on the strong
or weak
part of the discussion. Instead focus on the cycle part.
A retain cycle is a loop that happens when Object A retains Object B, and Object B retains Object A. In that situation, if either object is released:
Thus, those two objects will just hang around in memory for the life of the program even though they should, if everything were working properly, be deallocated.
So, what we're worried about is retain cycles, and there's nothing about blocks in and of themselves that create these cycles. This isn't a problem, for example:
[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
[self doSomethingWithObject:obj];
}];
The block retains self
, but self
doesn't retain the block. If one or the other is released, no cycle is created and everything gets deallocated as it should.
Where you get into trouble is something like:
//In the interface:
@property (strong) void(^myBlock)(id obj, NSUInteger idx, BOOL *stop);
//In the implementation:
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self doSomethingWithObj:obj];
}];
Now, your object (self
) has an explicit strong
reference to the block. And the block has an implicit strong reference to self
. That's a cycle, and now neither object will be deallocated properly.
Because, in a situation like this, self
by definition already has a strong
reference to the block, it's usually easiest to resolve by making an explicitly weak reference to self
for the block to use:
__weak MyObject *weakSelf = self;
[self setMyBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[weakSelf doSomethingWithObj:obj];
}];
But this should not be the default pattern you follow when dealing with blocks that call self
! This should only be used to break what would otherwise be a retain cycle between self and the block. If you were to adopt this pattern everywhere, you'd run the risk of passing a block to something that got executed after self
was deallocated.
//SUSPICIOUS EXAMPLE:
__weak MyObject *weakSelf = self;
[[SomeOtherObject alloc] initWithCompletion:^{
//By the time this gets called, "weakSelf" might be nil because it's not retained!
[weakSelf doSomething];
}];
For me a DNS name of my server was added to /etc/hosts and it was mapped to 127.0.0.1 which resulted in
SL23_GET_SERVER_HELLO:unknown protocol
Removing mapping of my real DNS name to 127.0.0.1 resolved the problem.
Another option might be node-querystring.
It's available in both npm
and bower
, which is why I have been using it.
RFC 3066 gives the details of the allowed values (emphasis and links added):
All 2-letter subtags are interpreted as ISO 3166 alpha-2 country codes from [ISO 3166], or subsequently assigned by the ISO 3166 maintenance agency or governing standardization bodies, denoting the area to which this language variant relates.
I interpret that as meaning any valid (according to ISO 3166) 2-letter code is valid as a subtag. The RFC goes on to state:
Tags with second subtags of 3 to 8 letters may be registered with IANA, according to the rules in chapter 5 of this document.
By the way, that looks like a typo, since chapter 3 seems to relate to the the registration process, not chapter 5.
A quick search for the IANA registry reveals a very long list, of all the available language subtags. Here's one example from the list (which would be used as en-scouse
):
Type: variant
Subtag: scouse
Description: Scouse
Added: 2006-09-18
Prefix: en
Comments: English Liverpudlian dialect known as 'Scouse'
There are all sorts of subtags available; a quick scroll has already revealed fr-1694acad
(17th century French).
The usefulness of some of these (I would say the vast majority of these) tags, when it comes to documents designed for display in the browser, is limited. The W3C Internationalization specification simply states:
Browsers and other applications can use information about the language of content to deliver to users the most appropriate information, or to present information to users in the most appropriate way. The more content is tagged and tagged correctly, the more useful and pervasive such applications will become.
I'm struggling to find detailed information on how browsers behave when encountering different language tags, but they are most likely going to offer some benefit to those users who use a screen reader, which can use the tag to determine the language/dialect/accent in which to present the content.
Delete your package-lock.json
file and node_modules
folder.
Then do npm cache clean
npm cache clean --force
do
npm install
again and run
Another solution in urllib2
and Python 2.7:
req = urllib2.Request('http://www.example.com/')
req.add_unredirected_header('User-Agent', 'Custom User-Agent')
urllib2.urlopen(req)
In order to add attributes, XSL wants
<xsl:element name="img"> (attributes) </xsl:element>
instead of just
<img> (attributes) </img>
Although, yes, if you're just copying the element as-is, you don't need any of that.
If you end up with none of the above working, you might be able to retrieve data using the suggestion from here: http://www.spinics.net/lists/git/msg62499.html
git prune -n
git cat-file -p <blob #>
If you want to refer to a global variable in a function, you can use the global keyword to declare which variables are global. You don't have to use it in all cases (as someone here incorrectly claims) - if the name referenced in an expression cannot be found in local scope or scopes in the functions in which this function is defined, it is looked up among global variables.
However, if you assign to a new variable not declared as global in the function, it is implicitly declared as local, and it can overshadow any existing global variable with the same name.
Also, global variables are useful, contrary to some OOP zealots who claim otherwise - especially for smaller scripts, where OOP is overkill.
.mat-column-skills {
max-width: 40px;
}
If one of the input when you create is a primary key, this will be enough:
Person.objects.get_or_create(id=1)
It will automatically update if exist since two data with the same primary key is not allowed.
Instead:
public class PhotosFragment extends Fragment
You can use:
public class PhotosFragment extends ListFragment
It change the methods
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayList<ListviewContactItem> listContact = GetlistContact();
setAdapter(new ListviewContactAdapter(getActivity(), listContact));
}
onActivityCreated is void and you didn't need to return a view like in onCreateView
You can see an example here
For the answer above, the default serial port is
serialParams.BaudRate = 9600;
serialParams.ByteSize = 8;
serialParams.StopBits = TWOSTOPBITS;
serialParams.Parity = NOPARITY;
Android does not allow a separate process into the main activity thread, and the HTTP connection is an independent thread here. That is the reason you are getting the "android.os.NetworkOnMainThreadException".
There can be a need where you want to check the actual Internet connection before showing webview to the user, because if there is not Internet the web view will show the page not found error to the user, which normally you don't what to show.
For checking Internet availability, the ping command can be used, but in case of Wi-Fi pinging can be disabled at the Wi-Fi server, so in this case you use an HTTP connection to check the status of the request.
This can be the right approach if you are checking your own webview URL link before showing a webview to the user. In this case, you can use the strict mode of Android, but don't permit all the policy because you don't need it.
You should only give network allow policy for the strict mode. Just add the below line into your code, and you will not get this error.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
If you are after performance and not precision, you should note that calculations with floats are much faster than decimals
You can use white-space: nowrap;
to define this behaviour:
// HTML:
.nowrap {_x000D_
white-space: nowrap ;_x000D_
}
_x000D_
<p>_x000D_
<span class="nowrap">How do I wrap this line of text</span>_x000D_
<span class="nowrap">- asked by Peter 2 days ago</span>_x000D_
</p>
_x000D_
// CSS:
.nowrap {
white-space: nowrap ;
}
Download and install IOBIT uninstaller: http://www.iobit.com/advanceduninstaller.php, find the date in which you install Visual Studio and select all programas from that date r elated to VS. Then run de batch uninstaller. It is not a fully automated solution but it is a lot quicker than going one by one int he add / remove programs in Windows. It even has a power scan to clean the registry.
In addition to the already excellent answers, also consider this function to retrieve both the number of dimensions and their bounds, which is similar to John's answer, but works and looks a little differently:
Function sizeOfArray(arr As Variant) As String
Dim str As String
Dim numDim As Integer
numDim = NumberOfArrayDimensions(arr)
str = "Array"
For i = 1 To numDim
str = str & "(" & LBound(arr, i) & " To " & UBound(arr, i)
If Not i = numDim Then
str = str & ", "
Else
str = str & ")"
End If
Next i
sizeOfArray = str
End Function
Private Function NumberOfArrayDimensions(arr As Variant) As Integer
' By Chip Pearson
' http://www.cpearson.com/excel/vbaarrays.htm
Dim Ndx As Integer
Dim Res As Integer
On Error Resume Next
' Loop, increasing the dimension index Ndx, until an error occurs.
' An error will occur when Ndx exceeds the number of dimension
' in the array. Return Ndx - 1.
Do
Ndx = Ndx + 1
Res = UBound(arr, Ndx)
Loop Until Err.Number <> 0
NumberOfArrayDimensions = Ndx - 1
End Function
Example usage:
Sub arrSizeTester()
Dim arr(1 To 2, 3 To 22, 2 To 9, 12 To 18) As Variant
Debug.Print sizeOfArray(arr())
End Sub
And its output:
Array(1 To 2, 3 To 22, 2 To 9, 12 To 18)
Try moving ValueDate
:
select sum(CASE
WHEN ValueDate > @startMonthDate THEN cash
ELSE 0
END)
from Table a
where a.branch = p.branch
and a.transID = p.transID
(reformatted for clarity)
You might also consider using '0' instead of NULL, as you are doing a sum. It works correctly both ways, but is maybe more indicitive of what your intentions are.
If you are looking for this:
Here is the link:
http://css-tricks.com/overriding-the-default-text-selection-color-with-css/
Install the BaseX database, then use it's "standalone command-line mode" like this:
basex -i - //element@attribute < filename.xml
or
basex -i filename.xml //element@attribute
The query language is actually XQuery (3.0), not XPath, but since XQuery is a superset of XPath, you can use XPath queries without ever noticing.
AS from the above discussion
[ng-cloak] {
display: none;
}
is the perfect way to solve the Problem.
Single quotes are for a single character. Double quotes are for a string (array of characters). You can use single quotes to build up a string one character at a time, if you like.
char myChar = 'A';
char myString[] = "Hello Mum";
char myOtherString[] = { 'H','e','l','l','o','\0' };
If you are using numpy you can use np.argsort
to get the sorted indices and apply those indices to the list. This works for any number of list that you would want to sort.
import numpy as np
arr1 = np.array([4,3,1,32,21])
arr2 = arr1 * 10
sorted_idxs = np.argsort(arr1)
print(sorted_idxs)
>>> array([2, 1, 0, 4, 3])
print(arr1[sorted_idxs])
>>> array([ 1, 3, 4, 21, 32])
print(arr2[sorted_idxs])
>>> array([ 10, 30, 40, 210, 320])
It depends on what you need the value for. You (and everyone else so far) omitted the third alternative:
static const int var = 5;
#define var 5
enum { var = 5 };
Ignoring issues about the choice of name, then:
So, in most contexts, prefer the 'enum' over the alternatives. Otherwise, the first and last bullet points are likely to be the controlling factors — and you have to think harder if you need to satisfy both at once.
If you were asking about C++, then you'd use option (1) — the static const — every time.
Well, its an easy way of doing some registry changes: I tried this on 2008 r2 and 2016 servers.
Things need to be done:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown]
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0]
"GPO-ID"="LocalGPO"
"SOM-ID"="Local"
"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"
"DisplayName"="Local Group Policy"
"GPOName"="Local Group Policy"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown\0\0]
"Script"="terminate_script.bat"
"Parameters"=""
"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0]
"GPO-ID"="LocalGPO"
"SOM-ID"="Local"
"FileSysPath"="C:\\Windows\\System32\\GroupPolicy\\Machine"
"DisplayName"="Local Group Policy"
"GPOName"="Local Group Policy"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown\0\0]
"Script"="terminate_script.bat"
"Parameters"=""
"IsPowershell"=dword:00000000
"ExecTime"=hex(b):00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00
Save this file as regedit.reg extension
Run it on any command line using below command:
regedit.exe /s regedit.reg
This will probably fix your problem if you're struggling to deploy a React solution that was created with the Visual Studio template (and has a web.config). In Azure Release Pipelines, when selecting the template, use:
Azure App Service deployment
Instead of:
Deploy a Node.js app to Azure App Service
It worked for me!
To avoid this error, you should use javac command with .java extension.
Javac DescendingOrder.java <- this work perfectly.
You can run the tool from Microsoft in this KB http://support.microsoft.com/default.aspx?scid=kb;en-us;Q195353 to fix the licensing issues for earlier ActiveX controls. This worked for me.
Getting only the instance attributes is easy.
But getting also the class attributes without the functions is a bit more tricky.
If you only have to list instance attributes just use
for attribute, value in my_instance
.__dict__
.items()
>>> from __future__ import (absolute_import, division, print_function)
>>> class MyClass(object):
... def __init__(self):
... self.a = 2
... self.b = 3
... def print_instance_attributes(self):
... for attribute, value in self.__dict__.items():
... print(attribute, '=', value)
...
>>> my_instance = MyClass()
>>> my_instance.print_instance_attributes()
a = 2
b = 3
>>> for attribute, value in my_instance.__dict__.items():
... print(attribute, '=', value)
...
a = 2
b = 3
To get also the class attributes without the functions, the trick is to use callable()
.
But static methods are not always callable
!
Therefore, instead of using callable(value)
use
callable
(getattr
(MyClass, attribute))
from __future__ import (absolute_import, division, print_function)
class MyClass(object):
a = "12"
b = "34" # class attributes
def __init__(self, c, d):
self.c = c
self.d = d # instance attributes
@staticmethod
def mystatic(): # static method
return MyClass.b
def myfunc(self): # non-static method
return self.a
def print_instance_attributes(self):
print('[instance attributes]')
for attribute, value in self.__dict__.items():
print(attribute, '=', value)
def print_class_attributes(self):
print('[class attributes]')
for attribute in self.__dict__.keys():
if attribute[:2] != '__':
value = getattr(self, attribute)
if not callable(value):
print(attribute, '=', value)
v = MyClass(4,2)
v.print_class_attributes()
v.print_instance_attributes()
Note: print_class_attributes()
should be @staticmethod
but not in this stupid and simple example.
$ python2 ./print_attributes.py
[class attributes]
a = 12
b = 34
[instance attributes]
c = 4
d = 2
$ python3 ./print_attributes.py
[class attributes]
b = 34
a = 12
[instance attributes]
c = 4
d = 2
You can get MinGW (as others have suggested) but I would recommend getting a simple IDE (not VS Express). You can try Dev C++ http://www.bloodshed.net/devcpp.html Its a simple IDE for C/C++ and uses MinGW internally. In this you can write and compile single C files without creating a full-blown "project".
In regards to problems with Qt4, I couldn't use the qmake moc option mentioned above. But that wasn't the problem anyway. I had the following code in the class definition:
class ScreenWidget : public QGLWidget
{
Q_OBJECT // must include this if you use Qt signals/slots
...
};
I had to remove the line "Q_OBJECT" because I had no signals or slots defined.
Here is a Swift 3 adaptation of Paul Hegarty's solution from rdprado's answer, with some checking for optionals added to it (returning 0.0 if any part of the process fails):
var wageFloat:Float = 0.0
if let wageText = wage.text {
if let wageNumber = NumberFormatter().number(from: wageText) {
wageFloat = wageNumber.floatValue
}
}
By the way, I took Stanford's CS193p class using iTunes University when it was still teaching Objective-C.
I found Paul Hegarty to be a FANTASTIC instructor, and I would highly recommend the class to anyone starting out as an iOS developer in Swift!!!
I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.
Also, the project is mostly dormant... the last release was in 2004.
For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.
Initially I had downgraded buildToolsVersion
from 24.0.0 rc3
to 23.0.3
, as specified in Rudy Kurniawan's answer. Then I have noticed that I have jdk 7 specified in my project settings. I have changed it to jdk 8 and now build tools 24.0.0 rc3
work.
It's also important to have compile options set to java7
:
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
Mockito has limitations testing final, static, and private methods.
with jMockit testing library, you can do few stuff very easy and straight-forward as below:
Mock constructor of a java.io.File class:
new MockUp<File>(){
@Mock
public void $init(String pathname){
System.out.println(pathname);
// or do whatever you want
}
};
Mock a static method: