You can get a graphical view of the project history with tools like gitk
. Just run:
gitk --all
If you want to checkout a specific branch:
git checkout <branch name>
For a specific commit, use the SHA1 hash instead of the branch name. (See Treeishes in the Git Community Book, which is a good read, to see other options for navigating your tree.)
git log
has a whole set of options to display detailed or summary history too.
I don't know of an easy way to move forward in a commit history. Projects with a linear history are probably not all that common. The idea of a "revision" like you'd have with SVN or CVS doesn't map all that well in Git.
The Revert command in the context menu ignores your edits and returns the working copy to its previous state. You may also select the desired revision other than the "Head" when you "CheckOut" from the repository.
How about making an alias
?
alias gc="git rev-list --all --count" #Or whatever name you wish
Using the latest versions of Subclipse, you can actually view them without using the cmd prompt. On the file, simply right-click => Team => Switch to another branch/tag/revision. Besides the revision field, you click select, and you'll see all the versions of that file.
Its simple. You just have to set the upstream for the current branch
$ git clone repo
$ git checkout -b newbranch
$ git branch --set-upstream-to=origin/branch newbranch
$ git pull
That's all
When you have created a new WPF application you should have a .xaml file and a .cs file. These represent your main window. Create an additional .xaml file and .cs file to represent your sub window.
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button Content="Open Window" Click="ButtonClicked" Height="25" HorizontalAlignment="Left" Margin="379,264,0,0" Name="button1" VerticalAlignment="Top" Width="100" />
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void ButtonClicked(object sender, RoutedEventArgs e)
{
SubWindow subWindow = new SubWindow();
subWindow.Show();
}
}
Then add whatever additional code you need to these classes:
SubWindow.xaml
SubWindow.xaml.cs
Have you tried :-
Sub test()
k = Cells(Rows.Count, "A").End(xlUp).Row
MsgBox (k)
End Sub
The /only/ catch is that if there is no data it still returns 1.
First thing, try a full rebuild. Clean and build (or just use rebuild). Every once in a long while that resolves bizarre build issues for me.
Next, comment out the rest of the code that is not in your example you have posted. Compile. Does that work?
If so, start adding segments back until one breaks it.
If not, make all the classes public
and try again.
If that still fails, maybe try putting the trimmed down classes in the same file and rebuilding. At that point, there would be absolutely no reason for access issues. If that still fails, take up carpentry.
I like Open DBDiff.
While not the most complete tool, it works great, it's free, and it's very easy to use.
All the properties of your object are private. aka... not available outside their class's scope.
Use the new JsonSerializable
Interface to provide your own json representation to be used by json_encode
class Thing implements JsonSerializable {
...
public function jsonSerialize() {
return [
'something' => $this->something,
'protected_something' => $this->get_protected_something(),
'private_something' => $this->get_private_something()
];
}
...
}
If you do want to serialize your private and protected object properties, you have to implement a JSON encoding function inside your Class that utilizes json_encode()
on a data structure you create for this purpose.
class Thing {
...
public function to_json() {
return json_encode(array(
'something' => $this->something,
'protected_something' => $this->get_protected_something(),
'private_something' => $this->get_private_something()
));
}
...
}
You also can set the width of a audio tag by JavaScript:
audio = document.getElementById('audio-id');
audio.style.width = '200px';
for AND you use
if ($status = 'clear' && $pRent == 0) {
mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
}
for OR you use
if ($status = 'clear' || $pRent == 0) {
mysql_query("UPDATE rent SET dNo = '$id', status = 'clear', colour = '#3C0' WHERE rent.id = $id");
}
It's creating a size 0
bitfield if the condition is false, but a size -1
(-!!1
) bitfield if the condition is true/non-zero. In the former case, there is no error and the struct is initialized with an int member. In the latter case, there is a compile error (and no such thing as a size -1
bitfield is created, of course).
For checking spaces just with bash:
[[ "$str" = "${str% *}" ]] && echo "no spaces" || echo "has spaces"
To use the hex
encoding in Python 3, use
>>> import codecs
>>> codecs.encode(b"c", "hex")
b'63'
In legacy Python, there are several other ways of doing this:
>>> hex(ord("c"))
'0x63'
>>> format(ord("c"), "x")
'63'
>>> "c".encode("hex")
'63'
async components
:Source : https://vueschool.io/articles/vuejs-tutorials/async-vuejs-components/
<script>
export default {
data: () => ({ show: false }),
components: {
Tooltip: () => import("./Tooltip")
}
};
</script>
Good Luck...
Bulk inserts are possible by using nested array, see the github page
Nested arrays are turned into grouped lists (for bulk inserts), e.g.
[['a', 'b'], ['c', 'd']]
turns into('a', 'b'), ('c', 'd')
You just insert a nested array of elements.
An example is given in here
var mysql = require('mysql');
var conn = mysql.createConnection({
...
});
var sql = "INSERT INTO Test (name, email, n) VALUES ?";
var values = [
['demian', '[email protected]', 1],
['john', '[email protected]', 2],
['mark', '[email protected]', 3],
['pete', '[email protected]', 4]
];
conn.query(sql, [values], function(err) {
if (err) throw err;
conn.end();
});
Note: values
is an array of arrays wrapped in an array
[ [ [...], [...], [...] ] ]
There is also a totally different node-msql package for bulk insertion
Have you given a try to Webkit Filters?
You can manipulate not only opacity, but colour, brightness, luminosity and other properties:
Incase if you don't file in your local repo but in git repo, then simply open file in git repo through web interface and find Delete button at right corner in interface. Click Here, To view interface Delete Option
sub uniq {
return keys %{{ map { $_ => 1 } @_ }};
}
my @my_array = ("a","a","b","b","c");
#print join(" ", @my_array), "\n";
my $a = join(" ", uniq(@my_array));
my @b = split(/ /,$a);
my $count = $#b;
I ran into this same issue, but I think I know what's causing the confusion. If you use MySql Query Analyzer, you can do this just fine:
SELECT myvalue
INTO @myvar
FROM mytable
WHERE anothervalue = 1;
However, if you put that same query in MySql Workbench, it will throw a syntax error. I don't know why they would be different, but they are. To work around the problem in MySql Workbench, you can rewrite the query like this:
SELECT @myvar:=myvalue
FROM mytable
WHERE anothervalue = 1;
top.frames.location.reload(false);
You don't have the last version of typescript.
Running :
npm install -g typescript
npm
checks if tsc
command is already installed.
And it might be, by another software like Visual Studio
. If so, npm
doesn't override it. So you have to remove the previous deprecated tsc
installed command.
Run where tsc
to know its bin location. It should be in C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\
in windows. Once found, delete the folder, and re-run npm install -g typescript
. This should now install the last version of typescript.
In bash
, provided you files names have no spaces:
cd /home/webapps/project1/folder1
for f in *.csv
do
cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv
done
use below code , change proper database name and user name and then take that output and execute in SSMS. FOR SQL 2005 ABOVE
USE <database_name>
select 'GRANT EXECUTE ON ['+name+'] TO [userName] '
from sys.objects
where type ='P'
and is_ms_shipped = 0
SELECT *
FROM Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND (C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND (isnull(@Value,1) <> 2
OR I.RecurringCharge = @Total
OR @Total is NULL )
AND (isnull(@Value,2) <> 3
OR I.RecurringCharge like '%'+cast(@Total as varchar(50))+'%'
OR @Total is NULL )
Basically, your condition was
if (@Value=2)
TEST FOR => (I.RecurringCharge=@Total or @Total is NULL )
flipped around,
AND (isnull(@Value,1) <> 2 -- A
OR I.RecurringCharge = @Total -- B
OR @Total is NULL ) -- C
When (A) is true, i.e. @Value is not 2, [A or B or C] will become TRUE regardless of B and C results. B and C are in reality only checked when @Value = 2
, which is the original intention.
Here is a chart of the compatibility between chromedriver and chrome. This information can be found at the Chromedriver downloads page.
chromedriver chrome
2.46 71-73
2.45 70-72
2.44 69-71
2.43 69-71
2.42 68-70
2.41 67-69
2.40 66-68
2.39 66-68
2.38 65-67
2.37 64-66
2.36 63-65
2.35 62-64
2.34 61-63
2.33 60-62
---------------------
2.28 57+
2.25 54+
2.24 53+
2.22 51+
2.19 44+
2.15 42+
chromedriver chrome
76.0.3809.68 76
75.0.3770.140 75
74.0.3729.6 74
73.0.3683.68 73
It seems compatibility is only guaranteed within that revision.
If you need to run chromedriver across multiple versions of chrome for some reason, well, plug the latest version number of chrome you're using into the Chromedriver version selection guide, then hope for the best. Actual compatibility will depend on the exact versions involved and what features you're using.
For example, we had a bug today where chromedriver 2.33 was trying to run this on Chrome 65:
((ChromeDriver) driver).findElement(By.id("firstName")).sendKeys("hello")
Due to the navigation changes in Chrome 63, updated in Chromedriver 2.34, we got back
unknown error: call function result missing 'value'
Updating to Chromedriver 2.37 fixed the issue.
With Guava 15 you can also simply use:
Set s = Sets.newConcurrentHashSet();
Some of the scenarios, object.item would not be loaded or will be undefined.
Use ng-init
<select ng-init="object.item=2" ng-model="object.item"
ng-options="item.id as item.name for item in list"
If you are facing this issue in Mac-OSX terminal with python, try updating the versions of the packages you are using. So, go to your files in python and where you specified the packages, update them to the latest versions available on the internet.
Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.
After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.
I'm using @foreach
when I send an entity that contains a list of entities ( for example to display 2 grids in 1 view )
For example if I'm sending as model the entity Foo that contains Foo1(List<Foo1>)
and Foo2(List<Foo2>)
I can refer to the first List with:
@foreach (var item in Model.Foo.Foo1)
{
@Html.DisplayFor(modelItem=> item.fooName)
}
Same codes from Nickolay above, but tested on IE9 and chrome (and removed the extra rendering):
window.onload = window.onresize = function() {
var canvas = document.getElementById('canvas');
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
var canvasWidth = viewportWidth * 0.8;
var canvasHeight = canvasWidth / 2;
canvas.style.position = "absolute";
canvas.setAttribute("width", canvasWidth);
canvas.setAttribute("height", canvasHeight);
canvas.style.top = (viewportHeight - canvasHeight) / 2 + "px";
canvas.style.left = (viewportWidth - canvasWidth) / 2 + "px";
}
HTML:
<body>
<canvas id="canvas" style="background: #ffffff">
Canvas is not supported.
</canvas>
</body>
The top and left offset only works when I add px
.
Your version does not support that character set, I believe it was 5.5.3
that introduced it. You should upgrade your mysql to the version you used to export this file.
The error is then quite clear: you set a certain character set in your code, but your mysql version does not support it, and therefore does not know about it.
According to https://dev.mysql.com/doc/refman/5.5/en/charset-unicode-utf8mb4.html :
utf8mb4 is a superset of utf8
so maybe there is a chance you can just make it utf8, close your eyes and hope, but that would depend on your data, and I'd not recommend it.
If you want this to work in IE 8 and below, use
<!--[if lte IE 8]>
lte
meaning "Less than or equal".
For more on conditional comments, see e.g. the quirksmode.org page.
The .swapcase method transforms the uppercase latters in a string to lowercase and the lowercase letters to uppercase.
'TESTING'.swapcase #=> testing
'testing'.swapcase #=> TESTING
If you set a variable via SETX, you cannot use this variable or its changes immediately. You have to restart the processes that want to use it.
Use the following sequence to directly set it in the setting process too (works for me perfectly in scripts that do some init stuff after setting global variables):
SET XYZ=test
SETX XYZ test
He was considering having the date as a key, but worried that values will be written one above other, all I wanted to show (maybe not that obvious, that why I do edit) is that he can still have values intact, not written one above other, isn't this okay?!
<?php
$data['may_1_2002']=
Array(
'title_id_32'=>'Good morning',
'title_id_21'=>'Blue sky',
'title_id_3'=>'Summer',
'date'=>'1 May 2002'
);
$data['may_2_2002']=
Array(
'title_id_34'=>'Leaves',
'title_id_20'=>'Old times',
'date'=>'2 May 2002 '
);
echo '<pre>';
print_r($data);
?>
In your case use data==null
(which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)
function test(data) {_x000D_
if (data != null) {_x000D_
console.log('Data: ', data);_x000D_
}_x000D_
}_x000D_
_x000D_
test(); // the data=undefined_x000D_
test(null); // the data=null_x000D_
test(undefined); // the data=undefined_x000D_
_x000D_
test(0); _x000D_
test(false); _x000D_
test('something');
_x000D_
Here you have all (src):
if
== (its negation !=)
=== (its negation !==)
If you want to just accept defaults you can use:
\n | ./shell_being_run
To solve your error I propose this solution: to work on Visual studio code editor and install live server extension in the editor, which allows you to connect to your local server, for me I put the picture in my workspace 127.0.0.1:5500/workspace/data/pict.png and it works!
So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.
/^[a-z0-9]+$/i
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
We can use attribute selector in DOM by using document.querySelector()
and document.querySelectorAll()
methods.
for yours:
document.querySelector("[myAttribute='aValue']");
and by using querySelectorAll()
:
document.querySelectorAll("[myAttribute='aValue']");
In querySelector()
and querySelectorAll()
methods we can select objects as we select in "CSS".
More about "CSS" attribute selectors in https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
If you'd like to turn this on by default for ALL ObjectMapper instances in a process, here's a little hack that will set the default value of INDENT_OUTPUT to true:
val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)
Tag helpers:
<a asp-controller="OtherController" asp-action="Index" class="btn btn-primary"> Back to Other Controller View </a>
In the controller.cs have a method:
public async Task<IActionResult> Index()
{
ViewBag.Title = "Titles";
return View(await Your_Model or Service method);
}
foreach (var item in dicNumber)
{
listnumber.Add(item.Key);
}
Curl is a non-java program and must be provided outside your Java program.
You can easily get much of the functionality using Jakarta Commons Net, unless there is some specific functionality like "resume transfer" you need (which is tedious to code on your own)
print
outputs each argument, followed by $,
, to $stdout
, followed by $\
. It is equivalent to args.join($,) + $\
puts
sets both $,
and $\
to "\n" and then does the same thing as print
. The key difference being that each argument is a new line with puts
.
You can require 'english'
to access those global variables with user-friendly names.
I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.
(function() {
var lastText = '';
$('#MyTextBox'), {
source: MyData
})
.on('autocompleteselect autocompletefocus', function(ev, ui) {
lastText = ui.item.label;
jqTag.data('autocomplete-item', ui.item);
})
.keyup(function(ev) {
if (lastText != jqTag.val()) {
// Clear when they stop typing
jqTag.data('autocomplete-item', null);
// Pass the event on as autocompleteclear so callers can listen for select/clear
var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
return jqTag.trigger(clearEv);
});
})();
With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.
To avoid the UnauthorizedAccessException
, I use:
var files = GetFiles(@"C:\", "*.*", SearchOption.AllDirectories);
foreach (var file in files)
{
Console.WriteLine($"{file}");
}
public static IEnumerable<string> GetFiles(string path, string searchPattern, SearchOption searchOption)
{
var foldersToProcess = new List<string>()
{
path
};
while (foldersToProcess.Count > 0)
{
string folder = foldersToProcess[0];
foldersToProcess.RemoveAt(0);
if (searchOption.HasFlag(SearchOption.AllDirectories))
{
//get subfolders
try
{
var subfolders = Directory.GetDirectories(folder);
foldersToProcess.AddRange(subfolders);
}
catch (Exception ex)
{
//log if you're interested
}
}
//get files
var files = new List<string>();
try
{
files = Directory.GetFiles(folder, searchPattern, SearchOption.TopDirectoryOnly).ToList();
}
catch (Exception ex)
{
//log if you're interested
}
foreach (var file in files)
{
yield return file;
}
}
}
You can first find the position of the string in this case ":"
'position = InStr(StringToSearch, StringToFind)
position = InStr(StringToSearch, ":")
Then use Left(StringToCut, NumberOfCharacterToCut)
Result = Left(StringToSearch, position -1)
Loads scripts that depends on one another with the right order.
Based on Satyam Pathak response, but fixed the onload. It was triggered before the script actually loaded.
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']_x000D_
let count = 0_x000D_
_x000D_
_x000D_
const recursivelyAddScript = (script, cb) => {_x000D_
const el = document.createElement('script')_x000D_
el.src = script_x000D_
if(count < scripts.length) {_x000D_
count ++_x000D_
el.onload = () => recursivelyAddScript(scripts[count])_x000D_
document.body.appendChild(el)_x000D_
} else {_x000D_
console.log('All script loaded')_x000D_
return_x000D_
}_x000D_
}_x000D_
_x000D_
recursivelyAddScript(scripts[count])
_x000D_
Looks like your form is submitting which is the default behaviour, you can stop it with this:
<form action="" method="post" onsubmit="completeAndRedirect();return false;">
I know this is old, but i think i have good solution. Comparing to other answers and also comparing to accepted, mine accepts multiple values. Basically filter object with key:value search parameters (also object within object). Also it works with numbers etc, cause when comparing, it converts them to string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'filter'})
export class Filter implements PipeTransform {
transform(array: Array<Object>, filter: Object): any {
let notAllKeysUndefined = false;
let newArray = [];
if(array.length > 0) {
for (let k in filter){
if (filter.hasOwnProperty(k)) {
if(filter[k] != undefined && filter[k] != '') {
for (let i = 0; i < array.length; i++) {
let filterRule = filter[k];
if(typeof filterRule === 'object') {
for(let fkey in filterRule) {
if (filter[k].hasOwnProperty(fkey)) {
if(filter[k][fkey] != undefined && filter[k][fkey] != '') {
if(this.shouldPushInArray(array[i][k][fkey], filter[k][fkey])) {
newArray.push(array[i]);
}
notAllKeysUndefined = true;
}
}
}
} else {
if(this.shouldPushInArray(array[i][k], filter[k])) {
newArray.push(array[i]);
}
notAllKeysUndefined = true;
}
}
}
}
}
if(notAllKeysUndefined) {
return newArray;
}
}
return array;
}
private shouldPushInArray(item, filter) {
if(typeof filter !== 'string') {
item = item.toString();
filter = filter.toString();
}
// Filter main logic
item = item.toLowerCase();
filter = filter.toLowerCase();
if(item.indexOf(filter) !== -1) {
return true;
}
return false;
}
}
CMD:
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
reg query HKEY_CURRENT_USER\Environment
PowerShell:
Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Get-Item HKCU:\Environment
Powershell/.NET: (see EnvironmentVariableTarget Enum)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)
login to mysql with proper credential and used mysql>SHOW VARIABLES LIKE 'datadir'; that will give you path of where mysql stored
d = Date.now();_x000D_
d = new Date(d);_x000D_
d = (d.getMonth()+1)+'/'+d.getDate()+'/'+d.getFullYear()+' '+(d.getHours() > 12 ? d.getHours() - 12 : d.getHours())+':'+d.getMinutes()+' '+(d.getHours() >= 12 ? "PM" : "AM");_x000D_
_x000D_
console.log(d);
_x000D_
Change the minDate dynamically
.datepicker("destroy")
For example
<script>
$(function() {
$( "#datepicker" ).datepicker("destroy");
$( "#datepicker" ).datepicker();
});
</script>
<p>Date: <input type="text" id="datepicker" /></p>
I could do it like this
i have ran into the same problem and found a solution (not totally by myself, but there is the internet for)
Color blue = ColorTranslator.FromHtml("#CCFFFF");
Color red = ColorTranslator.FromHtml("#FFCCFF");
Color letters = Color.Black;
foreach (DataGridViewRow r in datagridIncome.Rows)
{
if (r.Cells[5].Value.ToString().Contains("1")) {
r.DefaultCellStyle.BackColor = blue;
r.DefaultCellStyle.SelectionBackColor = blue;
r.DefaultCellStyle.SelectionForeColor = letters;
}
else {
r.DefaultCellStyle.BackColor = red;
r.DefaultCellStyle.SelectionBackColor = red;
r.DefaultCellStyle.SelectionForeColor = letters;
}
}
This is a small trick, the only way you can see a row is selected, is by the very first column (not column[0], but the one therefore). When you click another row, you will not see the blue selection anymore, only the arrow indicates which row have selected. As you understand, I use rowSelection in my gridview.
I use this method in my css file
@font-face {
font-family: FontName1;
src: url("fontname1.eot"); /* IE */
src: local('FontName1'), url('fontname1.ttf') format('truetype'); /* others */
}
@font-face {
font-family: FontName2;
src: url("fontname1.eot"); /* IE */
src: local('FontName2'), url('fontname2.ttf') format('truetype'); /* others */
}
@font-face {
font-family: FontName3;
src: url("fontname1.eot"); /* IE */
src: local('FontName3'), url('fontname3.ttf') format('truetype'); /* others */
}
Declare your ch
as
unsigned char ch = 212 ;
And your printf will work.
You can write a script and then use nohup ./yourscript &
to execute
For example:
vi yourscript
put
#!/bin/bash
script here
you may also need to change permission to run script on server
chmod u+rwx yourscript
finally
nohup ./yourscript &
This was a very handy page as I have a requirement to DELETE records from a mySQL table where the expiry date is < Today.
I am on a shared host and CRON did not like the suggestion AndrewKDay. it also said (and I agree) that exposing the password in this way could be insecure.
I then tried turning Events ON in phpMyAdmin but again being on a shared host this was a no no. Sorry fancyPants.
So I turned to embedding the SQL script in a PHP file. I used the example [here][1]
[1]: https://www.w3schools.com/php/php_mysql_create_table.asp stored it in a sub folder somewhere safe and added an empty index.php for good measure. I was then able to test that this PHP file (and my SQL script) was working from the browser URL line.
All good so far. On to CRON. Following the above example almost worked. I ended up calling PHP before the path for my *.php file. Otherwise CRON didn't know what to do with the file.
my cron is set to run once per day and looks like this, modified for security.
00 * * * * php mywebsiteurl.com/wp-content/themes/ForteChildTheme/php/DeleteExpiredAssessment.php
For the final testing with CRON I initially set it to run each minute and had email alerts turned on. This quickly confirmed that it was running as planned and I changed it back to once per day.
Hope this helps.
In my case, I had made a stupid typo in the shebang.
So in case someone else on with fat fingers stumbles across this question:
Whoops: #!/usr/local/bin ruby
I meant to write: #!/usr/bin/env ruby
The vague error ZSH gives sent me down the wrong path:
ZSH: zsh: permission denied: ./foo.rb
Bash: bash: ./foo.rb: /usr/local/bin: bad interpreter: Permission denied
What if you just wrap your code into function?
So this:
cd ~/documents
mkdir test
echo "useless script" > about.txt
Becomes this:
CommentedOutBlock() {
cd ~/documents
mkdir test
echo "useless script" > about.txt
}
As other answers have mentioned, the &&
token in this context is new to C++0x (the next C++ standard) and represent an "rvalue reference".
Rvalue references are one of the more important new things in the upcoming standard; they enable support for 'move' semantics on objects and permit perfect forwarding of function calls.
It's a rather complex topic - one of the best introductions (that's not merely cursory) is an article by Stephan T. Lavavej, "Rvalue References: C++0x Features in VC10, Part 2"
Note that the article is still quite heavy reading, but well worthwhile. And even though it's on a Microsoft VC++ Blog, all (or nearly all) the information is applicable to any C++0x compiler.
I prefer using Math.Round, Math.Floor, Math.Ceiling or Math.Truncate to explicitly set the rounding mode as appropriate.
Note that they all return Decimal as well - since Decimal has a larger range of values than an Int32, so you'll still need to cast (and check for overflow/underflow).
checked {
int i = (int)Math.Floor(d);
}
A simple way to do this is to call a logging function:
DEBUG = True
def log(s):
if DEBUG:
print s
log("hello world")
Then you can change the value of DEBUG
and run your code with or without logging.
The standard logging
module has a more elaborate mechanism for this.
General algorithms for date manipulation convert dates to and from Julian Day Numbers. Here is a link to a description of such algorithms, a description of the best algorithms currently known, and the mathematical proofs of each of them: http://web.archive.org/web/20140910060704/http://mysite.verizon.net/aesir_research/date/date0.htm
None of the aforementioned solutions worked for me. What I had to do was use a nullable int (int?) on the foreign key that was not required (or not a not null column key) and then delete some of my migrations.
Start by deleting the migrations, then try the nullable int.
Problem was both a modification and model design. No code change was necessary.
For me.
Edit .gitattributes file.
add
*.dll binary
Then everything goes well.
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
Alternatively, you could just return false from the click event:
$('div.toggle').hide();
$('ul.product-info li a').click(function(event){
$(this).next('div').slideToggle(200);
+ return false;
});
Which would stop the A-Href being triggered.
Note however, for usability reasons, in an ideal world that href should still go somewhere, for the people whom want to open link in new tab ;)
Per pierce.jason's answer above, I had luck with:
Just create a new DWORD(32) under the Fusion key. Name the DWORD to LogFailures, and set it to value 1. Then restart IIS, refresh the page giving errors, and the assembly bind logs will show in the error message.
For firefox links appear to be "special". The only way I was able to get this working was to use the createEvent described here on MDN and call the initMouseEvent function. Even that didn't work completely, I had to manually tell the browser to open a link...
var theEvent = document.createEvent("MouseEvent");
theEvent.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
var element = document.getElementById('link');
element.dispatchEvent(theEvent);
while (element)
{
if (element.tagName == "A" && element.href != "")
{
if (element.target == "_blank") { window.open(element.href, element.target); }
else { document.location = element.href; }
element = null;
}
else
{
element = element.parentElement;
}
}
in my case i click on recent apps shortcut on my cell phone and close all apps. This solution always work for me, because this error not related to code.
Thanks guys, I was migrating an existing project to Gradle and didn't like the idea of changing the project structure that much.
I have figured it out, thought this information could be useful to beginners.
Here is a sample task from my 'build.gradle':
version = '1.0.0'
jar {
baseName = 'analytics'
from('src/main/java') {
include 'config/**/*.xml'
}
manifest {
attributes 'Implementation-Title': 'Analytics Library', 'Implementation-Version': version
}
}
myArrayOfMatrices = zeros(unknown,500,800);
If you're running out of memory throw more RAM in your system, and make sure you're running a 64 bit OS. Also try reducing your precision (do you really need doubles or can you get by with singles?):
myArrayOfMatrices = zeros(unknown,500,800,'single');
To append to that array try:
myArrayOfMatrices(unknown+1,:,:) = zeros(500,800);
As noted at Detecting the onload event of a window opened with window.open, the following solution is ideal:
/* Internet Explorer will throw an error on one of the two statements, Firefox on the other one of the two. */
(function(ow) {
ow.addEventListener("load", function() { alert("loaded"); }, false);
ow.attachEvent("onload", function() { alert("loaded"); }, false);
})(window.open(prompt("Where are you going today?", location.href), "snapDown"));
Other comments and answers perpetrate several erroneous misconceptions as explained below.
The following script demonstrates the fickleness of defining onload
. Apply the script to a "fast loading" location for the window being opened, such as one with the file:
scheme and compare this to a "slow" location to see the problem: it is possible to see either onload
message or none at all (by reloading a loaded page all 3 variations can be seen). It is also assumed that the page being loaded itself does not define an onload
event which would compound the problem.
The onload
definitions are evidently not "inside pop-up document markup":
var popup = window.open(location.href, "snapDown");
popup.onload = function() { alert("message one"); };
alert("message 1 maybe too soon\n" + popup.onload);
popup.onload = function() { alert("message two"); };
alert("message 2 maybe too late\n" + popup.onload);
What you can do:
javascript:
URI -- the code will run with the same privileges as the domain of the "foreign" URLjavascript:
URI may need to be bookmarked if typing it in the address bar has no effect (may be the case with some browsers released around 2012)Thus any page, well almost, irregardless of origin, can be modified like:
if(confirm("wipe out links & anchors?\n" + document.body.innerHTML))
void(document.body.innerHTML=document.body.innerHTML.replace(/<a /g,"< a "))
Well, almost:
jar:file:///usr/lib/firefox/omni.ja!/chrome/toolkit/content/global/aboutSupport.xhtml
, Mozilla Firefox's troubleshooting page and other Jar archives are exceptions.
As another example, to routinely disable Google's usurping of target hits, change its rwt
function with the following URI:
javascript: void(rwt = function(unusurpURL) { return unusurpURL; })
(Optionally Bookmark the above as e.g. "Spay Google" ("neutralize Google"?)
This bookmark is then clicked before any Google hits are clicked, so bookmarks of any of those hits are clean and not the mongrelized perverted aberrations that Google made of them.
Tests done with Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:11.0) Gecko/20100101 Firefox/11.0
UA string.
It should be noted that addEventListener
in Firefox only has a non-standard fourth, boolean parameter, which if true
allows untrusted content triggers to be instantiated for foreign pages.
Reference:
element.addEventListener | Document Object Model (DOM) | MDN:
Interaction between privileged and non-privileged pages | Code snippets | MDN:
set JAVA_HOME variable and ad JAVA_HOME/bin to evnrionment path variable.
Or use JodaTime:
DateTime lastWeek = new DateTime().minusDays(7);
This style is for full reset for tables - cellpadding, cellspacing and borders.
I had this style in my reset.css file:
table{
border:0; /* Replace border */
border-spacing: 0px; /* Replace cellspacing */
border-collapse: collapse; /* Patch for Internet Explorer 6 and Internet Explorer 7 */
}
table td{
padding: 0px; /* Replace cellpadding */
}
SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')
More often than you think, C needs to do things that seem to be unneccessary from an Assembly coder's point of view just because the C standards say so.
Integer promotion, for example. If you want to shift a char variable in C, one would usually expect that the code would do in fact just that, a single bit shift.
The standards, however, enforce the compiler to do a sign extend to int before the shift and truncate the result to char afterwards which might complicate code depending on the target processor's architecture.
so if you need want use this code )
import { useRoutes } from "./routes";
import { BrowserRouter as Router } from "react-router-dom";
export const App = () => {
const routes = useRoutes(true);
return (
<Router>
<div className="container">{routes}</div>
</Router>
);
};
// ./routes.js
import { Switch, Route, Redirect } from "react-router-dom";
export const useRoutes = (isAuthenticated) => {
if (isAuthenticated) {
return (
<Switch>
<Route path="/links" exact>
<LinksPage />
</Route>
<Route path="/create" exact>
<CreatePage />
</Route>
<Route path="/detail/:id">
<DetailPage />
</Route>
<Redirect path="/create" />
</Switch>
);
}
return (
<Switch>
<Route path={"/"} exact>
<AuthPage />
</Route>
<Redirect path={"/"} />
</Switch>
);
};
Another way is to select a column with the columns
array:
In [5]: df = pd.DataFrame([[1,2], [3,4]], columns=['a', 'b'])
In [6]: df
Out[6]:
a b
0 1 2
1 3 4
In [7]: df[df.columns[0]]
Out[7]:
0 1
1 3
Name: a, dtype: int64
There's some sort of security restriction in place in Chrome for using geolocation from a file:///
URI, though unfortunately it doesn't seem to record any errors to indicate that. It will work from a local web server. If you have python installed try opening a command prompt in the directory where your test files are and issuing the command:
python -m SimpleHTTPServer
It should start up a web server on port 8000 (might be something else, but it'll tell you in the console what port it's listening on), then browse to http://localhost:8000/mytestpage.html
If you don't have python there are equivalent modules in Ruby, or Visual Web Developer Express comes with a built in local web server.
Just added ignore: []
in the specific page for the specific form, this solution worked for me.
$("#form_name").validate({
ignore: [],
onkeyup: false,
rules: {
},
highlight:false,
});
If you want to run notepad inside your app you would probably be better of with a text editor component. There's obviously a basic text box that comes with WinForms, but I suspect more advanced components that offer Notepad functionality (or better) can be found on the interweb.
I think your question isn't quite clear. There are several answers here on how to catch the data coming into a Linux's serial port, but perhaps your problem is the other way around?
If you need to catch the data coming out of a Linux's serial port and send it to a server, there are several little hardware gizmos that can do this, starting with the simple serial print server such as this Lantronix gizmo.
No, I'm not affiliated with Lantronix in any way.
This solved the problem
C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis -i
Be sure to run the command prompt as administrator
Your UITableViewDelegate
should implement tableView:heightForRowAtIndexPath:
Objective-C
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return [indexPath row] * 20;
}
Swift 5
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return indexPath.row * 20
}
You will probably want to use NSString
's sizeWithFont:constrainedToSize:lineBreakMode:
method to calculate your row height rather than just performing some silly math on the indexPath :)
public static String getcurrentDateAndTime(){
Date c = Calendar.getInstance().getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
String formattedDate = simpleDateFormat.format(c);
return formattedDate;
}
// String currentdate= getcurrentDateAndTime();
I like Robert McMahan's answer the best here as it seems the easiest to make into sharable include files for any of your scripts to use. But it seems to have a flaw with the line if [[ -n ${variables[$argument_label]} ]]
throwing the message, "variables: bad array subscript". I don't have the rep to comment, and I doubt this is the proper 'fix,' but wrapping that if
in if [[ -n $argument_label ]] ; then
cleans it up.
Here's the code I ended up with, if you know a better way please add a comment to Robert's answer.
Include File "flags-declares.sh"
# declaring a couple of associative arrays
declare -A arguments=();
declare -A variables=();
# declaring an index integer
declare -i index=1;
Include File "flags-arguments.sh"
# $@ here represents all arguments passed in
for i in "$@"
do
arguments[$index]=$i;
prev_index="$(expr $index - 1)";
# this if block does something akin to "where $i contains ="
# "%=*" here strips out everything from the = to the end of the argument leaving only the label
if [[ $i == *"="* ]]
then argument_label=${i%=*}
else argument_label=${arguments[$prev_index]}
fi
if [[ -n $argument_label ]] ; then
# this if block only evaluates to true if the argument label exists in the variables array
if [[ -n ${variables[$argument_label]} ]] ; then
# dynamically creating variables names using declare
# "#$argument_label=" here strips out the label leaving only the value
if [[ $i == *"="* ]]
then declare ${variables[$argument_label]}=${i#$argument_label=}
else declare ${variables[$argument_label]}=${arguments[$index]}
fi
fi
fi
index=index+1;
done;
Your "script.sh"
. bin/includes/flags-declares.sh
# any variables you want to use here
# on the left left side is argument label or key (entered at the command line along with it's value)
# on the right side is the variable name the value of these arguments should be mapped to.
# (the examples above show how these are being passed into this script)
variables["-gu"]="git_user";
variables["--git-user"]="git_user";
variables["-gb"]="git_branch";
variables["--git-branch"]="git_branch";
variables["-dbr"]="db_fqdn";
variables["--db-redirect"]="db_fqdn";
variables["-e"]="environment";
variables["--environment"]="environment";
. bin/includes/flags-arguments.sh
# then you could simply use the variables like so:
echo "$git_user";
echo "$git_branch";
echo "$db_fqdn";
echo "$environment";
I always prefer to check time in hours, minutes and seconds (%H:%M:%S) format:
from datetime import datetime
start = datetime.now()
# your code
end = datetime.now()
time_taken = end - start
print('Time: ',time_taken)
output:
Time: 0:00:00.000019
Because a stateless protocol does not require the server to retain session information or status about each communications partner for the duration of multiple requests.
HTTP is a stateless protocol, which means that the connection between the browser and the server is lost once the transaction ends.
Really cheap solution:
urllib.urlopen('http://user:[email protected]/api')
(which you may decide is not suitable for a number of reasons, like security of the url)
>>> import urllib, json
>>> result = urllib.urlopen('https://personal-access-token:[email protected]/repos/:owner/:repo')
>>> r = json.load(result.fp)
>>> result.close()
public static class SerializerDeserializerExtensions
{
public static byte[] Serializer(this object _object)
{
byte[] bytes;
using (var _MemoryStream = new MemoryStream())
{
IFormatter _BinaryFormatter = new BinaryFormatter();
_BinaryFormatter.Serialize(_MemoryStream, _object);
bytes = _MemoryStream.ToArray();
}
return bytes;
}
public static T Deserializer<T>(this byte[] _byteArray)
{
T ReturnValue;
using (var _MemoryStream = new MemoryStream(_byteArray))
{
IFormatter _BinaryFormatter = new BinaryFormatter();
ReturnValue = (T)_BinaryFormatter.Deserialize(_MemoryStream);
}
return ReturnValue;
}
}
You can use it like below code.
DataTable _DataTable = new DataTable();
_DataTable.Columns.Add(new DataColumn("Col1"));
_DataTable.Columns.Add(new DataColumn("Col2"));
_DataTable.Columns.Add(new DataColumn("Col3"));
for (int i = 0; i < 10; i++) {
DataRow _DataRow = _DataTable.NewRow();
_DataRow["Col1"] = (i + 1) + "Column 1";
_DataRow["Col2"] = (i + 1) + "Column 2";
_DataRow["Col3"] = (i + 1) + "Column 3";
_DataTable.Rows.Add(_DataRow);
}
byte[] ByteArrayTest = _DataTable.Serializer();
DataTable dt = ByteArrayTest.Deserializer<DataTable>();
For sake of completeness, here is a script which actually could be a one-liner to get a backup from a database, excluding (ignoring) all the views. The db name is assumed to be employees:
ignore=$(mysql --login-path=root1 INFORMATION_SCHEMA \
--skip-column-names --batch \
-e "select
group_concat(
concat('--ignore-table=', table_schema, '.', table_name) SEPARATOR ' '
)
from tables
where table_type = 'VIEW' and table_schema = 'employees'")
mysqldump --login-path=root1 --column-statistics=0 --no-data employees $ignore > "./backups/som_file.sql"
You can update the logic of the query. In general using group_concat
and concat
you can generate almost any desired string or shell command.
Dockers use images which are build in layers. This adds a lot in terms of portability, sharing, versioning and other features. These images are very easy to port or transfer and since they are in layers, changes in subsequent versions are added in form of layers over previous layers. So, while porting many a times you don't need to port the base layers. Dockers have containers which run these images with execution environment contained, they add changes as new layers providing easy version control.
Apart from that Docker Hub is a good registry with thousands of public images, where you can find images which have OS and other softwares installed. So, you can get a pretty good head start for your application.
You can use psexec.exe from Microsoft Sysinternals Suite https://docs.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite
Example:
c:\somedir\psexec.exe -u domain\user -p password cmd.exe
Use the following
SELECT timestamp, value, card
FROM my_table
ORDER BY timestamp DESC
LIMIT 1
String
s in java are objects, so when comparing with ==
, you are comparing references, rather than values. The correct way is to use equals()
.
However, there is a way. If you want to compare String
objects using the ==
operator, you can make use of the way the JVM copes with strings. For example:
String a = "aaa";
String b = "aaa";
boolean b = a == b;
b
would be true
. Why?
Because the JVM has a table of String
constants. So whenever you use string literals (quotes "
), the virtual machine returns the same objects, and therefore ==
returns true
.
You can use the same "table" even with non-literal strings by using the intern()
method. It returns the object that corresponds to the current string value from that table (or puts it there, if it is not). So:
String a = new String("aa");
String b = new String("aa");
boolean check1 = a == b; // false
boolean check1 = a.intern() == b.intern(); // true
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
You can do the following:
set a local variable to false
set that variable true
in the first loop, when you want to break
then you can check in the outer loop, that whether the condition is set then break from the outer loop as well.
boolean isBreakNeeded = false;
for (int i = 0; i < some.length; i++) {
for (int j = 0; j < some.lengthasWell; j++) {
//want to set variable if (){
isBreakNeeded = true;
break;
}
if (isBreakNeeded) {
break; //will make you break from the outer loop as well
}
}
This is a prototype to generate or destroy a controller or model in Rails:
rails generate/destroy controller/model [controller/model Name]
For example, if you need to generate a User Controller:
rails generate controller User
or
rails g controller User
If you want to destroy the User controller or revert to above action then use:
rails destroy controller User
or:
rails d controller User
Maybe will be useful for someone.
When you login to any user of any console/terminal history of your current session exists only in some "buffer" which flushes to ~/.bash_history on your logout.
So, to keep things secret you can just:
history -r && exit
and you will be logged out with all your session's (and only) history cleared ;)
android:background="@android:color/transparent"
The above is something that I know... I think creating a custom button class is the best idea
API Level 11
Recently I came across this android:alpha xml attribute which takes a value between 0 and 1. The corresponding method is setAlpha(float).
Using log4j.properties file, and including apache-log4j-extras 1.1 in my POM with log4j 1.2.16
log4j.appender.LOGFILE=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.LOGFILE.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.LOGFILE.RollingPolicy.FileNamePattern=/logs/application_%d{yyyy-MM-dd}.log
Since we're on a subject, one can use regular expressions too
"aaabcd".replaceFirst(".$",""); //=> aaabc
UPDATE:3 Now that I have upgraded to new Router, @borislemke's approach will not work if you use CanDeactivate
guard. I'm degrading to my old method, ie:
this answer
UPDATE2: Router events in new-router look promising and the answer by @borislemke seems to cover the main aspect of spinner implementation, I havent't tested it but I recommend it.
UPDATE1: I wrote this answer in the era of Old-Router
, when there used to be only one event route-changed
notified via router.subscribe()
. I also felt overload of the below approach and tried to do it using only router.subscribe()
, and it backfired because there was no way to detect canceled navigation
. So I had to revert back to lengthy approach(double work).
If you know your way around in Angular2, this is what you'll need
Boot.ts
import {bootstrap} from '@angular/platform-browser-dynamic';
import {MyApp} from 'path/to/MyApp-Component';
import { SpinnerService} from 'path/to/spinner-service';
bootstrap(MyApp, [SpinnerService]);
Root Component- (MyApp)
import { Component } from '@angular/core';
import { SpinnerComponent} from 'path/to/spinner-component';
@Component({
selector: 'my-app',
directives: [SpinnerComponent],
template: `
<spinner-component></spinner-component>
<router-outlet></router-outlet>
`
})
export class MyApp { }
Spinner-Component (will subscribe to Spinner-service to change the value of active accordingly)
import {Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
selector: 'spinner-component',
'template': '<div *ngIf="active" class="spinner loading"></div>'
})
export class SpinnerComponent {
public active: boolean;
public constructor(spinner: SpinnerService) {
spinner.status.subscribe((status: boolean) => {
this.active = status;
});
}
}
Spinner-Service (bootstrap this service)
Define an observable to be subscribed by spinner-component to change the status on change, and function to know and set the spinner active/inactive.
import {Injectable} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import 'rxjs/add/operator/share';
@Injectable()
export class SpinnerService {
public status: Subject<boolean> = new Subject();
private _active: boolean = false;
public get active(): boolean {
return this._active;
}
public set active(v: boolean) {
this._active = v;
this.status.next(v);
}
public start(): void {
this.active = true;
}
public stop(): void {
this.active = false;
}
}
All Other Routes' Components
(sample):
import { Component} from '@angular/core';
import { SpinnerService} from 'path/to/spinner-service';
@Component({
template: `<div *ngIf="!spinner.active" id="container">Nothing is Loading Now</div>`
})
export class SampleComponent {
constructor(public spinner: SpinnerService){}
ngOnInit(){
this.spinner.stop(); // or do it on some other event eg: when xmlhttp request completes loading data for the component
}
ngOnDestroy(){
this.spinner.start();
}
}
I just figured. You need to add a shared folder using VirtualBox before you access it with the guest.
Click "Device" in the menu bar--->Shared File--->add a directory and name it
then in the guest terminal, use:
sudo mount -t vboxsf myFileName ~/destination
Dont directly refer to the host directory
I found a good example of what you need in this link.
import javax.swing.JFileChooser;
public class Main {
public static void main(String s[]) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("choosertitle");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
} else {
System.out.println("No Selection ");
}
}
}
Iterate through a copy of the list:
>>> a = ["a", "b", "c", "d", "e"]
>>> for item in a[:]:
print item
if item == "b":
a.remove(item)
a
b
c
d
e
>>> print a
['a', 'c', 'd', 'e']
In .Net, you cannot assign a null
value to an int
or any other struct. Instead, use a Nullable<int>
, or int?
for short:
int? value = 0;
if (value == 0)
{
value = null;
}
Further Reading
Just a little addition if one wants to parse a space separated text file line by line.
read_file = function (path)
local file = io.open(path, "rb")
if not file then return nil end
local lines = {}
for line in io.lines(path) do
local words = {}
for word in line:gmatch("%w+") do
table.insert(words, word)
end
table.insert(lines, words)
end
file:close()
return lines;
end
To avoid this sort of trouble, you can use replace
(which takes a plain string) instead of replaceAll
(which takes a regular expression). You will still need to escape backslashes, but not in the wild ways required with regular expressions.
You can make method which return the datatable of given sql query:
public DataTable GetDataTable()
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["BarManConnectionString"].ConnectionString);
conn.Open();
string query = "SELECT * FROM [EventOne] ";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable t1 = new DataTable();
using (SqlDataAdapter a = new SqlDataAdapter(cmd))
{
a.Fill(t1);
}
return t1;
}
and now can be used like this:
table = GetDataTable();
Stopping (Killing) a thread mid-way is not recommended. The API is actually deprecated.
However,you can get more details including workarounds here: How do you kill a thread in Java?
ok, so my problem was that I tried to install the package with yum which is the primary tool for getting, installing, deleting, querying, and managing Red Hat Enterprise Linux RPM software packages from official Red Hat software repositories, as well as other third-party repositories.
But I'm using ubuntu and The usual way to install packages on the command line in Ubuntu is with apt-get. so the right command was:
sudo apt-get install libstdc++.i686
ALTER TABLE [table_name] ALTER COLUMN [column_name] varchar(150)
Run Developer Command Prompt For V2012 or any version installed in your system
gacutil /i pathofDll
Enter
Done!!!
In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325
Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.
Make sure that you have checked it to work properly with the IE version you specify.
subclass the handler you want to be able to disable temporarily:
class ToggledHandler(logging.StreamHandler):
"""A handler one can turn on and off"""
def __init__(self, args, kwargs):
super(ToggledHandler, self).__init__(*args, **kwargs)
self.enabled = True # enabled by default
def enable(self):
"""enables"""
self.enabled = True
def disable(self):
"""disables"""
self.enabled = False
def emit(self, record):
"""emits, if enabled"""
if self.enabled:
# this is taken from the super's emit, implement your own
try:
msg = self.format(record)
stream = self.stream
stream.write(msg)
stream.write(self.terminator)
self.flush()
except Exception:
self.handleError(record)
finding the handler by name is quite easy:
_handler = [x for x in logging.getLogger('').handlers if x.name == your_handler_name]
if len(_handler) == 1:
_handler = _handler[0]
else:
raise Exception('Expected one handler but found {}'.format(len(_handler))
once found:
_handler.disable()
doStuff()
_handler.enable()
There is an important bit that is not mentioned in the article to which you linked and that is flex-basis
. By default flex-basis
is auto
.
From the spec:
If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)
Each flex item has a flex-basis
which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow
) among the items. With auto
, that basis is the contents size (or defined size with width
, etc.). As a result, items with bigger text within are being given more space overall in your example.
If you want your elements to be completely even, you can set flex-basis: 0
. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow
.
li {
flex-grow: 1;
flex-basis: 0;
/* ... */
}
This diagram from the spec does a pretty good job of illustrating the point.
And here is a working example with your fiddle.
if everything fails then for gmail you must turn on access to 3rd party apps to connect to ur gmail account.
https://www.google.com/settings/security/lesssecureapps // turn it on
Applications that are not satisfied with only 256 different characters have the options of either using wide characters (more than 8 bits) or a variable-length encoding (a multibyte encoding in C++ terminology) such as UTF-8. Wide characters generally require more space than a variable-length encoding, but are faster to process. Multi-language applications that process large amounts of text usually use wide characters when processing the text, but convert it to UTF-8 when storing it to disk.
The only difference between a string
and a wstring
is the data type of the characters they store. A string stores char
s whose size is guaranteed to be at least 8 bits, so you can use strings for processing e.g. ASCII, ISO-8859-15, or UTF-8 text. The standard says nothing about the character set or encoding.
Practically every compiler uses a character set whose first 128 characters correspond with ASCII. This is also the case with compilers that use UTF-8 encoding. The important thing to be aware of when using strings in UTF-8 or some other variable-length encoding, is that the indices and lengths are measured in bytes, not characters.
The data type of a wstring is wchar_t
, whose size is not defined in the standard, except that it has to be at least as large as a char, usually 16 bits or 32 bits. wstring can be used for processing text in the implementation defined wide-character encoding. Because the encoding is not defined in the standard, it is not straightforward to convert between strings and wstrings. One cannot assume wstrings to have a fixed-length encoding either.
If you don't need multi-language support, you might be fine with using only regular strings. On the other hand, if you're writing a graphical application, it is often the case that the API supports only wide characters. Then you probably want to use the same wide characters when processing the text. Keep in mind that UTF-16 is a variable-length encoding, meaning that you cannot assume length()
to return the number of characters. If the API uses a fixed-length encoding, such as UCS-2, processing becomes easy. Converting between wide characters and UTF-8 is difficult to do in a portable way, but then again, your user interface API probably supports the conversion.
in 5.7 version. 'password' field has been deleted. 'authentication_string' replace it
use mysql;
update user set authentication_string=password('123456') where user='root';
flush privileges;
COPY:Click the title bar, choose mark, then select the content you want to copy. PASTE: Copy what you want to past, focus on the bash, hit the insert key on the keyboard.
You should use the equals
method since this is implemented to perform the comparison you want. toString()
itself uses an iterator just like equals
but it is a more inefficient approach. Additionally, as @Teepeemm pointed out, toString
is affected by order of elements (basically iterator return order) hence is not guaranteed to provide the same output for 2 different maps (especially if we compare two different maps).
Note/Warning: Your question and my answer assume that classes implementing the map interface respect expected toString
and equals
behavior. The default java classes do so, but a custom map class needs to be examined to verify expected behavior.
See: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
boolean equals(Object o)
Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings. More formally, two maps m1 and m2 represent the same mappings if m1.entrySet().equals(m2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.
Additionally, java itself takes care of iterating through all elements and making the comparison so you don't have to. Have a look at the implementation of AbstractMap
which is used by classes such as HashMap
:
// Comparison and hashing
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent the same mappings. More formally, two maps <tt>m1</tt> and
* <tt>m2</tt> represent the same mappings if
* <tt>m1.entrySet().equals(m2.entrySet())</tt>. This ensures that the
* <tt>equals</tt> method works properly across different implementations
* of the <tt>Map</tt> interface.
*
* <p>This implementation first checks if the specified object is this map;
* if so it returns <tt>true</tt>. Then, it checks if the specified
* object is a map whose size is identical to the size of this map; if
* not, it returns <tt>false</tt>. If so, it iterates over this map's
* <tt>entrySet</tt> collection, and checks that the specified map
* contains each mapping that this map contains. If the specified map
* fails to contain such a mapping, <tt>false</tt> is returned. If the
* iteration completes, <tt>true</tt> is returned.
*
* @param o object to be compared for equality with this map
* @return <tt>true</tt> if the specified object is equal to this map
*/
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> m = (Map<K,V>) o;
if (m.size() != size())
return false;
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
toString
fails miserably when comparing a TreeMap
and HashMap
though equals
does compare contents correctly.
Code:
public static void main(String args[]) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("2", "whatever2");
map.put("1", "whatever1");
TreeMap<String, Object> map2 = new TreeMap<String, Object>();
map2.put("2", "whatever2");
map2.put("1", "whatever1");
System.out.println("Are maps equal (using equals):" + map.equals(map2));
System.out.println("Are maps equal (using toString().equals()):"
+ map.toString().equals(map2.toString()));
System.out.println("Map1:"+map.toString());
System.out.println("Map2:"+map2.toString());
}
Output:
Are maps equal (using equals):true
Are maps equal (using toString().equals()):false
Map1:{2=whatever2, 1=whatever1}
Map2:{1=whatever1, 2=whatever2}
How to associate the command with a MenuItem
:
<MenuItem Header="My command" Command="{x:Static local:MyWindow.MyCommand}"/>
Your original question mentions the "Swing Timer". If in fact your question is related to SWing, then you should be using the Swing Timer and NOT the util.Timer.
Read the section from the Swing tutorial on "How to Use Timers" for more information.
The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with
conda install -c anaconda pandas
Unfortunately I do not know how to help with Eclipse.
use the min-height property. min-height:20px;
that is true that JSP is converted into servlet at the time of execution, and JSF is totally new thing in order to make the webpage more readable as JSF allows to write all the programming structures in the form of tag.
You can simply open http://localhost:8080/
in your web browser
and this will open Tomcat welcome page that shows running Tomcat version like this:
Apache Tomcat/7.0.42
INDEX=0
for i in $list; do
echo ${INDEX}_$i
let INDEX=${INDEX}+1
done
If preg_match
did not find a match, $matches
is an empty array. So you should check if preg_match
found an match before accessing $matches[0]
, for example:
function get_match($regex,$content)
{
if (preg_match($regex,$content,$matches)) {
return $matches[0];
} else {
return null;
}
}
Can't see anything wrong with your code, I use SqlExpress and it works fine when I use a connection string in the constructor.
You have created an App_Data folder in your project, haven't you?
You can have multiple .gitignore
, each one of course in its own directory.
To check which gitignore rule is responsible for ignoring a file, use git check-ignore
: git check-ignore -v -- afile
.
And you can have different version of a .gitignore
file per branch: I have already seen that kind of configuration for ensuring one branch ignores a file while the other branch does not: see this question for instance.
If your repo includes several independent projects, it would be best to reference them as submodules though.
That would be the actual best practices, allowing each of those projects to be cloned independently (with their respective .gitignore
files), while being referenced by a specific revision in a global parent project.
See true nature of submodules for more.
Note that, since git 1.8.2 (March 2013) you can do a git check-ignore -v -- yourfile
in order to see which gitignore run (from which .gitignore
file) is applied to 'yourfile
', and better understand why said file is ignored.
See "which gitignore
rule is ignoring my file?"
Also, to "increment" string, when update, use CONCAT
update dbo.test set foo=CONCAT(foo, 'bar') where 1=1
When using permitAll
it means every authenticated user, however you disabled anonymous access so that won't work.
What you want is to ignore certain URLs for this override the configure
method that takes WebSecurity
object and ignore
the pattern.
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/api/v1/signup");
}
And remove that line from the HttpSecurity
part. This will tell Spring Security to ignore this URL and don't apply any filters to them.
Under OSX, to avoid this issue and avoid other problems with developing on a case-insensitive filesystem, you can use Disk Utility to create a case sensitive virtual drive / disk image.
Run disk utility, create new disk image, and use the following settings (or change as you like, but keep it case sensitive):
Make sure to tell git it is now on a case sensitive FS:
git config core.ignorecase false
In pure SQL the main statement kools like:
INSERT INTO [simbs] ([En]) OUTPUT INSERTED.[ID] VALUES ('en')
Square brackets defines the table simbs and then the columns En and ID, round brackets defines the enumeration of columns to be initiated and then the values for the columns, in my case one column and one value. The apostrophes enclose a string
I will explain you my approach:
It might be not easy to understand but i hope useful to get the big picture around using the last inserted id. Of course there are alternative easier approaches. But I have reasons to keep mine. Associated functions are not included, just their names and parameter names.
I use this method for medical artificial intelligence The method check if the wanted string exist in the central table (1). If the wanted string is not in the central table "simbs", or if duplicates are allowed, the wanted string is added to the central table "simbs" (2). The last inseerted id is used to create associated table (3).
public List<int[]> CreateSymbolByName(string SymbolName, bool AcceptDuplicates)
{
if (! AcceptDuplicates) // check if "AcceptDuplicates" flag is set
{
List<int[]> ExistentSymbols = GetSymbolsByName(SymbolName, 0, 10); // create a list of int arrays with existent records
if (ExistentSymbols.Count > 0) return ExistentSymbols; //(1) return existent records because creation of duplicates is not allowed
}
List<int[]> ResultedSymbols = new List<int[]>(); // prepare a empty list
int[] symbolPosition = { 0, 0, 0, 0 }; // prepare a neutral position for the new symbol
try // If SQL will fail, the code will continue with catch statement
{
//DEFAULT und NULL sind nicht als explizite Identitätswerte zulässig
string commandString = "INSERT INTO [simbs] ([En]) OUTPUT INSERTED.ID VALUES ('" + SymbolName + "') "; // Insert in table "simbs" on column "En" the value stored by variable "SymbolName"
SqlCommand mySqlCommand = new SqlCommand(commandString, SqlServerConnection); // initialize the query environment
SqlDataReader myReader = mySqlCommand.ExecuteReader(); // last inserted ID is recieved as any resultset on the first column of the first row
int LastInsertedId = 0; // this value will be changed if insertion suceede
while (myReader.Read()) // read from resultset
{
if (myReader.GetInt32(0) > -1)
{
int[] symbolID = new int[] { 0, 0, 0, 0 };
LastInsertedId = myReader.GetInt32(0); // (2) GET LAST INSERTED ID
symbolID[0] = LastInsertedId ; // Use of last inserted id
if (symbolID[0] != 0 || symbolID[1] != 0) // if last inserted id succeded
{
ResultedSymbols.Add(symbolID);
}
}
}
myReader.Close();
if (SqlTrace) SQLView.Log(mySqlCommand.CommandText); // Log the text of the command
if (LastInsertedId > 0) // if insertion of the new row in the table was successful
{
string commandString2 = "UPDATE [simbs] SET [IR] = [ID] WHERE [ID] = " + LastInsertedId + " ;"; // update the table by giving to another row the value of the last inserted id
SqlCommand mySqlCommand2 = new SqlCommand(commandString2, SqlServerConnection);
mySqlCommand2.ExecuteNonQuery();
symbolPosition[0] = LastInsertedId; // mark the position of the new inserted symbol
ResultedSymbols.Add(symbolPosition); // add the new record to the results collection
}
}
catch (SqlException retrieveSymbolIndexException) // this is executed only if there were errors in the try block
{
Console.WriteLine("Error: {0}", retrieveSymbolIndexException.ToString()); // user is informed about the error
}
CreateSymbolTable(LastInsertedId); //(3) // Create new table based on the last inserted id
if (MyResultsTrace) SQLView.LogResult(LastInsertedId); // log the action
return ResultedSymbols; // return the list containing this new record
}
Android's permission system is one of the biggest security concern all along since those permissions are asked for at install time. Once installed, the application will be able to access all of things granted without any user's acknowledgement what exactly application does with the permission.
Android 6.0 Marshmallow introduces one of the largest changes to the permissions model with the addition of runtime permissions, a new permission model that replaces the existing install time permissions model when you target API 23 and the app is running on an Android 6.0+ device
Courtesy goes to Requesting Permissions at Run Time .
Example
Declare this as Global
private static final int PERMISSION_REQUEST_CODE = 1;
Add this in your onCreate()
section
After setContentView(R.layout.your_xml);
if (Build.VERSION.SDK_INT >= 23)
{
if (checkPermission())
{
// Code for above or equal 23 API Oriented Device
// Your Permission granted already .Do next code
} else {
requestPermission(); // Code for permission
}
}
else
{
// Code for Below 23 API Oriented Device
// Do next code
}
Now adding checkPermission() and requestPermission()
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(Your_Activity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(Your_Activity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(Your_Activity.this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(Your_Activity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
Log.e("value", "Permission Denied, You cannot use local drive .");
}
break;
}
}
This interface is the contract for receiving the results for permission requests.
Simple Solution :
Open Android SDK manager, on top side you can see the "Android SDK Location
" go to that location and follow this path
\extras\intel\Hardware_Accelerated_Execution_Manager
here you will get "intelhaxm-android.exe" install this setup.
UPDATE: with the compact
command and WiredTiger it looks like the extra disk space will actually be released to the OS.
UPDATE: as of v1.9+ there is a compact
command.
This command will perform a compaction "in-line". It will still need some extra space, but not as much.
MongoDB compresses the files by:
You can do this "compression" by running mongod --repair
or by connecting directly and running db.repairDatabase()
.
In either case you need the space somewhere to copy the files. Now I don't know why you don't have enough space to perform a compress, however, you do have some options if you have another computer with more space.
mongoexport
) and then you can Import that same database (using mongoimport
). This will result in a new database that is more compressed. Now you can stop the original mongod
replace with the new database files and you're good to go.There is not currently a good way to "compact in place" using Mongo. And Mongo can definitely suck up a lot of space.
The best strategy right now for compaction is to run a Master-Slave setup. You can then compact the Slave, let it catch up and switch them over. I know still a little hairy. Maybe the Mongo team will come up with better in place compaction, but I don't think it's high on their list. Drive space is currently assumed to be cheap (and it usually is).
UPDATE:
All of the above answers won't work for the repeated values, @BenBolker's answer using duplicated()
predicate solves this:
full_vector[!full_vector %in% searched_vector | duplicated(full_vector)]
Original Answer: here I write a little function for this:
exclude_val<-function(full_vector,searched_vector){
found=c()
for(i in full_vector){
if(any(is.element(searched_vector,i))){
searched_vector[(which(searched_vector==i))[1]]=NA
}
else{
found=c(found,i)
}
}
return(found)
}
so, let's say full_vector=c(1,2,3,4,1)
and searched_vector=c(1,2,3)
.
exclude_val(full_vector,searched_vector)
will return (4,1), however above answers will return just (4)
.
Python lacks the tail recursion optimizations common in functional languages like lisp. In Python, recursion is limited to 999 calls (see sys.getrecursionlimit).
If 999 depth is more than you are expecting, check if the implementation lacks a condition that stops recursion, or if this test may be wrong for some cases.
I dare to say that in Python, pure recursive algorithm implementations are not correct/safe. A fib() implementation limited to 999 is not really correct. It is always possible to convert recursive into iterative, and doing so is trivial.
It is not reached often because in many recursive algorithms the depth tend to be logarithmic. If it is not the case with your algorithm and you expect recursion deeper than 999 calls you have two options:
1) You can change the recursion limit with sys.setrecursionlimit(n)
until the maximum allowed for your platform:
sys.setrecursionlimit(limit)
:Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python.
The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.
2) You can try to convert the algorithm from recursive to iterative. If recursion depth is bigger than allowed by your platform, it is the only way to fix the problem. There are step by step instructions on the Internet and it should be a straightforward operation for someone with some CS education. If you are having trouble with that, post a new question so we can help.
Onur Güzel provides the solution in his blog post, "Uninstall Python Package from OS X.
You should type the following commands into the terminal:
sudo rm -rf /Library/Frameworks/Python.framework
cd /usr/local/bin
ls -l . | grep '../Library/Frameworks/Python.framework' | awk '{print $9}' | xargs sudo rm
sudo rm -rf "/Applications/Python x.y"
where command x.y is the version of Python installed. According to your question, it should be 2.7.
In Onur's words:
WARNING: This commands will remove all Python versions installed with packages. Python provided from the system will not be affected.
If you have more than 1 Python version installed from python.org, then run the fourth command again, changing "x.y" for each version of Python that is to be uninstalled.
function mydump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') {
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') {
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += mydump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else {
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
This should do the trick:
$($.parseJSON(data.msg)).map(function () {
return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');
Here's the distinction between ajax
and getJSON
(from the jQuery documentation):
[getJSON] is a shorthand Ajax function, which is equivalent to:
$.ajax({ url: url, dataType: 'json', data: data, success: callback });
EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:
{
"msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}
...So that msg
property needed to be parsed manually using $.parseJSON()
.
Like this:
var str = 'blah blah blah';
str += ' blah';
str += ' ' + 'and some more blah';
Try to set response dataType property directly:
dataType: 'text'
and put
die('');
in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.
Restoring a Database from Backup
sql-server-->connect to instance-->Databases-->right-click on databases-->Restore
DataBase..-->Device-->Add-->choose the path_filename(.bak)-->click OK
Make sure objects aren't null
.
Having obj1
and obj2
:
if(obj1 == null )
{
return false;
}
return obj1.Equals( obj2 );
Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).
>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)
Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get
>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160
There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.
If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).
you must compile the file with c++11 support
g++ -std=c++0x -o test example.cpp
The September 4th release for 3.7 recommends the following:
conda install python=3.7 anaconda=custom
If you want to create a new environment, they recommend:
conda create -n example_env numpy scipy pandas scikit-learn notebook
anaconda-navigator
conda activate example_env
In Codeignitor version 3.0.x the system/core/Codeigniter.php do not contain the time constraint as well as inserting
ini_set('MAX_EXECUTION_TIME', -1);
will not work since codeignitor will override that with its own function set_time_limit() . So either you have to delete that function from codeignitor or simply you can insert
set_time_limit('1000');
in the beginning of the php file if you wanna change that to 1000 seconds. Set the time to 0 (zero) if you want to run it as long as it want.
&
is bitwise.
&&
is logical.
&
evaluates both sides of the operation.
&&
evaluates the left side of the operation, if it's true
, it continues and evaluates the right side.
For others facing a similar problem to mine, where you know a particular object property cannot be null, you can use the non-null assertion operator (!) after the item in question. This was my code:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci.certificateStatus = "TRUE";
break;
default:
dataToSend.naci.certificateStatus = "";
}
}
And because dataToSend.naci
cannot be undefined in the switch statement, the code can be updated to include exclamation marks as follows:
const naciStatus = dataToSend.naci?.statusNACI;
if (typeof naciStatus != "undefined") {
switch (naciStatus) {
case "AP":
dataToSend.naci!.certificateStatus = "FALSE";
break;
case "AS":
case "WR":
dataToSend.naci!.certificateStatus = "TRUE";
break;
default:
dataToSend.naci!.certificateStatus = "";
}
}
For those who don't want to use curl:
//url
$url = 'some_url';
//Credentials
$client_id = "";
$client_pass= "";
//HTTP options
$opts = array('http' =>
array(
'method' => 'POST',
'header' => array ('Content-type: application/json', 'Authorization: Basic '.base64_encode("$client_id:$client_pass")),
'content' => "some_content"
)
);
//Do request
$context = stream_context_create($opts);
$json = file_get_contents($url, false, $context);
$result = json_decode($json, true);
if(json_last_error() != JSON_ERROR_NONE){
return null;
}
print_r($result);
abarnert
's answer is very good and pythonic. Another completely different route (not in python) is to let bash do this for you:
$ python myscript.py > myoutput.txt
This works in general to put all the output of a cli program (python, perl, php, java, binary, or whatever) into a file, see How to save entire output of bash script to file for more.
There is one issue with the top voted answer here which recommends this regex:
/^[a-z ,.'-]+$/i
It takes spaces only as a valid name!
The best solution in my opinion is to add a negative look forward to the beginning:
^(?!\s)([a-z ,.'-]+)$/i
For API 23+ you need to request the read/write permissions even if they are already in your manifest.
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You can reset your branch to the state it was in just before the merge if you find the commit it was on then.
One way is to use git reflog
, it will list all the HEADs you've had.
I find that git reflog --relative-date
is very useful as it shows how long ago each change happened.
Once you find that commit just do a git reset --hard <commit id>
and your branch will be as it was before.
If you have SourceTree, you can look up the <commit id>
there if git reflog
is too overwhelming.
if it doesnt exist load default image or handle error
$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
if (status == "error")
$(this).attr('src', 'images/DEFAULT.JPG');
else
$(this).attr('src', imgurl);
});
it depends on how you trigger the event. the key you are looking is textbox.clientid.
x.aspx code
<script type="text/javascript">
function disable_textbox(tid) {
var mytextbox = document.getElementById(tid);
mytextbox.disabled=false
}
</script>
code behind x.aspx.cs
string frameScript = "<script language='javascript'>" + "disable_textbox(" + tx.ClientID ");</script>";
Page.ClientScript.RegisterStartupScript(Page.GetType(), "FrameScript", frameScript);
Your id will be passed through as #1, #2 etc. However, # is not valid as an ID (CSS selectors prefix IDs with #).
SqlConnection c = new SqlConnection(@"Data Source=localhost;
Initial Catalog=Northwind; Integrated Security=True");
Prerequisites: You already have the service and published WSDL file, and you want to call your web service from C# client application.
There are 2 main way of doing this:
A) ASP.NET services, which is old way of doing SOA
B) WCF, as John suggested, which is the latest framework from MS and provides many protocols, including open and MS proprietary ones.
The simplest way is to generate proxy classes in C# application (this process is called adding service reference).
A dialog should appear shown in screenshot below. Enter the url of your wsdl file and hit Ok. Note that if you'll receive error message after hitting ok, try removing ?wsdl part from url.
I'm using http://www.dneonline.com/calculator.asmx?WSDL as an example
Expand Service References in Solution Explorer and double click CalculatorServiceReference
(or whatever you named the named the service in the previous step).
You should see generated proxy class name and namespace.
In my case, the namespace is SoapClient.CalculatorServiceReference
, the name of proxy class is CalculatorSoapClient
. As I said above, class names may vary in your case.
Go to your C# source code and add the following
using WindowsFormsApplication1.ServiceReference1
Now you can call the service this way.
Service1Client service = new Service1Client();
int year = service.getCurrentYear();
Hope this helps. If you encounter any problems, let us know.
Search for
or only nbsp
- did you try this?
If you use Laravel and want to use Carbon the correct solution would be the following:
$start_date = Carbon::createFromFormat('Y-m-d', '2020-01-01');
$end_date = Carbon::createFromFormat('Y-m-d', '2020-01-31');
$period = new CarbonPeriod($start_date, '1 day', $end_date);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d H:i:s\n");
}
Remember to add:
EDIT: better yet, do it like that:
var filteredProjects =
projects.Where(p => filteredTags.All(tag => p.Tags.Contains(tag)));
EDIT2: Honestly, I don't know which one is better, so if performance is not critical, choose the one you think is more readable. If it is, you'll have to benchmark it somehow.
Probably Intersect
is the way to go:
void Main()
{
var projects = new List<Project>();
projects.Add(new Project { Name = "Project1", Tags = new int[] { 2, 5, 3, 1 } });
projects.Add(new Project { Name = "Project2", Tags = new int[] { 1, 4, 7 } });
projects.Add(new Project { Name = "Project3", Tags = new int[] { 1, 7, 12, 3 } });
var filteredTags = new int []{ 1, 3 };
var filteredProjects = projects.Where(p => p.Tags.Intersect(filteredTags).Count() == filteredTags.Length);
}
class Project {
public string Name;
public int[] Tags;
}
Although that seems a little ugly at first. You may first apply Distinct
to filteredTags
if you aren't sure whether they are all unique in the list, otherwise the counts comparison won't work as expected.
I think this will work perfectly. I used the same:
For Android Studio:
In my case after files with names containing those characters were uploaded, they were not even visible with Filezilla! In Cpanel filemanager they were shown with ? (under black background). And this combination made it shown correctly on the browser (HTML document is Western-encoded):
$dspFileName = utf8_decode(htmlspecialchars(iconv(mb_internal_encoding(), 'utf-8', basename($thisFile['path']))) );
This question has already been answered, but for some extra information at the time of Swift 4:
In case of performance, you should reserve memory for the array, in case of dynamically creating it, such as adding elements with Array.append()
.
var array = [SKSpriteNode]()
array.reserveCapacity(64)
for _ in 0..<64 {
array.append(SKSpriteNode())
}
If you know the minimum amount of elements you'll add to it, but not the maximum amount, you should rather use array.reserveCapacity(minimumCapacity: 64)
.
In Python 3.x, 5 / 2
will return 2.5
and 5 // 2
will return 2
. The former is floating point division, and the latter is floor division, sometimes also called integer division.
In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division
, which causes Python 2.x to adopt the 3.x behavior.
Regardless of the future import, 5.0 // 2
will return 2.0
since that's the floor division result of the operation.
You can find a detailed description at https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator
Warning: This solution is deprecated since Angular 5.5, please refer to Trent's answer below
=====================
Yes, you need to import the operator:
import 'rxjs/add/operator/catch';
Or import Observable
this way:
import {Observable} from 'rxjs/Rx';
But in this case, you import all operators.
See this question for more details:
In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.
If you guys see any issues with this please let me know and I'll fix it (etc. etc.)
Save it in a file called git-rm-ntb
(call it whatever) on PATH
and run:
git-rm-ntb <remote1:optional> <remote2:optional> ...
clean()
{
REMOTES="$@";
if [ -z "$REMOTES" ]; then
REMOTES=$(git remote);
fi
REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
RBRANCHES=()
while read REMOTE; do
CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
done < <(echo "$REMOTES" )
[[ $RBRANCHES ]] || exit
LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
for i in "${LBRANCHES[@]}"; do
skip=
for j in "${RBRANCHES[@]}"; do
[[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
done
[[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
done
}
clean $@
As for ERRORCODE 39, you can definately just delete the physical table files on the disk. the location depends on your OS distribution and setup. On Debian its typically under /var/lib/mysql/database_name/ So do a:
rm -f /var/lib/mysql/<database_name>/
And then drop the database from your tool of choice or using the command:
DROP DATABASE <database_name>
A DataTable or DataSet object will have a Select Method that will return a DataRow array of results based on the query passed in as it's parameter.
Looking at your requirement your filterexpression will have to be somewhat general to make this work.
myDataTable.Select("columnName1 like '%" + value + "%'");
This is my solution. From my point of view, you can not bypass the <a>
.
function export2json() {_x000D_
const data = {_x000D_
a: '111',_x000D_
b: '222',_x000D_
c: '333'_x000D_
};_x000D_
const a = document.createElement("a");_x000D_
a.href = URL.createObjectURL(_x000D_
new Blob([JSON.stringify(data, null, 2)], {_x000D_
type: "application/json"_x000D_
})_x000D_
);_x000D_
a.setAttribute("download", "data.json");_x000D_
document.body.appendChild(a);_x000D_
a.click();_x000D_
document.body.removeChild(a);_x000D_
}
_x000D_
<button onclick="export2json()">Export data to json file</button>
_x000D_
I tested each of the above methods for finding if any alphabets are contained in a given string and found out average processing time per string on a standard computer.
~250 ns for
import re
~3 µs for
re.search('[a-zA-Z]', string)
~6 µs for
any(c.isalpha() for c in string)
~850 ns for
string.upper().isupper()
Opposite to as alleged, importing re takes negligible time, and searching with re takes just about half time as compared to iterating isalpha() even for a relatively small string.
Hence for larger strings and greater counts, re would be significantly more efficient.
But converting string to a case and checking case (i.e. any of upper().isupper() or lower().islower() ) wins here. In every loop it is significantly faster than re.search() and it doesn't even require any additional imports.
Let me point out an extremely interesting method of calculating an inverse square root 1/sqrt(x) which is a legend in the world of game design because it is mind-boggingly fast. Or wait, read the following post:
http://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/
PS: I know you just want the square root but the elegance of quake overcame all resistance on my part :)
By the way, the above mentioned article also talks about the boring Newton-Raphson approximation somewhere.
Got the same problem when removing item from table(ParentTable) that was referenced by another 2 tables foreign keys with ON DELETE CASCADE rule(RefTable1, RefTable2). The problem appears because of "AFTER DELETE" trigger at one of referencing tables(RefTable1). This trigger was removing related record from ParentTable as result RefTable2 record was removed too. It appears that Entity Framework, while in-code was explicitly set to remove ParentTable record, was removing related record from RefTable1 and then record from RefTable2 after latter operation this exception was thrown because trigger already removed record from ParentTable which as results removed RefTable2 record.
If you submit the form via Javascript (i.e. formElement.submit()
or anything equivalent), then none of the submit buttons are considered successful and none of their values are included in the submitted data. (Note that if you submit the form by using submitElement.click()
then the submit that you had a reference to is considered active; this doesn't really fall under the remit of your question since here the submit button is unambiguous but I thought I'd include it for people who read the first part and wonder how to make a submit button successful via JS form submission. Of course, the form's onsubmit handlers will still fire this way whereas they wouldn't via form.submit()
so that's another kettle of fish...)
If the form is submitted by hitting Enter while in a non-textarea field, then it's actually down to the user agent to decide what it wants here. The specs don't say anything about submitting a form using the enter key while in a text entry field (if you tab to a button and activate it using space or whatever, then there's no problem as that specific submit button is unambiguously used). All it says is that a form must be submitted when a submit button is activated, it's not even a requirement that hitting enter in e.g. a text input will submit the form.
I believe that Internet Explorer chooses the submit button that appears first in the source; I have a feeling that Firefox and Opera choose the button with the lowest tabindex, falling back to the first defined if nothing else is defined. There's also some complications regarding whether the submits have a non-default value attribute IIRC.
The point to take away is that there is no defined standard for what happens here and it's entirely at the whim of the browser - so as far as possible in whatever you're doing, try to avoid relying on any particular behaviour. If you really must know, you can probably find out the behaviour of the various browser versions but when I investigated this a while back there were some quite convoluted conditions (which of course are subject to change with new browser versions) and I'd advise you to avoid it if possible!
From the standpoint of a Checkpoint firewall, you will see a message from the firewall if you actually choose Reject as an Action thereby exposing to a propective attacker the presence of a firewall in front of the server. The firewall will silently drop all connections that doesn't match the policy. Connection refused almost always comes from the server
If you've tried all the solutions above and still doesn't resolve your issue.
This might not seemed related, but here's my take on it.
Try removing this from your Gradle dependency, I've spend 2 hours of my time because of this roadblock.
implementation "com.squareup.retrofit2:adapter-rxjava2:2.3.0"
If you're using Django you can use this. Yes i'm aware OP did not ask for django, but i ran across this question looking for a Django solution, didn't find one, and put it here for the next boy/gal that looks for it.
# It's available for v1.7+
# https://github.com/django/django/blob/stable/1.7.x/django/utils/module_loading.py
from django.utils.module_loading import import_string
Klass = import_string('path.to.module.Klass')
func = import_string('path.to.module.func')
var = import_string('path.to.module.var')
Keep in mind, if you want to import something that doesn't have a .
, like re
or argparse
use:
re = __import__('re')
CSS is designed to describe the presentation of documents. It has a few features for changing that presentation in reaction to user interaction (primarily :hover
for indicating that you are now pointing at something interactive).
Making something draggable isn't a simple matter of presentation. It is firmly in the territory of interactivity logic, which is handled by JavaScript.
What you want is not achievable.
You don't need all that code. All you need are the following lines:
<a href="https://www.facebook.com/sharer/sharer.php?u=example.org" target="_blank">
Share on Facebook
</a>
Documentation can be found at https://developers.facebook.com/docs/reference/plugins/share-links/
There is another way...
header('Content-Type: text/plain; charset=utf-8');
This makes the whole page served as plain text... better is htmlspecialchars...
Hope this helps...
passing variable from one function as argument to other functions can be done like this
define functions like this
def function1(): global a a=input("Enter any number\t") def function2(argument): print ("this is the entered number - ",argument)
call the functions like this
function1()
function2(a)
import image from './img/one.jpg';
class Icons extends React.Component{
render(){
return(
<img className='profile-image' alt='icon' src={image}/>
);
}
}
export default Icons;
it "should call 'bar' with appropriate arguments" do
expect(subject).to receive(:bar).with("an argument I want")
subject.foo
end
not sure if that's what you need but try this in ruby console:
h = Hash.new
h["name"] = "test"
h["post_number"] = 20
h["active"] = true
h
obviously it will return you a hash in console. if you want to return a hash from within a method - instead of just "h" try using "return h.inspect", something similar to:
def wordcount(str)
h = Hash.new()
str.split.each do |key|
if h[key] == nil
h[key] = 1
else
h[key] = h[key] + 1
end
end
return h.inspect
end
You can use tree to generate something very similar to your example. Once you have the output, you can wrap it in a <pre>
tag to preserve the plain text formatting.
One workaround, though not a great one, is to use the new @facebook.com email address. There are a few downsides to this:
1) Not everyone (as of this posting) has the new messages application enabled in their account.
2) Not everyone will have setup their @facebook.com email in their messages app.
3) Not everyone will choose their username (if they even have a facebook username) as their email address.
cmd.Parameters.Add(String parameterName, Object value)
is deprecated now. Instead use cmd.Parameters.AddWithValue(String parameterName, Object value)
There is no difference in terms of functionality. The reason they deprecated the
cmd.Parameters.Add(String parameterName, Object value)
in favor ofAddWithValue(String parameterName, Object value)
is to give more clarity. Here is the MSDN reference for the same
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.AddWithValue("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
You can do two things here either move the onSubmit attribute to the form tag, or change the onSubmit event to an onCLick event.
Option 1
<form name="loginform" onSubmit="return validateForm();">
Option 2
<input type="submit" value="Login" onClick="return validateForm();" />
$.getJSON("example.json", function() {_x000D_
alert("success");_x000D_
})_x000D_
.success(function() { alert("second success"); })_x000D_
.error(function() { alert("error"); })
_x000D_
It is fixed in jQuery 2.x; In jQuery 1.x you will never get an error callback