You can add the src
folder to build path by:
- Select Java perspective.
- Right click on
src
folder. - Select Build Path > Use a source folder.
And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
None of the solutions proposed worked fine for me, and after a couple of hours I finally found the way.
This is the angular directive:
angular.module('app').directive('restrictTo', function() {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var re = RegExp(attrs.restrictTo);
var exclude = /Backspace|Enter|Tab|Delete|Del|ArrowUp|Up|ArrowDown|Down|ArrowLeft|Left|ArrowRight|Right/;
element[0].addEventListener('keydown', function(event) {
if (!exclude.test(event.key) && !re.test(event.key)) {
event.preventDefault();
}
});
}
}
});
And the input would look like:
<input type="number" min="0" name="inputName" ng-model="myModel" restrict-to="[0-9]">
The regular expression evaluates the pressed key, not the value.
It also works perfectly with inputs type="number"
because prevents from changing its value, so the key is never displayed and it does not mess with the model.
<Button Background="#FF4148" BorderThickness="0" BorderBrush="Transparent">
<Border HorizontalAlignment="Right" BorderBrush="#FF6A6A" BorderThickness="0>
<Border.Style>
<Style TargetType="Border">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#FF6A6A" />
</Trigger>
</Style.Triggers>
</Style>
</Border.Style>
<StackPanel Orientation="Horizontal">
<Image RenderOptions.BitmapScalingMode="HighQuality" Source="//ImageName.png" />
</StackPanel>
</Border>
</Button>
SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.
You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...
From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.
If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/
@thebjorn has given a good answer. But if you want more options, you can try OpenCV, SimpleCV.
using SimpleCV (not supported in python3.x):
from SimpleCV import Image, Camera
cam = Camera()
img = cam.getImage()
img.save("filename.jpg")
using OpenCV:
from cv2 import *
# initialize the camera
cam = VideoCapture(0) # 0 -> index of camera
s, img = cam.read()
if s: # frame captured without any errors
namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
imshow("cam-test",img)
waitKey(0)
destroyWindow("cam-test")
imwrite("filename.jpg",img) #save image
using pygame:
import pygame
import pygame.camera
pygame.camera.init()
pygame.camera.list_cameras() #Camera detected or not
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")
Install OpenCV:
install python-opencv bindings, numpy
Install SimpleCV:
install python-opencv, pygame, numpy, scipy, simplecv
get latest version of SimpleCV
Install pygame:
install pygame
For Intellij Idea sometime localhost.log file generated at different location. For e.g. you can find it at homedirectory\ .IntelliJIdea14\system\tomcat.
IF you are using spring then start ur server in debug mode and put debug point in catch block of org.springframework.context.support.AbstractApplicationContext's refresh() method. If bean creation fails you would be able to see the exception.
Generally, there are two ways to list out installed packages - through the Command Line Interface (CLI) or in your application using the API.
Both commands will print to stdout
all the versions of packages that are installed, as well as their dependencies, in a tree-structure.
npm list
Use the -g
(global) flag to list out all globally-installed packages. Use the --depth=0
flag to list out only the top packages and not their dependencies.
In your case, you want to run this within your script, so you'd need to use the API. From the docs:
npm.commands.ls(args, [silent,] callback)
In addition to printing to stdout
, the data will also be passed into the callback.
Hey I was also facing similar problem, in an ajax generated page.. I took generated source using Webdeveloper pluggin in FF, and checked all the inputs in the form and found out that there was another checkbox inside a hidden div(display:none) with same ID, Once I changed the id of second checkbox, it started working.. You can also try that.. and let me know the result.. cheers
To return to your Activity
, you will need to listen to TelephonyStates
. On that listener
you can send an Intent
to re-open your Activity
once the phone is idle.
At least thats how I will do it.
I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.
What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;
If you do go down the inline-block route then you may have to consider my favorite IE hack.
width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only
Happy Coding :)
Given this test file (test.txt)
Lorem ipsum dolor sit amet,
consectetur adipiscing elit.
Duis eu diam non tortor laoreet
bibendum vitae et tellus.
the following command will replace the first line to "newline text"
$ sed '1 c\
> newline text' test.txt
Result:
newline text
consectetur adipiscing elit.
Duis eu diam non tortor laoreet
bibendum vitae et tellus.
more information can be found here
http://www.thegeekstuff.com/2009/11/unix-sed-tutorial-append-insert-replace-and-count-file-lines/
For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess
object, from which you can easily obtain the output as well as return code. Since you are only interested in the output, you can write a utility wrapper like this.
from subprocess import PIPE, run
def out(command):
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
return result.stdout
my_output = out("echo hello world")
# Or
my_output = out(["echo", "hello world"])
Contrary to @Andre Luus, setting Height="Auto"
will not make the TextBox
stretch. The solution I found was to set VerticalAlignment="Stretch"
I was just looking for a smiliar issue and I found this:
.div{
height : 100vh;
}
more info
vw: 1/100th viewport width
vh: 1/100th viewport height
vmin: 1/100th of the smallest side
vmax: 1/100th of the largest side
You can add the src
folder to build path by:
src
folder.And you are done. Hope this help.
EDIT: Refer to the Eclipse documentation
The sqlite team published an article explaining when to use sqlite that is great read. Basically, you want to avoid using sqlite when you have a lot of write concurrency or need to scale to terabytes of data. In many other cases, sqlite is a surprisingly good alternative to a "traditional" database such as MySQL.
>>> import tensorflow as tf
>>> tf.config.list_physical_devices('GPU')
2020-05-10 14:58:16.243814: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcuda.so.1
2020-05-10 14:58:16.262675: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-05-10 14:58:16.263119: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1555] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1060 6GB computeCapability: 6.1
coreClock: 1.7715GHz coreCount: 10 deviceMemorySize: 5.93GiB deviceMemoryBandwidth: 178.99GiB/s
2020-05-10 14:58:16.263143: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudart.so.10.1
2020-05-10 14:58:16.263188: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcublas.so.10
2020-05-10 14:58:16.264289: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcufft.so.10
2020-05-10 14:58:16.264495: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcurand.so.10
2020-05-10 14:58:16.265644: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusolver.so.10
2020-05-10 14:58:16.266329: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcusparse.so.10
2020-05-10 14:58:16.266357: I tensorflow/stream_executor/platform/default/dso_loader.cc:44] Successfully opened dynamic library libcudnn.so.7
2020-05-10 14:58:16.266478: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-05-10 14:58:16.266823: I tensorflow/stream_executor/cuda/cuda_gpu_executor.cc:981] successful NUMA node read from SysFS had negative value (-1), but there must be at least one NUMA node, so returning NUMA node zero
2020-05-10 14:58:16.267107: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1697] Adding visible gpu devices: 0
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
As suggested by @AmitaiIrron:
This section indicates that a gpu was found
2020-05-10 14:58:16.263119: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1555] Found device 0 with properties:
pciBusID: 0000:01:00.0 name: GeForce GTX 1060 6GB computeCapability: 6.1
coreClock: 1.7715GHz coreCount: 10 deviceMemorySize: 5.93GiB deviceMemoryBandwidth: 178.99GiB/s
And here that it got added as an available physical device
2020-05-10 14:58:16.267107: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1697] Adding visible gpu devices: 0
[PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]
I think the problem is that you load
isfar
data.frame but you overwrite it by value returned by load
.
Try either:
load("C:/Users/isfar.RData")
head(isfar)
Or more general way
load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex)
If you are only trying to change the include paths for a project and not for all solutions then in Visual Studio 2008 do this: Right-click on the name of the project in the Solution Navigator. From the popup menu select Properties. In the property pages dialog select Configuration Properties->C/C++/General. Click in the text box next to the "Additional Include Files" label and browse for the appropriate directory. Select OK.
What annoys me is that some of the answers to the original question asked do not apply to the version of Visual Studio that was mentioned.
shuffle the pandas data frame by taking a sample array in this case index and randomize its order then set the array as an index of data frame. Now sort the data frame according to index. Here goes your shuffled dataframe
import random
df = pd.DataFrame({"a":[1,2,3,4],"b":[5,6,7,8]})
index = [i for i in range(df.shape[0])]
random.shuffle(index)
df.set_index([index]).sort_index()
output
a b
0 2 6
1 1 5
2 3 7
3 4 8
Insert you data frame in the place of mine in above code .
Python really tries hard to intelligently set sys.path
. How it is
set can get really complicated. The following guide is a watered-down,
somewhat-incomplete, somewhat-wrong, but hopefully-useful guide
for the rank-and-file python programmer of what happens when python
figures out what to use as the initial values of sys.path
,
sys.executable
, sys.exec_prefix
, and sys.prefix
on a normal
python installation.
First, python does its level best to figure out its actual physical
location on the filesystem based on what the operating system tells
it. If the OS just says "python" is running, it finds itself in $PATH.
It resolves any symbolic links. Once it has done this, the path of
the executable that it finds is used as the value for sys.executable
, no ifs,
ands, or buts.
Next, it determines the initial values for sys.exec_prefix
and
sys.prefix
.
If there is a file called pyvenv.cfg
in the same directory as
sys.executable
or one directory up, python looks at it. Different
OSes do different things with this file.
One of the values in this config file that python looks for is
the configuration option home = <DIRECTORY>
. Python will use this directory instead of the directory containing sys.executable
when it dynamically sets the initial value of sys.prefix
later. If the applocal = true
setting appears in the
pyvenv.cfg
file on Windows, but not the home = <DIRECTORY>
setting,
then sys.prefix
will be set to the directory containing sys.executable
.
Next, the PYTHONHOME
environment variable is examined. On Linux and Mac,
sys.prefix
and sys.exec_prefix
are set to the PYTHONHOME
environment variable, if
it exists, superseding any home = <DIRECTORY>
setting in pyvenv.cfg
. On Windows,
sys.prefix
and sys.exec_prefix
is set to the PYTHONHOME
environment variable,
if it exists, unless a home = <DIRECTORY>
setting is present in pyvenv.cfg
,
which is used instead.
Otherwise, these sys.prefix
and sys.exec_prefix
are found by walking backwards
from the location of sys.executable
, or the home
directory given by pyvenv.cfg
if any.
If the file lib/python<version>/dyn-load
is found in that directory
or any of its parent directories, that directory is set to be to be
sys.exec_prefix
on Linux or Mac. If the file
lib/python<version>/os.py
is is found in the directory or any of its
subdirectories, that directory is set to be sys.prefix
on Linux,
Mac, and Windows, with sys.exec_prefix
set to the same value as
sys.prefix
on Windows. This entire step is skipped on Windows if
applocal = true
is set. Either the directory of sys.executable
is
used or, if home
is set in pyvenv.cfg
, that is used instead for
the initial value of sys.prefix
.
If it can't find these "landmark" files or sys.prefix
hasn't been
found yet, then python sets sys.prefix
to a "fallback"
value. Linux and Mac, for example, use pre-compiled defaults as the
values of sys.prefix
and sys.exec_prefix
. Windows waits
until sys.path
is fully figured out to set a fallback value for
sys.prefix
.
Then, (what you've all been waiting for,) python determines the initial values
that are to be contained in sys.path
.
sys.path
.
On Windows, this is always the empty string, which tells python to
use the full path where the script is located instead.sys.path
, unless you're
on Windows and applocal
is set to true in pyvenv.cfg
.<prefix>/lib/python35.zip
on Linux/Mac and
os.path.join(os.dirname(sys.executable), "python.zip")
on Windows, is added to sys.path
.applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;applocal = true
was set in pyvenv.cfg
, then the contents of the subkeys of the registry key
HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\
are added, if any.applocal = true
was set in pyvenv.cfg
, and sys.prefix
could not be found,
then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\
is added, if it exists;sys.prefix
.sys.exec_prefix
is added. On Windows, the directory
which was used (or would have been used) to search dynamically for sys.prefix
is
added.At this stage on Windows, if no prefix was found, then python will try to
determine it by searching all the directories in sys.path
for the landmark files,
as it tried to do with the directory of sys.executable
previously, until it finds something.
If it doesn't, sys.prefix
is left blank.
Finally, after all this, Python loads the site
module, which adds stuff yet further to sys.path
:
It starts by constructing up to four directories from a head and a tail part. For the head part, it uses
sys.prefix
andsys.exec_prefix
; empty heads are skipped. For the tail part, it uses the empty string and thenlib/site-packages
(on Windows) orlib/pythonX.Y/site-packages
and thenlib/site-python
(on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.
As long as the User does not delete their cookies or close their browser, the session should stay in existence.
The same can be applied to a scenario where the data has been normalized, but now you want a table to have values found in a third table. The following will allow you to update a table with information from a third table that is liked by a second table.
UPDATE t1
LEFT JOIN
t2
ON
t2.some_id = t1.some_id
LEFT JOIN
t3
ON
t2.t3_id = t3.id
SET
t1.new_column = t3.column;
This would be useful in a case where you had users and groups, and you wanted a user to be able to add their own variation of the group name, so originally you would want to import the existing group names into the field where the user is going to be able to modify it.
if you don't like the double brackets or you don't want to write a function, you can just use a variable.
$path = Test-Path C:\Code
if (!$path) {
write "it doesn't exist!"
}
SQL> sqlplus "/ as sysdba"
SQL> startup
Oracle instance started
------
Database mounted.
Database opened.
SQL> Quit
I also got same problem.I tried above mentioned steps and then it worked for me.You can try.
spin12.setLayoutParams(new LinearLayout.LayoutParams(200, 120));
spin12
is your spinner and 200,120 is width
and height
for your spinner
.
There's no easy way to do this, but something like this will work:
SELECT ET.TrainingID,
ET.CompletedDate,
ET.Notes
FROM
HR_EmployeeTrainings ET
inner join
(
select TrainingID, Max(CompletedDate) as CompletedDate
FROM HR_EmployeeTrainings
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
) ET2
on ET.TrainingID = ET2.TrainingID
and ET.CompletedDate = ET2.CompletedDate
package com.programmingfree.springshop.controller;
import java.util.List;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.programmingfree.springshop.dao.UserShop;
import com.programmingfree.springshop.domain.User;
@RestController
@RequestMapping("/shop/user")
public class SpringShopController {
UserShop userShop=new UserShop();
@RequestMapping(value = "/{id}", method = RequestMethod.GET,headers="Accept=application/json")
public User getUser(@PathVariable int id) {
User user=userShop.getUserById(id);
return user;
}
@RequestMapping(method = RequestMethod.GET,headers="Accept=application/json")
public List<User> getAllUsers() {
List<User> users=userShop.getAllUsers();
return users;
}
}
In the above example they going to display all user and particular id details now I want to use both id and name,
1) localhost:8093/plejson/shop/user <---this link will display all user details
2) localhost:8093/plejson/shop/user/11 <----if i use 11 in link means, it will display particular user 11 details
now I want to use both id and name
localhost:8093/plejson/shop/user/11/raju <-----------------like this it means we can use any one in this please help me out.....
I have built an module for this if you want to add styles based on a condition like this:
multipleStyles(styles.icon, { [styles.iconRed]: true })
DisplayFor
is also useful for templating. You could write a template for your Model, and do something like this:
@Html.DisplayFor(m => m)
Similar to @Html.EditorFor(m => m)
. It's useful for the DRY principal so that you don't have to write the same display logic over and over for the same Model.
Take a look at this blog on MVC2 templates. It's still very applicable to MVC3:
http://www.dalsoft.co.uk/blog/index.php/2010/04/26/mvc-2-templates/
It's also useful if your Model has a Data annotation. For instance, if the property on the model is decorated with the EmailAddress
data annotation, DisplayFor
will render it as a mailto:
link.
You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.
The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,
var students = $http.get(path).then(function (resp) {
return resp.data;
}); // then() returns a promise object, not resp.data
There's a simple way to get around this and it's to supply a callback function.
.service('StudentService', [ '$http',
function ($http) {
// get some data via the $http
var path = '/students';
//save method create a new student if not already exists
//else update the existing object
this.save = function (student, doneCallback) {
$http.post(
path,
{
params: {
student: student
}
}
)
.then(function (resp) {
doneCallback(resp.data); // when the async http call is done, execute the callback
});
}
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
$scope.saveUser = function (user) {
StudentService.save(user, function (data) {
$scope.message = data; // I'm assuming data is a string error returned from your REST API
})
}
}]);
The form:
<div class="form-message">{{message}}</div>
<div ng-controller="StudentSaveController">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="saveUser(user)" value="Save" />
</form>
</div>
This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.
You shold use the keys()
or names()
method. keys()
will give you an iterator containing all the String property names in the object while names()
will give you an array of all key String names.
You can get the JSONObject documentation here
http://developer.android.com/reference/org/json/JSONObject.html
class SelfFocusingInput extends React.Component<{ value: string, onChange: (value: string) => any }, {}>{
ctrls: {
input?: HTMLInputElement;
} = {};
render() {
return (
<input
ref={(input) => this.ctrls.input = input}
value={this.props.value}
onChange={(e) => { this.props.onChange(this.ctrls.input.value) } }
/>
);
}
componentDidMount() {
this.ctrls.input.focus();
}
}
put them in an object
dt
accessorA common source of confusion revolves around when to use .year
and when to use .dt.year
.
The former is an attribute for pd.DatetimeIndex
objects; the latter for pd.Series
objects. Consider this dataframe:
df = pd.DataFrame({'Dates': pd.to_datetime(['2018-01-01', '2018-10-20', '2018-12-25'])},
index=pd.to_datetime(['2000-01-01', '2000-01-02', '2000-01-03']))
The definition of the series and index look similar, but the pd.DataFrame
constructor converts them to different types:
type(df.index) # pandas.tseries.index.DatetimeIndex
type(df['Dates']) # pandas.core.series.Series
The DatetimeIndex
object has a direct year
attribute, while the Series
object must use the dt
accessor. Similarly for month
:
df.index.month # array([1, 1, 1])
df['Dates'].dt.month.values # array([ 1, 10, 12], dtype=int64)
A subtle but important difference worth noting is that df.index.month
gives a NumPy array, while df['Dates'].dt.month
gives a Pandas series. Above, we use pd.Series.values
to extract the NumPy array representation.
You can use this syntax but it will require some changes in the SVG file. And remove any fill/stroke from the SVG itself.
icon.svg
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1">
<!-- use symbol instead of defs and g,
must add viewBox on symbol just copy yhe viewbox from the svg tag itself
must add id on symbol
-->
<symbol id="location" viewBox="0 0 430.114 430.114">
<!-- add all the icon's paths and shapes here -->
<path d="M356.208,107.051c-1.531-5.738-4.64-11.852-6.94-17.205C321.746,23.704,261.611,0,213.055,0 C148.054,0,76.463,43.586,66.905,133.427v18.355c0,0.766,0.264,7.647,0.639,11.089c5.358,42.816,39.143,88.32,64.375,131.136 c27.146,45.873,55.314,90.999,83.221,136.106c17.208-29.436,34.354-59.259,51.17-87.933c4.583-8.415,9.903-16.825,14.491-24.857 c3.058-5.348,8.9-10.696,11.569-15.672c27.145-49.699,70.838-99.782,70.838-149.104v-20.262 C363.209,126.938,356.581,108.204,356.208,107.051z M214.245,199.193c-19.107,0-40.021-9.554-50.344-35.939 c-1.538-4.2-1.414-12.617-1.414-13.388v-11.852c0-33.636,28.56-48.932,53.406-48.932c30.588,0,54.245,24.472,54.245,55.06 C270.138,174.729,244.833,199.193,214.245,199.193z"/>
</symbol>
icon.html
<svg><use xlink:href="file_path/location.svg#location"></use></svg>
For anyone using EF5, following extension library can be used: https://github.com/loresoft/EntityFramework.Extended
context.Widgets.Delete(w => w.WidgetId == widgetId);
If you use form.close() in your form and set the FormClosing Event of your form and either use form.close() in this Event ,you fall in unlimited loop and Argument out of range happened and the solution is that change the form.close() with form.dispose() in Event of FormClosing. I hope this little tip help you!!!
the one liner for python3 is :
def bytes_xor(a, b) :
return bytes(x ^ y for x, y in zip(a, b))
where a
, b
and the returned value are bytes()
instead of str()
of course
can't be easier, I love python3 :)
You can try this instead
var myu = document.getElementById('myu').value;
var myp = document.getElementById('myp').value;
window.opener.location.href='myurl.php?myu='+ myu +'&myp='+ myp;
Note: Do not use this method to pass sensitive information like username, password.
The ideas posted above are good, but a very simple and easy way to invalidate all the existing JWTs is simply to change the secret.
If your server creates the JWT, signs it with a secret (JWS) then sends it to the client, simply changing the secret will invalidating all existing tokens and require all users to gain a new token to authenticate as their old token suddenly becomes invalid according to the server.
It doesn't require any modifications to the actual token contents (or lookup ID).
Clearly this only works for an emergency case when you wanted all existing tokens to expire, for per token expiry one of the solutions above is required (such as short token expiry time or invalidating a stored key inside the token).
you can make a function like this
function translateTo($language, $word) {
define('defaultLang','english');
if (isset($lang[$language][$word]) == FALSE)
return $lang[$language][$word];
else
return $lang[defaultLang][$word];
}
ES5 solution can be:
// for enumerable and non-enumerable properties
Object.getOwnPropertyNames(obj).forEach(function (prop) {
delete obj[prop];
});
And ES6 solution can be:
// for enumerable and non-enumerable properties
for (const prop of Object.getOwnPropertyNames(obj)) {
delete obj[prop];
}
Regardless of the specs, the quickest solutions will generally be:
// for enumerable and non-enumerable of an object with proto chain
var props = Object.getOwnPropertyNames(obj);
for (var i = 0; i < props.length; i++) {
delete obj[props[i]];
}
// for enumerable properties of shallow/plain object
for (var key in obj) {
// this check can be safely omitted in modern JS engines
// if (obj.hasOwnProperty(key))
delete obj[key];
}
The reason why for..in
should be performed only on shallow or plain object is that it traverses the properties that are prototypically inherited, not just own properties that can be deleted. In case it isn't known for sure that an object is plain and properties are enumerable, for
with Object.getOwnPropertyNames
is a better choice.
Patching as well Ralph Bolton's answer. Moving to a class and moving tulp of tulp (intervals) to dictionary. Adding an optional rounded function depending of granularity (enable by default). Ready to translation using gettext (default is disable). This is intend to be load from an module. This is for python3 (tested 3.6 - 3.8)
import gettext
import locale
from itertools import chain
mylocale = locale.getdefaultlocale()
# see --> https://stackoverflow.com/a/10174657/11869956 thx
#localedir = os.path.join(os.path.dirname(__file__), 'locales')
# or python > 3.4:
try:
localedir = pathlib.Path(__file__).parent/'locales'
lang_translations = gettext.translation('utils', localedir,
languages=[mylocale[0]])
lang_translations.install()
_ = lang_translations.gettext
except Exception as exc:
print('Error: unexcept error while initializing translation:', file=sys.stderr)
print(f'Error: {exc}', file=sys.stderr)
print(f'Error: localedir={localedir}, languages={mylocale[0]}', file=sys.stderr)
print('Error: translation has been disabled.', file=sys.stderr)
_ = gettext.gettext
Here is the class:
class FormatTimestamp:
"""Convert seconds to, optional rounded, time depending of granularity's degrees.
inspired by https://stackoverflow.com/a/24542445/11869956"""
def __init__(self):
# For now i haven't found a way to do it better
# TODO: optimize ?!? ;)
self.intervals = {
# 'years' : 31556952, # https://www.calculateme.com/time/years/to-seconds/
# https://www.calculateme.com/time/months/to-seconds/ -> 2629746 seconds
# But it's outputing some strange result :
# So 3 seconds less (2629743) : 4 weeks, 2 days, 10 hours, 29 minutes and 3 seconds
# than after 3 more seconds : 1 month ?!?
# Google give me 2628000 seconds
# So 3 seconds less (2627997): 4 weeks, 2 days, 9 hours, 59 minutes and 57 seconds
# Strange as well
# So for the moment latest is week ...
#'months' : 2419200, # 60 * 60 * 24 * 7 * 4
'weeks' : 604800, # 60 * 60 * 24 * 7
'days' : 86400, # 60 * 60 * 24
'hours' : 3600, # 60 * 60
'minutes' : 60,
'seconds' : 1
}
self.nextkey = {
'seconds' : 'minutes',
'minutes' : 'hours',
'hours' : 'days',
'days' : 'weeks',
'weeks' : 'weeks',
#'months' : 'months',
#'years' : 'years' # stop here
}
self.translate = {
'weeks' : _('weeks'),
'days' : _('days'),
'hours' : _('hours'),
'minutes' : _('minutes'),
'seconds' : _('seconds'),
## Single
'week' : _('week'),
'day' : _('day'),
'hour' : _('hour'),
'minute' : _('minute'),
'second' : _('second'),
' and' : _('and'),
',' : _(','), # This is for compatibility
'' : '\0' # same here BUT we CANNOT pass empty string to gettext
# or we get : warning: Empty msgid. It is reserved by GNU gettext:
# gettext("") returns the header entry with
# meta information, not the empty string.
# Thx to --> https://stackoverflow.com/a/30852705/11869956 - saved my day
}
def convert(self, seconds, granularity=2, rounded=True, translate=False):
"""Proceed the conversion"""
def _format(result):
"""Return the formatted result
TODO : numpy / google docstrings"""
start = 1
length = len(result)
none = 0
next_item = False
for item in reversed(result[:]):
if item['value']:
# if we have more than one item
if length - none > 1:
# This is the first 'real' item
if start == 1:
item['punctuation'] = ''
next_item = True
elif next_item:
# This is the second 'real' item
# Happened 'and' to key name
item['punctuation'] = ' and'
next_item = False
# If there is more than two 'real' item
# than happened ','
elif 2 < start:
item['punctuation'] = ','
else:
item['punctuation'] = ''
else:
item['punctuation'] = ''
start += 1
else:
none += 1
return [ { 'value' : mydict['value'],
'name' : mydict['name_strip'],
'punctuation' : mydict['punctuation'] } for mydict in result \
if mydict['value'] is not None ]
def _rstrip(value, name):
"""Rstrip 's' name depending of value"""
if value == 1:
name = name.rstrip('s')
return name
# Make sure granularity is an integer
if not isinstance(granularity, int):
raise ValueError(f'Granularity should be an integer: {granularity}')
# For seconds only don't need to compute
if seconds < 0:
return 'any time now.'
elif seconds < 60:
return 'less than a minute.'
result = []
for name, count in self.intervals.items():
value = seconds // count
if value:
seconds -= value * count
name_strip = _rstrip(value, name)
# save as dict: value, name_strip (eventually strip), name (for reference), value in seconds
# and count (for reference)
result.append({
'value' : value,
'name_strip' : name_strip,
'name' : name,
'seconds' : value * count,
'count' : count
})
else:
if len(result) > 0:
# We strip the name as second == 0
name_strip = name.rstrip('s')
# adding None to key 'value' but keep other value
# in case when need to add seconds when we will
# recompute every thing
result.append({
'value' : None,
'name_strip' : name_strip,
'name' : name,
'seconds' : 0,
'count' : count
})
# Get the length of the list
length = len(result)
# Don't need to compute everything / every time
if length < granularity or not rounded:
if translate:
return ' '.join('{0} {1}{2}'.format(item['value'], _(self.translate[item['name']]),
_(self.translate[item['punctuation']])) \
for item in _format(result))
else:
return ' '.join('{0} {1}{2}'.format(item['value'], item['name'], item['punctuation']) \
for item in _format(result))
start = length - 1
# Reverse list so the firsts elements
# could be not selected depending on granularity.
# And we can delete item after we had his seconds to next
# item in the current list (result)
for item in reversed(result[:]):
if granularity <= start <= length - 1:
# So we have to round
current_index = result.index(item)
next_index = current_index - 1
# skip item value == None
# if the seconds of current item is superior
# to the half seconds of the next item: round
if item['value'] and item['seconds'] > result[next_index]['count'] // 2:
# +1 to the next item (in seconds: depending on item count)
result[next_index]['seconds'] += result[next_index]['count']
# Remove item which is not selected
del result[current_index]
start -= 1
# Ok now recalculate everything
# Reverse as well
for item in reversed(result[:]):
# Check if seconds is superior or equal to the next item
# but not from 'result' list but from 'self.intervals' dict
# Make sure it's not None
if item['value']:
next_item_name = self.nextkey[item['name']]
# This mean we are at weeks
if item['name'] == next_item_name:
# Just recalcul
item['value'] = item['seconds'] // item['count']
item['name_strip'] = _rstrip(item['value'], item['name'])
# Stop to weeks to stay 'right'
elif item['seconds'] >= self.intervals[next_item_name]:
# First make sure we have the 'next item'
# found via --> https://stackoverflow.com/q/26447309/11869956
# maybe there is a faster way to do it ? - TODO
if any(search_item['name'] == next_item_name for search_item in result):
next_item_index = result.index(item) - 1
# Append to
result[next_item_index]['seconds'] += item['seconds']
# recalculate value
result[next_item_index]['value'] = result[next_item_index]['seconds'] // \
result[next_item_index]['count']
# strip or not
result[next_item_index]['name_strip'] = _rstrip(result[next_item_index]['value'],
result[next_item_index]['name'])
else:
# Creating
next_item_index = result.index(item) - 1
# get count
next_item_count = self.intervals[next_item_name]
# convert seconds
next_item_value = item['seconds'] // next_item_count
# strip 's' or not
next_item_name_strip = _rstrip(next_item_value, next_item_name)
# added to dict
next_item = {
'value' : next_item_value,
'name_strip' : next_item_name_strip,
'name' : next_item_name,
'seconds' : item['seconds'],
'count' : next_item_count
}
# insert to the list
result.insert(next_item_index, next_item)
# Remove current item
del result[result.index(item)]
else:
# for current item recalculate
# keys 'value' and 'name_strip'
item['value'] = item['seconds'] // item['count']
item['name_strip'] = _rstrip(item['value'], item['name'])
if translate:
return ' '.join('{0} {1}{2}'.format(item['value'],
_(self.translate[item['name']]),
_(self.translate[item['punctuation']])) \
for item in _format(result))
else:
return ' '.join('{0} {1}{2}'.format(item['value'], item['name'], item['punctuation']) \
for item in _format(result))
To use it:
myformater = FormatTimestamp()
myconverter = myformater.convert(seconds)
granularity = 1 - 5, rounded = True / False, translate = True / False
Some test to show difference:
myformater = FormatTimestamp()
for firstrange in [131440, 563440, 604780, 2419180, 113478160]:
print(f'#### Seconds : {firstrange} ####')
print('\tFull - function: {0}'.format(display_time(firstrange, granularity=5)))
print('\tFull - class: {0}'.format(myformater.convert(firstrange, granularity=5)))
for secondrange in range(1, 6, 1):
print('\tGranularity this answer ({0}): {1}'.format(secondrange,
myformater.convert(firstrange,
granularity=secondrange, translate=False)))
print('\tGranularity Bolton\'s answer ({0}): {1}'.format(secondrange, display_time(firstrange,
granularity=secondrange)))
print()
Seconds : 131440Seconds : 563440Full - function: 1 day, 12 hours, 30 minutes, 40 seconds Full - class: 1 day, 12 hours, 30 minutes and 40 seconds Granularity this answer (1): 2 days Granularity Bolton's answer (1): 1 day Granularity this answer (2): 1 day and 13 hours Granularity Bolton's answer (2): 1 day, 12 hours Granularity this answer (3): 1 day, 12 hours and 31 minutes Granularity Bolton's answer (3): 1 day, 12 hours, 30 minutes Granularity this answer (4): 1 day, 12 hours, 30 minutes and 40 seconds Granularity Bolton's answer (4): 1 day, 12 hours, 30 minutes, 40 seconds Granularity this answer (5): 1 day, 12 hours, 30 minutes and 40 seconds Granularity Bolton's answer (5): 1 day, 12 hours, 30 minutes, 40 seconds
Full - function: 6 days, 12 hours, 30 minutes, 40 seconds
Full - class: 6 days, 12 hours, 30 minutes and 40 seconds
Granularity this answer (1): 1 week
Granularity Bolton's answer (1): 6 days
Granularity this answer (2): 6 days and 13 hours
Granularity Bolton's answer (2): 6 days, 12 hours
Granularity this answer (3): 6 days, 12 hours and 31 minutes
Granularity Bolton's answer (3): 6 days, 12 hours, 30 minutes
Granularity this answer (4): 6 days, 12 hours, 30 minutes and 40 seconds
Granularity Bolton's answer (4): 6 days, 12 hours, 30 minutes, 40 seconds
Granularity this answer (5): 6 days, 12 hours, 30 minutes and 40 seconds
Granularity Bolton's answer (5): 6 days, 12 hours, 30 minutes, 40 seconds
Seconds : 604780
Full - function: 6 days, 23 hours, 59 minutes, 40 seconds
Full - class: 6 days, 23 hours, 59 minutes and 40 seconds
Granularity this answer (1): 1 week
Granularity Bolton's answer (1): 6 days
Granularity this answer (2): 1 week
Granularity Bolton's answer (2): 6 days, 23 hours
Granularity this answer (3): 1 week
Granularity Bolton's answer (3): 6 days, 23 hours, 59 minutes
Granularity this answer (4): 6 days, 23 hours, 59 minutes and 40 seconds
Granularity Bolton's answer (4): 6 days, 23 hours, 59 minutes, 40 seconds
Granularity this answer (5): 6 days, 23 hours, 59 minutes and 40 seconds
Granularity Bolton's answer (5): 6 days, 23 hours, 59 minutes, 40 seconds
Seconds : 2419180
Full - function: 3 weeks, 6 days, 23 hours, 59 minutes, 40 seconds
Full - class: 3 weeks, 6 days, 23 hours, 59 minutes and 40 seconds
Granularity this answer (1): 4 weeks
Granularity Bolton's answer (1): 3 weeks
Granularity this answer (2): 4 weeks
Granularity Bolton's answer (2): 3 weeks, 6 days
Granularity this answer (3): 4 weeks
Granularity Bolton's answer (3): 3 weeks, 6 days, 23 hours
Granularity this answer (4): 4 weeks
Granularity Bolton's answer (4): 3 weeks, 6 days, 23 hours, 59 minutes
Granularity this answer (5): 3 weeks, 6 days, 23 hours, 59 minutes and 40 seconds
Granularity Bolton's answer (5): 3 weeks, 6 days, 23 hours, 59 minutes, 40 seconds
Seconds : 113478160
Full - function: 187 weeks, 4 days, 9 hours, 42 minutes, 40 seconds
Full - class: 187 weeks, 4 days, 9 hours, 42 minutes and 40 seconds
Granularity this answer (1): 188 weeks
Granularity Bolton's answer (1): 187 weeks
Granularity this answer (2): 187 weeks and 4 days
Granularity Bolton's answer (2): 187 weeks, 4 days
Granularity this answer (3): 187 weeks, 4 days and 10 hours
Granularity Bolton's answer (3): 187 weeks, 4 days, 9 hours
Granularity this answer (4): 187 weeks, 4 days, 9 hours and 43 minutes
Granularity Bolton's answer (4): 187 weeks, 4 days, 9 hours, 42 minutes
Granularity this answer (5): 187 weeks, 4 days, 9 hours, 42 minutes and 40 seconds
Granularity Bolton's answer (5): 187 weeks, 4 days, 9 hours, 42 minutes, 40 seconds
I have a french translation ready. But it's fast to do the translation ... just few words. Hope this could help as the other answer help me a lot.
If you call a new window UI statement in an existing thread, it throws an error. Instead of that create a new thread inside the main thread and write the window UI statement in the new child thread.
In /etc/subversion/servers
you are setting http-proxy-host
, which has nothing to do with svn://
which connects to a different server usually running on port 3690 started by svnserve
command.
If you have access to the server, you can setup svn+ssh://
as explained here.
Update: You could also try using connect-tunnel
, which uses your HTTPS proxy server to tunnel connections:
connect-tunnel -P proxy.company.com:8080 -T 10234:svn.example.com:3690
Then you would use
svn checkout svn://localhost:10234/path/to/trunk
My app uses a ListView in portraint mode which is simply switches to Gallery in landscape mode. Both of them use one BaseAdapter. This looks like shown below.
setContentView(R.layout.somelayout);
orientation = getResources().getConfiguration().orientation;
if ( orientation == Configuration.ORIENTATION_LANDSCAPE )
{
Gallery gallery = (Gallery)findViewById( R.id.somegallery );
gallery.setAdapter( someAdapter );
gallery.setOnItemClickListener( new OnItemClickListener() {
@Override
public void onItemClick( AdapterView<?> parent, View view,
int position, long id ) {
onClick( position );
}
});
}
else
{
setListAdapter( someAdapter );
getListView().setOnScrollListener(this);
}
To handle scrolling events I've inherited my own widget from Gallery and override onFling(). Here's the layout.xml:
<view
class="package$somegallery"
android:id="@+id/somegallery"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</view>
and code:
public static class somegallery extends Gallery
{
private Context mCtx;
public somegallery(Context context, AttributeSet attrs)
{
super(context, attrs);
mCtx = context;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
( (CurrentActivity)mCtx ).onScroll();
return super.onFling(e1, e2, velocityX, velocityY);
}
}
I couldn't quite get there in my use case from the examples above, but Ahmad got me the closest (thank you). For those reading this in the future, here is the code that worked for me.
def get_class(fully_qualified_path, module_name, class_name, *instantiation):
"""
Returns an instantiated class for the given string descriptors
:param fully_qualified_path: The path to the module eg("Utilities.Printer")
:param module_name: The module name eg("Printer")
:param class_name: The class name eg("ScreenPrinter")
:param instantiation: Any fields required to instantiate the class
:return: An instance of the class
"""
p = __import__(fully_qualified_path)
m = getattr(p, module_name)
c = getattr(m, class_name)
instance = c(*instantiation)
return instance
Use index notation with the key.
Object.keys(obj).forEach(function(k){
console.log(k + ' - ' + obj[k]);
});
I know Gmail already fix all the problem above, the alt and stuff now.
And this is unrelated to the question but probably someone experiences the same as me.
So my web designer use "image" tag instead of "img", but the symptom was the same. It works on outlook but not Gmail.
It takes me an hour to realize. Sigh, such a waste of time.
So make sure the tag is "img" not "image" as well.
# select columns containing 'spike'
df.filter(like='spike', axis=1)
You can also select by name, regular expression. Refer to: pandas.DataFrame.filter
You can try to do json.loads()
, which will throw a ValueError
if the string you pass can't be decoded as JSON.
In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.
Don't know why it loses the selection in the GotFocus
event.
But one solution is to do the selection on the GotKeyboardFocus
and the GotMouseCapture
events. That way it will always work.
XOR behaves like Austin explained, as an exclusive OR, either A or B but not both and neither yields false.
There are 16 possible logical operators for two inputs since the truth table consists of 4 combinations there are 16 possible ways to arrange two boolean parameters and the corresponding output.
They all have names according to this wikipedia article
Why not make a function to echo, like this:
function fecho($string) {
echo $string;
ob_flush();
}
The best method I've ever come across to update the content size of a UIScrollView
based on its contained subviews:
Objective-C
CGRect contentRect = CGRectZero;
for (UIView *view in self.scrollView.subviews) {
contentRect = CGRectUnion(contentRect, view.frame);
}
self.scrollView.contentSize = contentRect.size;
Swift
let contentRect: CGRect = scrollView.subviews.reduce(into: .zero) { rect, view in
rect = rect.union(view.frame)
}
scrollView.contentSize = contentRect.size
Working code from my sources:
HTML WORLD
<select name="select_from" disabled>...</select>
JS WORLD
var from = jQuery('select[name=select_from]');
//add disabled
from.attr('disabled', 'disabled');
//remove it
from.removeAttr("disabled");
In Python it is easier to ask for forgiveness than permission. Don't sweat the nested exception handling.
(Besides, has*
almost always uses exceptions under the cover anyway.)
In terms of the scale of quantities:
If epsilon
is the small fraction of the magnitude of quantity (i.e. relative value) in some certain physical sense and A
and B
types is comparable in the same sense, than I think, that the following is quite correct:
#include <limits>
#include <iomanip>
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <cassert>
template< typename A, typename B >
inline
bool close_enough(A const & a, B const & b,
typename std::common_type< A, B >::type const & epsilon)
{
using std::isless;
assert(isless(0, epsilon)); // epsilon is a part of the whole quantity
assert(isless(epsilon, 1));
using std::abs;
auto const delta = abs(a - b);
auto const x = abs(a);
auto const y = abs(b);
// comparable generally and |a - b| < eps * (|a| + |b|) / 2
return isless(epsilon * y, x) && isless(epsilon * x, y) && isless((delta + delta) / (x + y), epsilon);
}
int main()
{
std::cout << std::boolalpha << close_enough(0.9, 1.0, 0.1) << std::endl;
std::cout << std::boolalpha << close_enough(1.0, 1.1, 0.1) << std::endl;
std::cout << std::boolalpha << close_enough(1.1, 1.2, 0.01) << std::endl;
std::cout << std::boolalpha << close_enough(1.0001, 1.0002, 0.01) << std::endl;
std::cout << std::boolalpha << close_enough(1.0, 0.01, 0.1) << std::endl;
return EXIT_SUCCESS;
}
The following seems to work:
import datetime
print (datetime.datetime.now().strftime("%y"))
The datetime.data object that it wants is on the "left" of the dot rather than the right. You need an instance of the datetime to call the method on, which you get through now()
Since pandas 0.14.1 my suggestion here to have a keyword argument in the value_counts method has been implemented:
import pandas as pd
df = pd.DataFrame({'a':[1,2,np.nan], 'b':[np.nan,1,np.nan]})
for col in df:
print df[col].value_counts(dropna=False)
2 1
1 1
NaN 1
dtype: int64
NaN 2
1 1
dtype: int64
I like the extension method solution..
namespace System
{
public static class StringExtensions
{
public static bool TryParseAsEnum<T>(this string value, out T output) where T : struct
{
T result;
var isEnum = Enum.TryParse(value, out result);
output = isEnum ? result : default(T);
return isEnum;
}
}
}
Here below my implementation with tests.
using static Microsoft.VisualStudio.TestTools.UnitTesting.Assert;
using static System.Console;
private enum Countries
{
NorthAmerica,
Europe,
Rusia,
Brasil,
China,
Asia,
Australia
}
[TestMethod]
public void StringExtensions_On_TryParseAsEnum()
{
var countryName = "Rusia";
Countries country;
var isCountry = countryName.TryParseAsEnum(out country);
WriteLine(country);
IsTrue(isCountry);
AreEqual(Countries.Rusia, country);
countryName = "Don't exist";
isCountry = countryName.TryParseAsEnum(out country);
WriteLine(country);
IsFalse(isCountry);
AreEqual(Countries.NorthAmerica, country); // the 1rst one in the enumeration
}
If you are using Visual Studio, there is a GUI solution as well:
If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.
First of all, where you're going wrong is the offset.
It should look more like this...
set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%
If the date was Tue 12/02/2013
then it would display it as 2013/02/12
.
To remove the slashes, the code would look more like
set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%
which would output 20130212
And a hint for doing it in the future, if mydate
equals something like %date:~10,4%%date:~7,2%
or the like, you probably forgot a tilde (~).
I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:
TypeError: 'int' object is not callable
My code for Python 3 is as follows:
# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error
raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54
def intro():
print("Welcome! This program will convert measures for you.")
main()
def main():
print("Select operation.")
print("1.Miles to Kilometers")
print("2.Fahrenheit to Celsius")
print("3.Gallons to liters")
print("4.Pounds to kilograms")
print("5.Inches to centimeters")
choice = input("Enter your choice by number: ")
if choice == '1':
convertMK()
elif choice == '2':
converCF()
elif choice == '3':
convertGL()
elif choice == '4':
convertPK()
elif choice == '5':
convertPK()
else:
print("Error")
def convertMK():
input_M = float(input(("Miles: ")))
M_conv = (M) * input_M
print("Kilometers: {M_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def converCF():
input_F = float(input(("Fahrenheit: ")))
F_conv = (input_F - 32) * 5/9
print("Celcius: {F_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print("I didn't quite understand that answer. Terminating.")
main()
def convertGL():
input_G = float(input(("Gallons: ")))
G_conv = input_G * 3.6
print("Centimeters: {G_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def convertIC():
input_cm = float(input(("Inches: ")))
inches_conv = input_cm * 2.54
print("Centimeters: {inches_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
def end():
print("This program will close.")
exit()
intro()
I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.
def convertPK():
input_P = float(input(("Pounds: ")))
P_conv = input_P * 0.45
# Printing error in the line below
print("Centimeters: {P_conv}\n")
restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
if restart == 'y':
main()
elif restart == 'n':
end()
else:
print ("I didn't quite understand that answer. Terminating.")
main()
I hope this helps.
Run the code below - it prints:
Step 0: ello / H
Step 1: llo / e
Step 2: lo / l
Step 3: o / l
Step 3 returns: ol
Step 2 returns: oll
Step 1 returns: olle
Step 0 returns: olleH
Code:
public class Test {
private static int i = 0;
public static void main(String args[]) {
reverse("Hello");
}
public static String reverse(String str) {
int localI = i++;
if ((null == str) || (str.length() <= 1)) {
return str;
}
System.out.println("Step " + localI + ": " + str.substring(1) + " / " + str.charAt(0));
String reversed = reverse(str.substring(1)) + str.charAt(0);
System.out.println("Step " + localI + " returns: " + reversed);
return reversed;
}
}
In my case, after some refactoring in EF6, my tests were failing with the same error message as the original poster but my solution had nothing to do with the DateTime fields.
I was just missing a required field when creating the entity. Once I added the missing field, the error went away. My entity does have two DateTime? fields but they weren't the problem.
Usage:
select replace_foreign_key('user_rates_posts', 'post_id', 'ON DELETE CASCADE');
Function:
CREATE OR REPLACE FUNCTION
replace_foreign_key(f_table VARCHAR, f_column VARCHAR, new_options VARCHAR)
RETURNS VARCHAR
AS $$
DECLARE constraint_name varchar;
DECLARE reftable varchar;
DECLARE refcolumn varchar;
BEGIN
SELECT tc.constraint_name, ccu.table_name AS foreign_table_name, ccu.column_name AS foreign_column_name
FROM
information_schema.table_constraints AS tc
JOIN information_schema.key_column_usage AS kcu
ON tc.constraint_name = kcu.constraint_name
JOIN information_schema.constraint_column_usage AS ccu
ON ccu.constraint_name = tc.constraint_name
WHERE constraint_type = 'FOREIGN KEY'
AND tc.table_name= f_table AND kcu.column_name= f_column
INTO constraint_name, reftable, refcolumn;
EXECUTE 'alter table ' || f_table || ' drop constraint ' || constraint_name ||
', ADD CONSTRAINT ' || constraint_name || ' FOREIGN KEY (' || f_column || ') ' ||
' REFERENCES ' || reftable || '(' || refcolumn || ') ' || new_options || ';';
RETURN 'Constraint replaced: ' || constraint_name || ' (' || f_table || '.' || f_column ||
' -> ' || reftable || '.' || refcolumn || '); New options: ' || new_options;
END;
$$ LANGUAGE plpgsql;
Be aware: this function won't copy attributes of initial foreign key. It only takes foreign table name / column name, drops current key and replaces with new one.
You could use only delegate which is best for callback functions:
public class ServerRequest
{
public delegate void CallBackFunction(string input);
public void DoRequest(string request, CallBackFunction callback)
{
// do stuff....
callback(request);
}
}
and consume this like below:
public class Class1
{
private void btn_click(object sender, EventArgs e)
{
ServerRequest sr = new ServerRequest();
var callback = new ServerRequest.CallBackFunction(CallbackFunc);
sr.DoRequest("myrequest",callback);
}
void CallbackFunc(string something)
{
}
}
About duli's contribution with my own measurements.
The conclusion is that arrays of integers are faster than vectors of integers (5 times in my example). However, arrays and vectors are arround the same speed for more complex / not aligned data.
When inserting an image into the drawable folders, another import point in addition to the "no capital letters" rule is that the image name cannot contain dashes or other special characters.
Use them all the time to process long-running operations asynchronously. A web user won't want to wait for more than 5 seconds for a request to process. If you have one that runs longer than that, one design is to submit the request to a queue and immediately send back a URL that the user can check to see when the job is finished.
Publish/subscribe is another good technique for decoupling senders from many receivers. It's a flexible architecture, because subscribers can come and go as needed.
In the numpy README.txt file, it says
After installation, tests can be run with:
python -c 'import numpy; numpy.test()'
This should be a sufficient test for proper installation.
you can also use the below code.
function activateController(){
console.log('HELLO WORLD');
}
$scope.$on('$viewContentLoaded', function ($evt, data) {
activateController();
});
String string = "This is test string on web";
String splitData[] = string.split("\\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
Example 1 is for asp.net applications using forms authenication. This is common practice for internet applications because user is unauthenticated until it is authentcation against some security module.
Example 2 is for asp.net application using windows authenication. Windows Authentication uses Active Directory to authenticate users. The will prevent access to your application. I use this feature on intranet applications.
You CANNOT do this - you cannot attach/detach or backup/restore a database from a newer version of SQL Server down to an older version - the internal file structures are just too different to support backwards compatibility. This is still true in SQL Server 2014 - you cannot restore a 2014 backup on anything other than another 2014 box (or something newer).
You can either get around this problem by
using the same version of SQL Server on all your machines - then you can easily backup/restore databases between instances
otherwise you can create the database scripts for both structure (tables, view, stored procedures etc.) and for contents (the actual data contained in the tables) either in SQL Server Management Studio (Tasks > Generate Scripts
) or using a third-party tool
or you can use a third-party tool like Red-Gate's SQL Compare and SQL Data Compare to do "diffing" between your source and target, generate update scripts from those differences, and then execute those scripts on the target platform; this works across different SQL Server versions.
The compatibility mode setting just controls what T-SQL features are available to you - which can help to prevent accidentally using new features not available in other servers. But it does NOT change the internal file format for the .mdf
files - this is NOT a solution for that particular problem - there is no solution for restoring a backup from a newer version of SQL Server on an older instance.
one can print values using the format method in python. This small example will help take input of two numbers a and b. Print a+b in first line and a-b in second line
print('{:d}\n{:d}'.format(a+b,a-b))
Similarly in the answer we can do
print ("{0}. {1} appears {2} times.".format(22, 'c', 9999))
The python method format() for string is used to specify a string format. So {0},{1},{2} are like array indexes called as positional parameters. Therefore {0} is assigned first value written in format (a+b), {1} is assigned the second value (a-b) and so on. We can also use keyword instead of positional parameter like for example
print("Hi! my name is {name}".format(name="rashi"))
Therefore name here is the keyword and its value is Rashi Hope it helps :)
You can also get the API key in the android studio. Switch to Project view in android then find the google-services.json. Scroll down and you will find the api_key
You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:
netstat
and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.
I know I'm late :) But this how i do it:
public static void AddOrUpdateAppSettings(string key, string value)
{
try
{
var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var settings = configFile.AppSettings.Settings;
if (settings[key] == null)
{
settings.Add(key, value);
}
else
{
settings[key].Value = value;
}
configFile.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
}
catch (ConfigurationErrorsException)
{
Console.WriteLine("Error writing app settings");
}
}
For more information look at MSDN
if (var) {
// This is the most concise equivalent of Php's isset().
}
Html-Binding will not work when using an {{interpolation}}
, use an "Expression" instead:
invalid
<p [innerHTML]="{{item.anleser}}"></p>
-> throws an error (Interpolation instead of expected Expression)
correct
<p [innerHTML]="item.anleser"></p>
-> this is the correct way.
you may add additional elements to the expression, like:
<p [innerHTML]="'<b>'+item.anleser+'</b>'"></p>
hint
HTML added using [innerHTML]
(or added dynamically by other means like element.appenChild()
or similar) won't be processed by Angular in any way except sanitization for security purposed.
Such things work only when the HTML is added statically to a components template. If you need this, you can create a component at runtime like explained in How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
In Gecko/WebKit-based browsers (Firefox, Chrome and Safari) and Opera, you can use btoa() and atob().
Original answer: How can you encode a string to Base64 in JavaScript?
Based in the answer of @G M and paying attention to the @John La Rooy's warning, I was able to append a new row opening the file in 'a'
mode.
Even in windows, in order to avoid the newline problem, you must declare it as
newline=''
.Now you can open the file in
'a'
mode (without the b).
import csv
with open(r'names.csv', 'a', newline='') as csvfile:
fieldnames = ['This','aNew']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writerow({'This':'is', 'aNew':'Row'})
I didn't try with the regular writer (without the Dict), but I think that it'll be ok too.
With newer subprocess library, you can now use the following code (*nix only solution):
import subprocess
import shlex
filename = 'your_file'
cmd = shlex.split('file --mime-type {0}'.format(filename))
result = subprocess.check_output(cmd)
mime_type = result.split()[-1]
print mime_type
I struggled with this because I'm developing a library, and every now and then want to run it as an application.
From app/build.gradle, check that you have apply plugin: 'com.android.application'
instead of apply plugin: 'com.android.library'
.
You should also have this in app/build.gradle:
defaultConfig {
applicationId "com.your_company.your_application"
...
}
Finally run Gradle sync.
I had some good results with
SELECT alphanumeric, integer FROM sorting_test ORDER BY CAST(alphanumeric AS UNSIGNED), alphanumeric ASC
I am facing the same problem. There are two solutions that I tried, and both works fine for me.
Update the Maven version repository:
Download the Apache Maven binary that includes the default https addresses (Apache Maven 3.6.3 binary). And open the Options dialog window in tools of NetBeans menu bar (Java Maven Dialog View). And select browse option in Maven Home List Box (Maven Home List Box View). After adding the Apache Maven newly downloaded version (Updated Maven Home List Box View), the project builds and runs successfully.
Restrict the current Maven version to use HTTPS links:
Include the following code in pom.xml of your project.
<project>
...
<pluginRepositories>
<pluginRepository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<repository>
<id>central</id>
<name>Central Repository</name>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
The trick is to use useradd
instead of its interactive wrapper adduser
.
I usually create users with:
RUN useradd -ms /bin/bash newuser
which creates a home directory for the user and ensures that bash is the default shell.
You can then add:
USER newuser
WORKDIR /home/newuser
to your dockerfile. Every command afterwards as well as interactive sessions will be executed as user newuser
:
docker run -t -i image
newuser@131b7ad86360:~$
You might have to give newuser
the permissions to execute the programs you intend to run before invoking the user command.
Using non-privileged users inside containers is a good idea for security reasons. It also has a few drawbacks. Most importantly, people deriving images from your image will have to switch back to root before they can execute commands with superuser privileges.
In my case, I was getting this error because my table had
varchar(50)
but I was injecting 67 character long string, which resulted in thi error. Changing it to
varchar(255)
fixed the problem.
You can use dot notation or bracket notation ...
var obj = {};
obj = {
"1": "aa",
"2": "bb"
};
obj.another = "valuehere";
obj["3"] = "cc";
Why hasn't anyone suggested Activator.CreateInstance
?
http://msdn.microsoft.com/en-us/library/wccyzw83.aspx
T obj = (T)Activator.CreateInstance(typeof(T));
Most of the answers on this thread are either complex or will result in deadlock.
Following method is simple and it will avoid deadlock because we are waiting for the task to finish and only then getting its result-
var task = Task.Run(() => GenerateCodeAsync());
task.Wait();
string code = task.Result;
Furthermore, here is a reference to MSDN article that talks about exactly same thing- https://blogs.msdn.microsoft.com/jpsanders/2017/08/28/asp-net-do-not-use-task-result-in-main-context/
I've added to /etc/sysconfig/jenkins (CentOS):
# Options to pass to java when running Jenkins.
#
JENKINS_JAVA_OPTIONS="-Djava.awt.headless=true -Xmx1024m -XX:MaxPermSize=512m"
For ubuntu the same config should be located in /etc/default
HTML
<div class="box-left-mini">
<div class="front"><span>this is in front</span></div>
<div class="behind_container">
<div class="behind">behind</div>
</div>
</div>
CSS
.box-left-mini{
float:left;
background-image:url(website-content/hotcampaign.png);
width:292px;
height:141px;
}
.box-left-mini .front {
display: block;
z-index: 5;
position: relative;
}
.box-left-mini .front span {
background: #fff
}
.box-left-mini .behind_container {
background-color: #ff0;
position: relative;
top: -18px;
}
.box-left-mini .behind {
display: block;
z-index: 3;
}
The reason you're getting so many different answers is because you've not explained what you want to do exactly. All the answers you get with code will be programmatically correct, but it's all down to what you want to achieve
With Underscore.js, you could do
_.find( {"one": [1,2,3], "two": [4,5,6]} )
It will return [1,2,3]
Try this code:
import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
buttons[inew][jnew].setBackgroundColor(Color.BLACK);
}
}, 5000);
If you are willing to put a container element around your image, a pure CSS solution is simple. You see, 99% height has no meaning when the parent element will extend vertically to contain its children. The parent needs to have a fixed height, say... the height of the viewport.
HTML
<!-- use a tall image to illustrate the problem -->
<div class='fill-screen'>
<img class='make-it-fit'
src='https://upload.wikimedia.org/wikipedia/commons/f/f2/Leaning_Tower_of_Pisa.jpg'>
</div>
CSS
div.fill-screen {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
text-align: center;
}
img.make-it-fit {
max-width: 99%;
max-height: 99%;
}
Play with the fiddle.
Using the chronic gem:
class MyModel < ActiveRecord::Base
validate :valid_date?
def valid_date?
unless Chronic.parse(from_date)
errors.add(:from_date, "is missing or invalid")
end
end
end
The existing answers are correct, but sometimes you aren't actually returning something explicitly with a Write-Output
or a return
, yet there is some mystery value in the function results. This could be the output of a builtin function like New-Item
PS C:\temp> function ContrivedFolderMakerFunction {
>> $folderName = [DateTime]::Now.ToFileTime()
>> $folderPath = Join-Path -Path . -ChildPath $folderName
>> New-Item -Path $folderPath -ItemType Directory
>> return $true
>> }
PS C:\temp> $result = ContrivedFolderMakerFunction
PS C:\temp> $result
Directory: C:\temp
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 2/9/2020 4:32 PM 132257575335253136
True
All that extra noise of the directory creation is being collected and emitted in the output. The easy way to mitigate this is to add | Out-Null
to the end of the New-Item
statement, or you can assign the result to a variable and just not use that variable. It would look like this...
PS C:\temp> function ContrivedFolderMakerFunction {
>> $folderName = [DateTime]::Now.ToFileTime()
>> $folderPath = Join-Path -Path . -ChildPath $folderName
>> New-Item -Path $folderPath -ItemType Directory | Out-Null
>> # -or-
>> $throwaway = New-Item -Path $folderPath -ItemType Directory
>> return $true
>> }
PS C:\temp> $result = ContrivedFolderMakerFunction
PS C:\temp> $result
True
New-Item
is probably the more famous of these, but others include all of the StringBuilder.Append*()
methods, as well as the SqlDataAdapter.Fill()
method.
I think you want this:
foreach ($myarray as $key => $value) {
echo "$key = $value\n";
}
Try to use constructor procedure in your class.
Object.assign
is a key
Please take a look on this sample:
class Employee{
firstname: string;
lastname: string;
birthdate: Date;
maxWorkHours: number;
department: string;
permissions: string;
typeOfEmployee: string;
note: string;
lastUpdate: Date;
constructor(original: Object) {
Object.assign(this, original);
}
}
let e = new Employee({
"department": "<anystring>",
"typeOfEmployee": "<anystring>",
"firstname": "<anystring>",
"lastname": "<anystring>",
"birthdate": "<anydate>",
"maxWorkHours": 3,
"username": "<anystring>",
"permissions": "<anystring>",
"lastUpdate": "<anydate>"
});
console.log(e);
Quoting the Scheduling Repeating Alarms - Understand the Trade-offs docs:
A common scenario for triggering an operation outside the lifetime of your app is syncing data with a server. This is a case where you might be tempted to use a repeating alarm. But if you own the server that is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with sync adapter is a better solution than AlarmManager. A sync adapter gives you all the same scheduling options as AlarmManager, but it offers you significantly more flexibility.
So, based on this, the best way to schedule a server call is using Google Cloud Messaging (GCM) in conjunction with sync adapter.
strace sqlplus -L scott/tiger@orcl
helps to find .tnsnames.ora
file on /home/oracle
to find the file it takes instead of $ORACLE_HOME/network/admin/tnsnames.ora
file. Thanks for the posting.
On Windows at least, the only practically accurate measurement mechanism is QueryPerformanceCounter (QPC). std::chrono is implemented using it (since VS2015, if you use that), but it is not accurate to the same degree as using QueryPerformanceCounter directly. In particular it's claim to report at 1 nanosecond granularity is absolutely not correct. So, if you're measuring something that takes a very short amount of time (and your case might just be such a case), then you should use QPC, or the equivalent for your OS. I came up against this when measuring cache latencies, and I jotted down some notes that you might find useful, here; https://github.com/jarlostensen/notesandcomments/blob/master/stdchronovsqcp.md
Big O is a measure of how much time/space an algorithm uses relative to the size of its input.
If an algorithm is O(n) then the time/space will increase at the same rate as its input.
If an algorithm is O(n2) then the time/space increase at the rate of its input squared.
and so on.
There is the tabindex property that can be set on component. It specifies in which order the input components should be iterated when selecting one and pressing tab. Values above 0 are reserved for custom navigation, 0 is "in natural order" (so would behave differently if set for the first element), -1 means not keyboard focusable:
<!-- navigate with tab key: -->
<input tabindex="1" type="text"/>
<input tabindex="2" type="text"/>
It can also be set for something else than the text input fields but it is not very obvious what it would do there, if anything at all. Even if the navigation works, maybe better to use "natural order" for anything else than the very obvious user input elements.
No, you do not need JQuery or any scripting at all to support this custom path of navigation. You can implement it on the server side without any JavaScript support. From the other side, the property also works fine in React framework but does not require it.
window.onload = function() {
var userImage = document.getElementById('imageOtherUser');
var hangoutButton = document.getElementById("hangoutButtonId");
userImage.onclick = function() {
hangoutButton.click(); // this will trigger the click event
};
};
this will do the trick
@echo off
set workdir={your working dir. for example - C:\work } set iplist=%workdir%\IP-list.txt
setlocal enabledelayedexpansion
set OUTPUT_FILE=%workdir%\result.csv
>nul copy nul %OUTPUT_FILE%
echo HOSTNAME,LONGNAME,IPADDRESS,STATE >%OUTPUT_FILE%
for /f %%i in (%iplist%) do (
set SERVER_ADDRESS_I=UNRESOLVED
set SERVER_ADDRESS_L=UNRESOLVED
for /f "tokens=1,2,3" %%x in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP') do (
if %%x==Pinging set SERVER_ADDRESS_L=%%y
if %%x==Pinging set SERVER_ADDRESS_I=%%z
if %%x==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
)
echo %%i [!SERVER_ADDRESS_L::=!] !SERVER_ADDRESS_I::=! is !SERVER_STATE!
echo %%i,!SERVER_ADDRESS_L::=!,!SERVER_ADDRESS_I::=!,!SERVER_STATE! >>%OUTPUT_FILE%
)
Is this issue resolved.
I am getting this error: ERROR in node_modules/ngx-restangular/lib/ngx-restangular-http.d.ts(3,27): error TS2307: Cannot find module '@angular/common/http/src/response'.
After updating my angular to version=8
Mine got solved by enabling multiDex for debug builds.
defaultConfig {
multiDexEnabled true
}
A function pointer to a class member is a problem that is really suited to using boost::function. Small example:
#include <boost/function.hpp>
#include <iostream>
class Dog
{
public:
Dog (int i) : tmp(i) {}
void bark ()
{
std::cout << "woof: " << tmp << std::endl;
}
private:
int tmp;
};
int main()
{
Dog* pDog1 = new Dog (1);
Dog* pDog2 = new Dog (2);
//BarkFunction pBark = &Dog::bark;
boost::function<void (Dog*)> f1 = &Dog::bark;
f1(pDog1);
f1(pDog2);
}
In the event you have to solve the problem with simple SQL you might use an inline view.
select count(*) from (select * from foo) as x;
If you got "Error is not recoverable: exiting now" You might have specified incorrect path references.
[me@host ~]$ tar -xvf nameOfMyTar.tar -C /someSubDirectory/
tar: /someSubDirectory: Cannot open: No such file or directory
tar: Error is not recoverable: exiting now
[me@host ~]$
Make sure you provide correct relative or absolute directory references e.g.:
[me@host ~]$ tar -xvf ./nameOfMyTar.tar -C ./someSubDirectory/
./foo/
./bar/
[me@host ~]$
This question & answer lead me to believe that IQueryable require an active context for its operation. That means you should try this instead:
try
{
IQueryable<User> users;
using (var dataContext = new dataContext())
{
users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);
if(users.Any() == false)
{
return null;
}
else
{
return users.Select(x => x.ToInfo()).ToList(); // this line is the problem
}
}
}
catch (Exception ex)
{
...
}
This this, it worked for me:
Style:
.pagination {
display: flex;
justify-content: center;
}
.pagination li {
display: block;
}
And blade:
<div class="pagination">
{{ $myCollection->render() }}
</div>
If you're purely fetching data, it's a big help to performance when you tell EF to not keep track of the entities it fetches. Do this by using MergeOption.NoTracking. EF will just generate the query, execute it and deserialize the results to objects, but will not attempt to keep track of entity changes or anything of that nature. If a query is simple (doesn't spend much time waiting on the database to return), I've found that setting it to NoTracking can double query performance.
See this MSDN article on the MergeOption enum:
Identity Resolution, State Management, and Change Tracking
This seems to be a good article on EF performance:
You can get your package name like so:
$ /path/to/adb shell 'pm list packages -f myapp'
package:/data/app/mycompany.myapp-2.apk=mycompany.myapp
Here are the options:
$ adb
Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android
-a - directs adb to listen on all interfaces for a connection
-d - directs command to the only connected USB device
returns an error if more than one USB device is present.
-e - directs command to the only running emulator.
returns an error if more than one emulator is running.
-s <specific device> - directs command to the device or emulator with the given
serial number or qualifier. Overrides ANDROID_SERIAL
environment variable.
-p <product name or path> - simple product name like 'sooner', or
a relative/absolute path to a product
out directory like 'out/target/product/sooner'.
If -p is not specified, the ANDROID_PRODUCT_OUT
environment variable is used, which must
be an absolute path.
-H - Name of adb server host (default: localhost)
-P - Port of adb server (default: 5037)
devices [-l] - list all connected devices
('-l' will also list device qualifiers)
connect <host>[:<port>] - connect to a device via TCP/IP
Port 5555 is used by default if no port number is specified.
disconnect [<host>[:<port>]] - disconnect from a TCP/IP device.
Port 5555 is used by default if no port number is specified.
Using this command with no additional arguments
will disconnect from all connected TCP/IP devices.
device commands:
adb push [-p] <local> <remote>
- copy file/dir to device
('-p' to display the transfer progress)
adb pull [-p] [-a] <remote> [<local>]
- copy file/dir from device
('-p' to display the transfer progress)
('-a' means copy timestamp and mode)
adb sync [ <directory> ] - copy host->device only if changed
(-l means list but don't copy)
adb shell - run remote shell interactively
adb shell <command> - run remote shell command
adb emu <command> - run emulator console command
adb logcat [ <filter-spec> ] - View device log
adb forward --list - list all forward socket connections.
the format is a list of lines with the following format:
<serial> " " <local> " " <remote> "\n"
adb forward <local> <remote> - forward socket connections
forward specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
dev:<character device name>
jdwp:<process pid> (remote only)
adb forward --no-rebind <local> <remote>
- same as 'adb forward <local> <remote>' but fails
if <local> is already forwarded
adb forward --remove <local> - remove a specific forward socket connection
adb forward --remove-all - remove all forward socket connections
adb reverse --list - list all reverse socket connections from device
adb reverse <remote> <local> - reverse socket connections
reverse specs are one of:
tcp:<port>
localabstract:<unix domain socket name>
localreserved:<unix domain socket name>
localfilesystem:<unix domain socket name>
adb reverse --norebind <remote> <local>
- same as 'adb reverse <remote> <local>' but fails
if <remote> is already reversed.
adb reverse --remove <remote>
- remove a specific reversed socket connection
adb reverse --remove-all - remove all reversed socket connections from device
adb jdwp - list PIDs of processes hosting a JDWP transport
adb install [-lrtsdg] <file>
- push this package file to the device and install it
(-l: forward lock application)
(-r: replace existing application)
(-t: allow test packages)
(-s: install application on sdcard)
(-d: allow version code downgrade)
(-g: grant all runtime permissions)
adb install-multiple [-lrtsdpg] <file...>
- push this package file to the device and install it
(-l: forward lock application)
(-r: replace existing application)
(-t: allow test packages)
(-s: install application on sdcard)
(-d: allow version code downgrade)
(-p: partial application install)
(-g: grant all runtime permissions)
adb uninstall [-k] <package> - remove this app package from the device
('-k' means keep the data and cache directories)
adb bugreport - return all information from the device
that should be included in a bug report.
adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]
- write an archive of the device's data to <file>.
If no -f option is supplied then the data is written
to "backup.ab" in the current directory.
(-apk|-noapk enable/disable backup of the .apks themselves
in the archive; the default is noapk.)
(-obb|-noobb enable/disable backup of any installed apk expansion
(aka .obb) files associated with each application; the default
is noobb.)
(-shared|-noshared enable/disable backup of the device's
shared storage / SD card contents; the default is noshared.)
(-all means to back up all installed applications)
(-system|-nosystem toggles whether -all automatically includes
system applications; the default is to include system apps)
(<packages...> is the list of applications to be backed up. If
the -all or -shared flags are passed, then the package
list is optional. Applications explicitly given on the
command line will be included even if -nosystem would
ordinarily cause them to be omitted.)
adb restore <file> - restore device contents from the <file> backup archive
adb disable-verity - disable dm-verity checking on USERDEBUG builds
adb enable-verity - re-enable dm-verity checking on USERDEBUG builds
adb keygen <file> - generate adb public/private key. The private key is stored in <file>,
and the public key is stored in <file>.pub. Any existing files
are overwritten.
adb help - show this help message
adb version - show version num
scripting:
adb wait-for-device - block until device is online
adb start-server - ensure that there is a server running
adb kill-server - kill the server if it is running
adb get-state - prints: offline | bootloader | device
adb get-serialno - prints: <serial-number>
adb get-devpath - prints: <device-path>
adb remount - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write
adb reboot [bootloader|recovery]
- reboots the device, optionally into the bootloader or recovery program.
adb reboot sideload - reboots the device into the sideload mode in recovery program (adb root required).
adb reboot sideload-auto-reboot
- reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.
adb sideload <file> - sideloads the given package
adb root - restarts the adbd daemon with root permissions
adb unroot - restarts the adbd daemon without root permissions
adb usb - restarts the adbd daemon listening on USB
adb tcpip <port> - restarts the adbd daemon listening on TCP on the specified port
networking:
adb ppp <tty> [parameters] - Run PPP over USB.
Note: you should not automatically start a PPP connection.
<tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
[parameters] - Eg. defaultroute debug dump local notty usepeerdns
adb sync notes: adb sync [ <directory> ]
<localdir> can be interpreted in several ways:
- If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.
- If it is "system", "vendor", "oem" or "data", only the corresponding partition
is updated.
environment variables:
ADB_TRACE - Print debug information. A comma separated list of the following values
1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp
ANDROID_SERIAL - The serial number to connect to. -s takes priority over this if given.
ANDROID_LOG_TAGS - When used with the logcat option, only these debug tags are printed.
The recent versions of XAMPP for Windows runs PHP 7.x which are NOT compatible with mbcrypt. If you have a package like Laravel that requires mbcrypt, you will need to install an older version of XAMPP. OR, you can run XAMPP with multiple versions of PHP by downloading a PHP package from Windows.PHP.net, installing it in your XAMPP folder, and configuring php.ini and httpd.conf to use the correct version of PHP for your site.
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)
$ git remote remove <name>
ie.
$ git remote remove upstream
that should do the trick
For those who are using python 2.7, python2.7 don't support django 2 so you can't install django.urls. If you are already using python 3.6 so you need to upgrade django to latest version which is greater than 2.
On PowerShell
pip install -U django
Verification
>
PS C:\Users\xyz> python
Python 3.6.6 |Anaconda, Inc.| (default, Jul 25 2018, 15:27:00) [MSC v.1910 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.urls import path
>>>
As next prompt came, it means it is installed now and ready to use.
I would prefer to import projects into Eclipse as maven
projects rather than git
project. Doing this will still allow the project contents to be recognized as git contents. You can continue to perform git operations from Eclipse. As you have mentioned the reverse is not true.
The nature of a project in Eclipse is not based on the SCM which holds the project, but on the type of project - whether war or jar, etc. - which is automagically determined when the project is imported as maven project.
I would be hesitant to check-in to SCM IDE-specific metadata. Doing so assumes a lot of things - all developers are using the same IDE or version of the IDE, perhaps same version of JDK/JRE, that they continue to use the same version throughout the project lifecycle and so on.
Ansible uses the become
, become_user
, and become_method
directives to achieve privilege escalation. You can apply them to an entire play or playbook, set them in an included playbook, or set them for a particular task.
- name: checkout repo
git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
become: yes
become_user: some_user
You can use become_with
to specify how the privilege escalation is achieved, the default being sudo
.
The directive is in effect for the scope of the block in which it is used (examples).
See Hosts and Users for some additional examples and Become (Privilege Escalation) for more detailed documentation.
In addition to the task-scoped become
and become_user
directives, Ansible 1.9 added some new variables and command line options to set these values for the duration of a play in the absence of explicit directives:
become
/become_user
directives.As of Ansible 2.0.2.0, the older sudo
/sudo_user
syntax described below still works, but the deprecation notice states, "This feature will be removed in a future release."
- name: checkout repo
git: repo=https://github.com/some/repo.git version=master dest={{ dst }}
sudo: yes
sudo_user: some_user
Use window.open
https://developer.mozilla.org/en-US/docs/Web/API/Window/open
For example, you can put this line of code in a click handler:
window.open('/file.txt', '_blank');
It will open a new tab (because of the '_blank' window-name) and that tab will open the URL.
Your server-side code should also have something like this:
res.set('Content-Disposition', 'attachment; filename=file.txt');
And that way, the browser should prompt the user to save the file to disk, instead of just showing them the file. It will also automatically close the tab that it just opened.
In case when the enum members have different values, you can apply something like this:
public static MyGender? MapToMyGender(this Gender gender)
{
return gender switch
{
Gender.Male => MyGender.Male,
Gender.Female => MyGender.Female,
Gender.Unknown => null,
_ => throw new InvalidEnumArgumentException($"Invalid gender: {gender}")
};
}
Then you can call: var myGender = gender.MapToMyGender();
Update: This previous code works only with C# 8. For older versions of C#, you can use the switch statement instead of the switch expression:
public static MyGender? MapToMyGender(this Gender gender)
{
switch (gender)
{
case Gender.Male:
return MyGender.Male;
case Gender.Female:
return MyGender.Female;
case Gender.Unknown:
return null;
default:
throw new InvalidEnumArgumentException($"Invalid gender: {gender}")
};
}
You didn't state your actual goal, but maybe this can help:
require 'matrix' # bundled with Ruby
m = Matrix[
[1, 2, 3],
[4, 5, 6]
]
m.column(0) # ==> Vector[1, 4]
(and Vectors acts like arrays)
or, using a similar notation as you desire:
m.minor(0..1, 2..2) # => Matrix[[3], [6]]
check for scipy.stats module:
scipy.stats.scoreatpercentile
To avoid syntax errors, be sure to always put BEGIN
and END
after an IF
clause, eg:
IF (@A!= @SA)
BEGIN
--do stuff
END
IF (@C!= @SC)
BEGIN
--do stuff
END
... and so on. This should work as expected. Imagine BEGIN
and END
keyword as the opening and closing bracket, respectively.
There are two events on client side as given below.
1. window.onbeforeunload (calls on Browser/tab Close & Page Load)
2. window.onload (calls on Page Load)
On server Side
public JsonResult TestAjax( string IsRefresh)
{
JsonResult result = new JsonResult();
return result = Json("Called", JsonRequestBehavior.AllowGet);
}
On Client Side
<script type="text/javascript">_x000D_
window.onbeforeunload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: { IsRefresh: 'Close' }_x000D_
});_x000D_
};_x000D_
_x000D_
window.onload = function (e) {_x000D_
_x000D_
$.ajax({_x000D_
type: 'GET',_x000D_
async: false,_x000D_
url: '/Home/TestAjax',_x000D_
data: {IsRefresh:'Load'}_x000D_
});_x000D_
};_x000D_
</script>
_x000D_
On Browser/Tab Close: if user close the Browser/tab, then window.onbeforeunload will fire and IsRefresh value on server side will be "Close".
On Refresh/Reload/F5: If user will refresh the page, first window.onbeforeunload will fire with IsRefresh value = "Close" and then window.onload will fire with IsRefresh value = "Load", so now you can determine at last that your page is refreshing.
You can achieve this with MAVEN_OPTS, for example
MAVEN_OPTS=-Dorg.slf4j.simpleLogger.defaultLogLevel=warn mvn clean
Rather than putting the system property directly on the command line. (At least for maven 3.3.1.)
Consider using ~/.mavenrc
for setting MAVEN_OPTS
if you would like logging changed for your login across all maven invocations.
@EboMike: I didn't know that Resources.getIdentifier()
existed.
In my projects I used the following code to do that:
public static int getResId(String resName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resName);
return idField.getInt(idField);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
It would be used like this for getting the value of R.drawable.icon
resource integer value
int resID = getResId("icon", R.drawable.class); // or other resource class
I just found a blog post saying that Resources.getIdentifier()
is slower than using reflection like I did. Check it out.
All your exercise conditionals are separate and the else is only tied to the last if statement. Use else if
to bind them all together in the way I believe you intend.
i am using v3.1.3 and i had to use data('DateTimePicker')
like this
var fromE = $( "#" + fromInput );
var toE = $( "#" + toInput );
$('.form-datepicker').datetimepicker(dtOpts);
$('.form-datepicker').on('change', function(e){
var isTo = $(this).attr('name') === 'to';
$( "#" + ( isTo ? fromInput : toInput ) )
.data('DateTimePicker')[ isTo ? 'setMaxDate' : 'setMinDate' ](moment($(this).val(), 'DD/MM/YYYY'))
});
The notion of complex numbers was introduced in mathematics, from the need of calculating negative quadratic roots. Complex number concept was taken by a variety of engineering fields.
Today that complex numbers are widely used in advanced engineering domains such as physics, electronics, mechanics, astronomy, etc...
Real and imaginary part, of a negative square root example:
#include <stdio.h>
#include <complex.h>
int main()
{
int negNum;
printf("Calculate negative square roots:\n"
"Enter negative number:");
scanf("%d", &negNum);
double complex negSqrt = csqrt(negNum);
double pReal = creal(negSqrt);
double pImag = cimag(negSqrt);
printf("\nReal part %f, imaginary part %f"
", for negative square root.(%d)",
pReal, pImag, negNum);
return 0;
}
You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.
This is can done in this way:
add hash in the url of next_page : example.com#hashkey
$( document ).ready(function() {
##get hash code at next page
var hashcode = window.location.hash;
## move page to any specific position of next page(let that is div with id "hashcode")
$('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');
});
//Method for Smaller Number Range:
Integer.parseInt("abc",16);
//Method for Bigger Number Range.
Long.parseLong("abc",16);
//Method for Biggest Number Range.
new BigInteger("abc",16);
You may want to take a look at GeoIP Country Whois Locator found at PHPClasses.
git rebase master
is the proper way to do this. Merging would mean a commit would be created for the merge, while rebasing would not.
Use String.Format
:
string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";
string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);
In the format {0,-20}
means the first argument has a fixed length 20, and the negative sign guarantees the string is printed from left to right.
Select the Body using chrome dev tools (Inspect ) and change in css overflow:visible,
If that doesn't work then check in below css file if html, body is set as overflow:hidden , change it as visible
I had this error:
Failed to find Build Tools revision 23.0.2
When you got updated/installed:
Change version number in build.gradle
FROM
buildToolsVersion "23.0.2"
TO
buildToolsVersion "25.0.2"
Here's full list of black dotlikes from unicode
● - ●
- Black Circle
⏺ - ⏺
- Black Circle for Record
⚫ - ⚫
- Medium Black Circle
⬤ - ⬤
- Black Large Circle
⧭ - ⧭
- Black Circle with Down Arrow
🞄 - 🞄
- Black Slightly Small Circle
• - •
- Bullet (also - •
- Message Waiting)
∙ - ∙
- Bullet Operator
⋅ - ⋅
- Dot Operator (also · - ·
- Middle Dot)
🌑 - 🌑
- New Moon Symbol
Yes, Blah.valueOf("A")
will give you Blah.A
.
Note that the name must be an exact match, including case: Blah.valueOf("a")
and Blah.valueOf("A ")
both throw an IllegalArgumentException
.
The static methods valueOf()
and values()
are created at compile time and do not appear in source code. They do appear in Javadoc, though; for example, Dialog.ModalityType
shows both methods.
INSERT...ON DUPLICATE KEY UPDATE
is prefered to prevent unexpected Exceptions management.
In my case I know that col1
and col2
make a unique composite index.
It keeps track of the error, but does not throw an exception on duplicate. Regarding the performance, the update by the same value is efficient as MySQL notices this and does not update it
INSERT INTO table
(col1, col2, col3, col4)
VALUES
(?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
col1 = VALUES(col1),
col2 = VALUES(col2)
The idea to use this approach came from the comments at phpdelusions.net/pdo.
VSCode can now support debugging PHP projects through the marketplace extension vscode-php-debug.
This extension uses XDebug in the background, and allows you to use breakpoints, watches, stack traces and the like:
Installation is straightforward from within VSCode: Summon the command line with F1 and then type ext install php-debug
Don't use LONGs, use CLOB instead. You can index and search CLOBs like VARCHAR2.
Additionally, querying with a leading wildcard(%) will ALWAYS result in a full-table-scan. Look into Oracle Text indexes instead.
Hope this helps somebody. :)
// This html:
// <form id="someCoolForm">
// <input type="text" class="form-control" name="username" value="...." />
//
// <input type="text" class="form-control" name="profile.first_name" value="...." />
// <input type="text" class="form-control" name="profile.last_name" value="...." />
//
// <input type="text" class="form-control" name="emails[]" value="..." />
// <input type="text" class="form-control" name="emails[]" value=".." />
// <input type="text" class="form-control" name="emails[]" value="." />
// </form>
//
// With this js:
//
// var form1 = parseForm($('#someCoolForm'));
// console.log(form1);
//
// Will output something like:
// {
// username: "test2"
// emails:
// 0: "[email protected]"
// 1: "[email protected]"
// profile: Object
// first_name: "..."
// last_name: "..."
// }
//
// So, function below:
var parseForm = function (form) {
var formdata = form.serializeArray();
var data = {};
_.each(formdata, function (element) {
var value = _.values(element);
// Parsing field arrays.
if (value[0].indexOf('[]') > 0) {
var key = value[0].replace('[]', '');
if (!data[key])
data[key] = [];
data[value[0].replace('[]', '')].push(value[1]);
} else
// Parsing nested objects.
if (value[0].indexOf('.') > 0) {
var parent = value[0].substring(0, value[0].indexOf("."));
var child = value[0].substring(value[0].lastIndexOf(".") + 1);
if (!data[parent])
data[parent] = {};
data[parent][child] = value[1];
} else {
data[value[0]] = value[1];
}
});
return data;
};
Addendum to @sjngm's answer:
They both also ignore whitespace:
var foo = " 3 ";
console.log(parseInt(foo)); // 3
console.log(Number(foo)); // 3
String link = driver.findElement(By.linkText(linkText)).getAttribute("href")
This will give you the link the element is pointing to.
For Oracle 11g:
SELECT COL1
FROM TABLE1
WHERE length(COL1) = (SELECT max(length(COL1)) FROM TABLE1);
There really isn't any way of doing this as most of the useful information is discarded in the compilation process. However, you may want to take a look at this site to see if you can find some way of extracting something from the DLL.
I had the same problem on CentOS 5.5
In addition to installing unixODBC-devel I also had to install gcc-c++
yum install gcc-c++
Consume and cache the column value that you want to group by, then push the remaining data as a new subarray of the group you have created in the the result.
function array_group(array $data, $by_column)
{
$result = [];
foreach ($data as $item) {
$column = $item[$by_column];
unset($item[$by_column]);
$result[$column][] = $item;
}
return $result;
}
Just Call this code and call it to your nave bar for sticky navbar
.sticky {
/*css for stickey navbar*/
position: sticky;
top: 0;
z-index: 100;
}
"The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery."
If you want to do an ajax call or a simple javascript function, don't forget to close your function with the return false
like this:
function DoAction(id, name)
{
// your code
return false;
}
To catch errors with subprocess.check_output()
, you can use CalledProcessError
. If you want to use the output as string, decode it from the bytecode.
# \return String of the output, stripped from whitespace at right side; or None on failure.
def runls():
import subprocess
try:
byteOutput = subprocess.check_output(['ls', '-a'], timeout=2)
return byteOutput.decode('UTF-8').rstrip()
except subprocess.CalledProcessError as e:
print("Error in ls -a:\n", e.output)
return None
When you don't want to write IEqualityComparer you can try something like following.
class Program
{
private static void Main(string[] args)
{
var items = new List<Item>();
items.Add(new Item {Id = 1, Name = "Item1"});
items.Add(new Item {Id = 2, Name = "Item2"});
items.Add(new Item {Id = 3, Name = "Item3"});
//Duplicate item
items.Add(new Item {Id = 4, Name = "Item4"});
//Duplicate item
items.Add(new Item {Id = 2, Name = "Item2"});
items.Add(new Item {Id = 3, Name = "Item3"});
var res = items.Select(i => new {i.Id, i.Name})
.Distinct().Select(x => new Item {Id = x.Id, Name = x.Name}).ToList();
// now res contains distinct records
}
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
The instance initialiser is just syntactic sugar in this case, right? I don't see why you need an extra anonymous class just to initialize. And it won't work if the class being created is final.
You can create an immutable map using a static initialiser too:
public class Test {
private static final Map<Integer, String> myMap;
static {
Map<Integer, String> aMap = ....;
aMap.put(1, "one");
aMap.put(2, "two");
myMap = Collections.unmodifiableMap(aMap);
}
}
In Twig:
{% for l in locations %}
<tr>
<td>
<input type="checkbox" class="filled-in" id="filled-in-box-{{ l.idLocation }}" />
<label for="filled-in-box-{{ l.idLocation }}"></label>
</td>
<td>{{ l.loc }}</td>
<td>{{ l.mun }}</td>
<td>{{ l.pro }}</td>
<td>{{ l.cou }}</td>
{#<td>
{% if l.active == 1 %}
<span class="fa fa-check"></span>
{% else %}
<span class="fa fa-close"></span>
{% endif %}
</td>#}
<td><a href="{{ url('admin_edit_location',{'id': l.idLocation}) }}" class="db-list-edit"><span class="fa fa-pencil-square-o"></span></a>
</td>
</tr>{% endfor %}
The route admin_edit_location
:
admin_edit_location:
path: /edit_location/{id}
defaults: { _controller: "AppBundle:Admin:editLocation" }
methods: GET
And the controller
public function editLocationAction($id){
// use $id
$em = $this->getDoctrine()->getManager();
$location = $em->getRepository('BackendBundle:locations')->findOneBy(array(
'id' => $id
));
}
The effect of the 301 would be that the search engines will index /option-a instead of /option-x. Which is probably a good thing since /option-x is not reachable for the search index and thus could have a positive effect on the index. Only if you use this wisely ;-)
After the redirect put exit(); to stop the rest of the script to execute
header("HTTP/1.1 301 Moved Permanently");
header("Location: /option-a");
exit();
use the following code :
if(name.getText().equals(""))
{
loginbt.disable();
}
I've also had success under linux using shutdown()
from one pthread to force another pthread currently blocked in connect()
to abort early.
Under other OSes (OSX at least), I found calling close()
was enough to get connect()
fail.
If your table is only 2 columns across, you can easily reach the second td
with the adjacent sibling selector, which IE8 does support along with :first-child
:
.editor td:first-child
{
width: 150px;
}
.editor td:first-child + td input,
.editor td:first-child + td textarea
{
width: 500px;
padding: 3px 5px 5px 5px;
border: 1px solid #CCC;
}
Otherwise, you'll have to use a JS selector library like jQuery, or manually add a class to the last td
, as suggested by James Allardice.
Using
System.ComponentModel.DataAnnotations;
You can simply put that attribute in your model :
[DataType("decimal(18,5)")]
Visual summary of options for spinning icons. Recorded using Screen To Gif.
Install via NuGet:
PM> Install-Package FontAwesome.WPF
Looks like this:
XAML:
<fa:ImageAwesome Icon="Spinner" Spin="True" SpinDuration="4" />
Icons pictured are Spinner
, CircleOutlineNotch
, Refresh
and Cog
. There are many others.
XAML copy/paste.
try
Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
, CreateBackup:=False
End Sub
If you want to save the workbook with the macros use the below code
Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
"\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
if you want to save workbook with no macros and no pop-up use this
Sub save()
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
"\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
Application.DisplayAlerts = True
End Sub
Try this, no need for a loop..
string stringToCheck = "text1";
List<string> stringList = new List<string>() { "text1", "someothertext", "etc.." };
if (stringList.Exists(o => stringToCheck.Contains(o)))
{
}
Please use [::1] instead of localhost, and make sure that the port is correct, and put the port inside the link.
const request = require('request');
let json = {
"id": id,
"filename": filename
};
let options = {
uri: "http://[::1]:8000" + constants.PATH_TO_API,
// port:443,
method: 'POST',
json: json
};
request(options, function (error, response, body) {
if (error) {
console.error("httpRequests : error " + error);
}
if (response) {
let statusCode = response.status_code;
if (callback) {
callback(body);
}
}
});
I encountered this error recently and after some brief investigation, found the cause to be that we were running out of space on the disk holding the database (less than 1GB).
As soon as I moved out the database files (.mdf and .ldf) to another disk on the same server (with lots more space), the same page (running the query) that had timed-out loaded within three seconds.
One other thing to investigate, while trying to resolve this error, is the size of the database log files. Your log files just might need to be shrunk.
There are several good articles on the subject on dev2qa.com site, about Contacts Provider
API:
How To Add Contact In Android Programmatically
How To Update Delete Android Contacts Programmatically
How To Get Contact List In Android Programmatically
Contacts are stored in SQLite .db files in bunch of tables, the structure is discussed here: Android Contacts Database Structure
Official Google documentation on Contacts Provider here
This works too, with the semi-colon.
NAME=sam; echo $NAME
With modern C++ compilers you can use sanitizers to track.
Sample example :
My program:
$cat d_free.cxx
#include<iostream>
using namespace std;
int main()
{
int * i = new int();
delete i;
//i = NULL;
delete i;
}
Compile with address sanitizers :
# g++-7.1 d_free.cxx -Wall -Werror -fsanitize=address -g
Execute :
# ./a.out
=================================================================
==4836==ERROR: AddressSanitizer: attempting double-free on 0x602000000010 in thread T0:
#0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
#1 0x400b2c in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:11
#2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
#3 0x400a08 (/media/sf_shared/jkr/cpp/d_free/a.out+0x400a08)
0x602000000010 is located 0 bytes inside of 4-byte region [0x602000000010,0x602000000014)
freed by thread T0 here:
#0 0x7f35b2d7b3c8 in operator delete(void*, unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140
#1 0x400b1b in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:9
#2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
previously allocated by thread T0 here:
#0 0x7f35b2d7a040 in operator new(unsigned long) /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:80
#1 0x400ac9 in main /media/sf_shared/jkr/cpp/d_free/d_free.cxx:8
#2 0x7f35b2050c04 in __libc_start_main (/lib64/libc.so.6+0x21c04)
SUMMARY: AddressSanitizer: double-free /media/sf_shared/gcc-7.1.0/libsanitizer/asan/asan_new_delete.cc:140 in operator delete(void*, unsigned long)
==4836==ABORTING
To learn more about sanitizers you can check this or this or any modern c++ compilers (e.g. gcc, clang etc.) documentations.
Maybe not as elegant but another possibility would be to write a formula to do the check and fill it in an adjacent column. You could then filter on that column.
The following looks in cell b14 and would return true for all the file types you mention. This assumes that the file extension is by itself in the column. If it's not it would be a little more complicated but you could still do it this way.
=OR(B14=".pdf",B14=".doc",B14=".docx",B14=".xls",B14=".xlsx",B14=".rtf",B14=".txt",B14=".csv",B14=".pps")
Like I said, not as elegant as the advanced filters but options are always good.
One can also use slightly modified version of the accepted one and adjust base characters string to it's needs:
public static string Int32ToString(int value, int toBase)
{
string result = string.Empty;
do
{
result = "0123456789ABCDEF"[value % toBase] + result;
value /= toBase;
}
while (value > 0);
return result;
}
Try this:
TO_DATE('2011-07-28T23:54:14Z', 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
something = "\t please_ \t remove_ all_ \n\n\n\nwhitespaces\n\t "
something = "".join(something.split())
output:
please_remove_all_whitespaces
something = "\t please \t remove all extra \n\n\n\nwhitespaces\n\t "
something = " ".join(something.split())
output:
please remove all extra whitespaces
Or use regex assertions: grep -oP '(?<=potato: ).*' file.txt
completing Kai Noack's answer, I would do this:
var originalTitle = document.title;
document.title = "Print page title";
window.print();
document.title = originalTitle;
this way once you print page, This will return to have its original title.
assert_has_calls
is another approach to this problem.
From the docs:
assert_has_calls (calls, any_order=False)
assert the mock has been called with the specified calls. The mock_calls list is checked for the calls.
If any_order is False (the default) then the calls must be sequential. There can be extra calls before or after the specified calls.
If any_order is True then the calls can be in any order, but they must all appear in mock_calls.
Example:
>>> from unittest.mock import call, Mock
>>> mock = Mock(return_value=None)
>>> mock(1)
>>> mock(2)
>>> mock(3)
>>> mock(4)
>>> calls = [call(2), call(3)]
>>> mock.assert_has_calls(calls)
>>> calls = [call(4), call(2), call(3)]
>>> mock.assert_has_calls(calls, any_order=True)
Source: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_has_calls
Javascript doesn't have access to the user's filesystem for security reasons. FileReader
is only for files manually selected by the user.
I would do
import os
path = os.path.normpath(path)
path.split(os.sep)
First normalize the path string into a proper string for the OS. Then os.sep
must be safe to use as a delimiter in string function split.
It means the new copy of your application (on your development machine) was signed with a different signing key than the old copy of your application (installed on the device/emulator). For example, if this is a device, you might have put the old copy on from a different development machine (e.g., some other developer's machine). Or, the old one is signed with your production key and the new one is signed with your debug key.
Just to add to the other answers: In case you don't like the onload
callback approach, you can "promisify" it like so:
let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img
I just want to add to all great answers above,
that if you write a library it's a good practice to use ConfigureAwait(false)
and get better performance, as said here.
So this snippet seems to be better:
public static async Task DoWork()
{
int[] ids = new[] { 1, 2, 3, 4, 5 };
await Task.WhenAll(ids.Select(i => DoSomething(1, i))).ConfigureAwait(false);
}
A full fiddle link here.
You have mixed 2 standard.
The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";
The function http_build_query($filedata)
is only for "Content-Type: application/x-www-form-urlencoded", or none.
As to the short script, the following runs on my Linux host
#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION="\.jpg"
while read MYFILE ; do
adb pull "$DEVICE_DIR/$MYFILE" "$HOST_DIR/$MYFILE"
done < $(adb shell ls -1 "$DEVICE_DIR" | grep "$EXTENSION")
"ls minus one" lets "ls" show one file per line, and the quotation marks allow spaces in the filename.
You can set a default value at creation time like:
CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
Married boolean DEFAULT false);
If you go to the Flat file connection manager under Advanced and Look at the "OutputColumnWidth" description's ToolTip It will tell you that Composit characters may use more spaces. So the "é" in "Société" most likely occupies more than one character.
EDIT: Here's something about it: http://en.wikipedia.org/wiki/Precomposed_character
Spring annotations will work fine if you remove enctype="multipart/form-data"
.
@RequestParam(value="txtEmail", required=false)
You can even get the parameters from the request
object .
request.getParameter(paramName);
Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.
Configure the Multi-part resolver if you want to receive enctype="multipart/form-data"
.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="250000"/>
</bean>
Refer the Spring documentation.
As a simple extension to marc_s's answer (the one that has been accepted), this is adjusted to return column count and allow for filtering:
SELECT *
FROM
(
SELECT
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
COUNT(DISTINCT c.COLUMN_NAME) as ColumnCount,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
(SUM(a.used_pages) * 8) AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
INNER JOIN
INFORMATION_SCHEMA.COLUMNS c ON t.NAME = c.TABLE_NAME
LEFT OUTER JOIN
sys.schemas s ON t.schema_id = s.schema_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
) AS Result
WHERE
RowCounts > 1000
AND ColumnCount > 10
ORDER BY
UsedSpaceKB DESC
From your code it becomes apparent that you use POCO. Having another key is unnecessary: you can add an index as suggested by juFo.
If you use Fluent API instead of attributing UserName property your column annotation should look like this:
this.Property(p => p.UserName)
.HasColumnAnnotation("Index", new IndexAnnotation(new[] {
new IndexAttribute("Index") { IsUnique = true }
}
));
This will create the following SQL script:
CREATE UNIQUE NONCLUSTERED INDEX [Index] ON [dbo].[Users]
(
[UserName] ASC
)
WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
SORT_IN_TEMPDB = OFF,
IGNORE_DUP_KEY = OFF,
DROP_EXISTING = OFF,
ONLINE = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON
) ON [PRIMARY]
If you attempt to insert multiple Users having the same UserName you'll get a DbUpdateException with the following message:
Cannot insert duplicate key row in object 'dbo.Users' with unique index 'Index'.
The duplicate key value is (...).
The statement has been terminated.
Again, column annotations are not available in Entity Framework prior to version 6.1.
Simple, just use .set_color
>>> barlist=plt.bar([1,2,3,4], [1,2,3,4])
>>> barlist[0].set_color('r')
>>> plt.show()
For your new question, not much harder either, just need to find the bar from your axis, an example:
>>> f=plt.figure()
>>> ax=f.add_subplot(1,1,1)
>>> ax.bar([1,2,3,4], [1,2,3,4])
<Container object of 4 artists>
>>> ax.get_children()
[<matplotlib.axis.XAxis object at 0x6529850>,
<matplotlib.axis.YAxis object at 0x78460d0>,
<matplotlib.patches.Rectangle object at 0x733cc50>,
<matplotlib.patches.Rectangle object at 0x733cdd0>,
<matplotlib.patches.Rectangle object at 0x777f290>,
<matplotlib.patches.Rectangle object at 0x777f710>,
<matplotlib.text.Text object at 0x7836450>,
<matplotlib.patches.Rectangle object at 0x7836390>,
<matplotlib.spines.Spine object at 0x6529950>,
<matplotlib.spines.Spine object at 0x69aef50>,
<matplotlib.spines.Spine object at 0x69ae310>,
<matplotlib.spines.Spine object at 0x69aea50>]
>>> ax.get_children()[2].set_color('r')
#You can also try to locate the first patches.Rectangle object
#instead of direct calling the index.
If you have a complex plot and want to identify the bars first, add those:
>>> import matplotlib
>>> childrenLS=ax.get_children()
>>> barlist=filter(lambda x: isinstance(x, matplotlib.patches.Rectangle), childrenLS)
[<matplotlib.patches.Rectangle object at 0x3103650>,
<matplotlib.patches.Rectangle object at 0x3103810>,
<matplotlib.patches.Rectangle object at 0x3129850>,
<matplotlib.patches.Rectangle object at 0x3129cd0>,
<matplotlib.patches.Rectangle object at 0x3112ad0>]
As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.
If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").
But this function is not intended to reload the browser.
All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.
Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).
For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.
Hence the need for the function
history.pushState({},"Results for `Cats`",'url.html?s=cats');
It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.
When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.
If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.
As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.
See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.
Give permission in .htaccess as follows:
<Directory "Your directory path/uploads/">
Allow from all
</Directory>
A single line:
this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
(Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
It is essentially a security measure. If your app is compromised, the attacker will only have access to the short-lived access token and no way to generate a new one.
Refresh tokens also expire but they are supposed to live much longer than the access token.