If you're using django REST framework, you can use the reverse function from rest_framework.reverse
. This has the same behavior as django.core.urlresolvers.reverse
, except that it uses a request parameter to build a full URL.
from rest_framework.reverse import reverse
# returns the full url
url = reverse('view_name', args=(obj.pk,), request=request)
# returns only the relative url
url = reverse('view_name', args=(obj.pk,))
Edited to mention availability only in REST framework
You can use Linq. Something like:
bool exists = dt.AsEnumerable().Where(c => c.Field<string>("Author").Equals("your lookup value")).Count() > 0;
in Windows, you can use the runas command. For linux users, there are some alternatives for sudo in windows, you can check this out
http://helpdeskgeek.com/free-tools-review/5-windows-alternatives-linux-sudo-command/
From XML.com:
Like xsl:if instructions, xsl:when elements can have more elaborate contents between their start- and end-tags—for example, literal result elements, xsl:element elements, or even xsl:if and xsl:choose elements—to add to the result tree. Their test expressions can also use all the tricks and operators that the xsl:if element's test attribute can use, such as and, or, and function calls, to build more complex boolean expressions.
You can use the typeid operator:
#include <typeinfo>
...
cout << typeid(variable).name() << endl;
For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).
The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.
ReactJs defines the following synthetic events for mouse events:
onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp
As you can see there is no hover event, because browsers do not define a hover event natively.
You will want to add handlers for onMouseEnter and onMouseLeave for hover behavior.
If you are matching the full value of the field use
WHERE UPPER(fieldName) = 'ANGEL'
EDIT: From your comment you want to use:
SELECT
RPAD(a.name, 10,'=') "Nombre del Cliente"
, RPAD(b.name, 12,'*') "Nombre del Consumidor"
FROM
s_customer a,
s_region b
WHERE
a.region_id = b.id
AND UPPER(a.name) LIKE '%SPORT%'
"use strict";
Basically it enables the strict mode.
Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.
As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.
So, there will be no major difference how "use strict";
is interpreted by the Chrome browser and Node.js.
Please read what is strict mode in JavaScript.
For more information:
ECMAScript 6 Code & strict mode. Following is brief from the specification:
10.2.1 Strict Mode Code
An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:
- Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
- Module code is always strict mode code.
- All parts of a ClassDeclaration or a ClassExpression are strict mode code.
- Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
- Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
- Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.
Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).
You need to call $compile
on the HTML string before inserting it into the DOM so that angular gets a chance to perform the binding.
In your fiddle, it would look something like this.
$("#dynamicContent").html(
$compile(
"<button ng-click='count = count + 1' ng-init='count=0'>Increment</button><span>count: {{count}} </span>"
)(scope)
);
Obviously, $compile
must be injected into your controller for this to work.
Read more in the $compile
documentation.
Spent a while on this issue, and the PATH switch wasn't helping. My problem was the Homebrew/node/npm bug found here - https://github.com/npm/npm/issues/3794
If you've already installed node using Homebrew, try ****Note per comments that this might not be safe. It worked for me but could have unintended consequences. It also appears that latest version of Homebrew properly installs npm. So likely I would try brew update
, brew doctor
, brew upgrade node
etc before trying****:
npm update -gf
Or, if you want to install node with Homebrew and have npm work, use:
brew install node --without-npm
curl -L https://npmjs.org/install.sh | sh
The use of @Qualifier will solve the issue.
Explained as below example :
public interface PersonType {} // MasterInterface
@Component(value="1.2")
public class Person implements PersonType { //Bean implementing the interface
@Qualifier("1.2")
public void setPerson(PersonType person) {
this.person = person;
}
}
@Component(value="1.5")
public class NewPerson implements PersonType {
@Qualifier("1.5")
public void setNewPerson(PersonType newPerson) {
this.newPerson = newPerson;
}
}
Now get the application context object in any component class :
Object obj= BeanFactoryAnnotationUtils.qualifiedBeanOfType((ctx).getAutowireCapableBeanFactory(), PersonType.class, type);//type is the qualifier id
you can the object of class of which qualifier id is passed.
This snippet is from working code.
You can trigger bat file not only from Windows GUI or Task Scheduler, but directly from PHP script when you need it. But in most cases it will have execution for 30-60 sec. depending from your PHP configuration. If job in BAT file is long and you don't want to freeze your PHP scripts, you need to fork BAT job as another process using php.exe
and not be dependable from Apache.
This runs in background mode in Windows, seen as separate processes cmd.exe
and php.exe
from Task Manager not halting your Apache PHP scripts. The messages produced by your script may be stored and retrieved back via log files.
In my case in file_scanner.php
I do some heavy calculations in loop for big array of files which may last for few hours with php function sleep()
not to overload CPU.
The success poiner result from file $r
which you can query via ajax if you want to know success or fauty start. In my case file_scanner.php
writes log file with messages somefile.jpg - OK
wich you can load to your UI with AJAX every few seconds to show progress.
PHP
/**
* Runs bat file in background mode
*
*/
function run_scanner() {
$c='start /b D:\Web\example.com\tasks\file_scanner.bat';
$r=pclose(popen($c, 'r'));
return json_encode(array('result'=>$r));
}
BAT
@echo Off
D:\PHP\php.exe D:\Web\example.com\tasks\file_scanner.php > D:\Web\example.com\tasks\file_scanner.log
exit
I know this is an old thread but an easier solution would be to embed an input within the label like so:
<label>Label one: <input id="input1" type="text"></label>
_x000D_
Assuming C++11, here is a one-liner loop body, if this is consistent with your programming style:
using Map = std::map<K,V>;
Map map;
// Erase members that satisfy needs_removing(itr)
for (Map::const_iterator itr = map.cbegin() ; itr != map.cend() ; )
itr = needs_removing(itr) ? map.erase(itr) : std::next(itr);
A couple of other minor style changes:
Map::const_iterator
) when possible/convenient, over using auto
.using
for template types, to make ancillary types (Map::const_iterator
) easier to read/maintain.This:
print "\n"
is printing out two \n
characters -- the one you tell it to, and the one that Python prints out at the end of any line which doesn't end with a ,
like you use in print a,
. Simply use
print
instead.
To get the address of p do:
int **pp = &p;
and you can go on:
int ***ppp = &pp;
int ****pppp = &ppp;
...
or, only in C++11, you can do:
auto pp = std::addressof(p);
To print the address in C, most compilers support %p
, so you can simply do:
printf("addr: %p", pp);
otherwise you need to cast it (assuming a 32 bit platform)
printf("addr: 0x%u", (unsigned)pp);
In C++ you can do:
cout << "addr: " << pp;
Use of pseudo-element as suggested by Terry has one PRO and one CON:
Anyway is a great solution.
OTHER SOLUTIONS:
If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:
outline
property combined with border
and a single inset box-shadow
box-shadow
combined with border
.Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border
class):
.left
{
outline: 4px solid #fff;
box-shadow:inset 0 0 0 4px #fff;
}
.right
{
box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}
LESS code:
You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.
Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):
@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;
.double-border
{
background-color: @content-color;
border: @double-border-size solid @content-color;
padding: 2em;
width: 16em;
height: 16em;
float:left;
margin-right:20px;
text-align:center;
}
.left
{
outline: @double-border-size solid @inset-border-color;
box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}
.right
{
box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}
Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.
import React from 'react';
import { Link } from 'react-router';
export default class Nav extends React.Component {
render() {
return (
<nav className="Nav">
<div className="Nav__container">
<Link to="/" className="Nav__brand">
<img src="logo.svg" className="Nav__logo" />
</Link>
<div className="Nav__right">
<ul className="Nav__item-wrapper">
<li className="Nav__item">
<Link className="Nav__link" to="/path1">Link 1</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path2">Link 2</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path3">Link 3</Link>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<div>
<Nav />
<Switch>
<Route exactly component={Landing} pattern="/" />
<Route exactly component={Page1} pattern="/path1" />
<Route exactly component={Page2} pattern="/path2" />
<Route exactly component={Page3} pattern="/path3" />
<Route component={Page404} />
</Switch>
</div>
</Router>
</div>
);
}
}
Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar
A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
const NavRoute = ({exact, path, component: Component}) => (
<Route exact={exact} path={path} render={(props) => (
<div>
<Header/>
<Component {...props}/>
</div>
)}/>
)
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<Switch>
<NavRoute exactly component={Landing} pattern="/" />
<Route exactly component={Login} pattern="/login" />
<NavRoute exactly component={Page1} pattern="/path1" />
<NavRoute exactly component={Page2} pattern="/path2" />
<NavRoute component={Page404} />
</Switch>
</Router>
</div>
);
}
}
You should write textcolor in xml as
android:textColor="@color/text_color"
or
android:textColor="#FFFFFF"
You can stash
(save the changes in temporary box) then, back to master
branch HEAD.
$ git add .
$ git stash
$ git checkout master
Jump Over Commits Back and Forth:
Go to a specific commit-sha
.
$ git checkout <commit-sha>
If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.
# checkout a new branch, add, commit, push
$ git checkout -b <branch-name>
$ git add .
$ git commit -m 'Commit message'
$ git push origin HEAD # push the current branch to remote
$ git checkout master # back to master branch now
If you have changes in the specific commit and don't want to keep the changes, you can do stash
or reset
then checkout to master
(or, any other branch).
# stash
$ git add -A
$ git stash
$ git checkout master
# reset
$ git reset --hard HEAD
$ git checkout master
After checking out a specific commit if you have no uncommitted change(s) then, just back to master
or other
branch.
$ git status # see the changes
$ git checkout master
# or, shortcut
$ git checkout - # back to the previous state
I was searching for days for this command.
This worked for me outside any session or somthing like this.
# you get an array = your tensor.eval(session=tf.compat.v1.Session())
an_array = a_tensor.eval(session=tf.compat.v1.Session())
https://kite.com/python/answers/how-to-convert-a-tensorflow-tensor-to-a-numpy-array-in-python
[class*="test"],[class="second"] {
background: #ffff00;
}
Heads up, if clearing the settings doesn't fix your issue you may need to uninstall the extensions as well.
public int factorial(int num) {
if (num == 1) return 1;
return num * factorial(num - 1);
}
If you want to change the format for all dates you can add a builder customizer. Here is an example of a bean that converts dates to ISO 8601:
@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder builder) {
builder.dateFormat(new ISO8601DateFormat());
}
};
}
Maintain a set
and remove a randomly picked-up element (with choice
) until the list is empty:
s = set(range(1, 6))
import random
while len(s) > 0:
s.remove(random.choice(list(s)))
print(s)
Three runs give three different answers:
>>>
set([1, 3, 4, 5])
set([3, 4, 5])
set([3, 4])
set([4])
set([])
>>>
set([1, 2, 3, 5])
set([2, 3, 5])
set([2, 3])
set([2])
set([])
>>>
set([1, 2, 3, 5])
set([1, 2, 3])
set([1, 2])
set([1])
set([])
I've had this happen on VS after I changed the file's line endings. Changing them back to Windows CR LF fixed the issue.
You should set a fixed value to your span's line-height
property:
.float, .twoline {
line-height: 100px;
}
you can convert a string to array with str_split and use foreach
$chars = str_split($str);
foreach($chars as $char){
// your code
}
For my projects I made this solution (RecyclerView
with setEmptyView
method):
public class RecyclerViewEmptySupport extends RecyclerView {
private View emptyView;
private AdapterDataObserver emptyObserver = new AdapterDataObserver() {
@Override
public void onChanged() {
Adapter<?> adapter = getAdapter();
if(adapter != null && emptyView != null) {
if(adapter.getItemCount() == 0) {
emptyView.setVisibility(View.VISIBLE);
RecyclerViewEmptySupport.this.setVisibility(View.GONE);
}
else {
emptyView.setVisibility(View.GONE);
RecyclerViewEmptySupport.this.setVisibility(View.VISIBLE);
}
}
}
};
public RecyclerViewEmptySupport(Context context) {
super(context);
}
public RecyclerViewEmptySupport(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RecyclerViewEmptySupport(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void setAdapter(Adapter adapter) {
super.setAdapter(adapter);
if(adapter != null) {
adapter.registerAdapterDataObserver(emptyObserver);
}
emptyObserver.onChanged();
}
public void setEmptyView(View emptyView) {
this.emptyView = emptyView;
}
}
And you should use it instead of RecyclerView
class:
<com.maff.utils.RecyclerViewEmptySupport android:id="@+id/list1"
android:layout_height="match_parent"
android:layout_width="match_parent"
/>
<TextView android:id="@+id/list_empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Empty"
/>
and
RecyclerViewEmptySupport list =
(RecyclerViewEmptySupport)rootView.findViewById(R.id.list1);
list.setLayoutManager(new LinearLayoutManager(context));
list.setEmptyView(rootView.findViewById(R.id.list_empty));
There's no need to start idle transactions on the master. In postgresql-9.1 the most direct way to solve this problem is by setting
hot_standby_feedback = on
This will make the master aware of long-running queries. From the docs:
The first option is to set the parameter hot_standby_feedback, which prevents VACUUM from removing recently-dead rows and so cleanup conflicts do not occur.
Why isn't this the default? This parameter was added after the initial implementation and it's the only way that a standby can affect a master.
Extract all gz files in current directory and its subdirectories:
find . -name "*.gz" | xargs gunzip
I've installed MySQL using installer. In fact, there was no data directory alongside 'bin' directory.
So, I manually created the 'data' directory under "C:\Program Files\MySQL\MySQL Server 8.0". And it worked (changing the root password following steps suggested on https://dev.mysql.com/doc/mysql-windows-excerpt/5.7/en/resetting-permissions-windows.html.
For CSS, I found that max height of 180 is better for mobile phones landscape 320 when showing browser chrome.
.scrollable-menu {
height: auto;
max-height: 180px;
overflow-x: hidden;
}
Also, to add visible scrollbars, this CSS should do the trick:
.scrollable-menu::-webkit-scrollbar {
-webkit-appearance: none;
width: 4px;
}
.scrollable-menu::-webkit-scrollbar-thumb {
border-radius: 3px;
background-color: lightgray;
-webkit-box-shadow: 0 0 1px rgba(255,255,255,.75);
}
The changes are reflected here: https://www.bootply.com/BhkCKFEELL
Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.
<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>
<script>
document.getElementById('click').addEventListener('click', function(){
doStuff();
});
function doStuff() {
for(var i=1; i<=2; i++){
var el = document.getElementById("hello" + i);
el.style.display = 'none';
}
}
</script>
Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.
Long time since I've done Assembly programming, but this link might be useful...
The processor has a collection of registers which are used to store data. Some of these are direct values while others are pointing to an area within RAM. Registers do tend to be used for certain specific actions and every operand in assembly will require a certain amount of data in specific registers.
The stack pointer is mostly used when you're calling other procedures. With modern compilers, a bunch of data will be dumped first on the stack, followed by the return address so the system will know where to return once it's told to return. The stack pointer will point at the next location where new data can be pushed to the stack, where it will stay until it's popped back again.
Base registers or segment registers just point to the address space of a large amount of data. Combined with a second regiser, the Base pointer will divide the memory in huge blocks while the second register will point at an item within this block. Base pointers therefor point to the base of blocks of data.
Do keep in mind that Assembly is very CPU specific. The page I've linked to provides information about different types of CPU's.
class MaxHeap:
def __init__(self, items=[]):
self.heap = [0]
self.items = items
for item in items:
self.heap.append(item)
self.__floatUp(len(self.heap)-1)
"""
self.heap = [0] heap index stars form 1
self.heap.append(item) append items from list to heap
append items to it's proper place
"""
def push(self, data):
self.heap.append(data)
self.__floatUp(len(self.heap)-1)
"""
Append data to the end of the list the using float up put it to the proper place
"""
def peek(self):
if self.heap[1]:
return self.heap[1]
else:
return False
"""
To return the first element form list
"""
def pop(self):
if (len(self.heap)) > 2:
self.__swap(1,len(self.heap)-1)
max = self.heap.pop()
self.__bubbleDown(1)
elif (len(self.heap)) == 2:
max = self.heap.pop()
else:
return False
return max
"""
If length is greater than two then swap first and last value as only the last value can be removed from the tree
Place the new first item after removing of the item to its proper place using bubble down
"""
def __swap(self, i, j):
self.heap[i], self.heap[j] = self.heap[j], self.heap[i]
"""
Swap is used in a bubble down and bubble up for proper placing of values is list
"""
def __floatUp(self, index):
parent = index // 2
if index <= 1:
return
elif self.heap[index] > self.heap[parent]:
self.__swap(index, parent)
self.__floatUp(parent)
"""
if value and parents , where parent < value , swap where parent, value = value,parent
After swap again check parent > value == True if false then again continue
"""
def __bubbleDown(self, index):
left = index * 2
right = index * 2 + 1
largest = index
if len(self.heap) > left and self.heap[largest] < self.heap[left]:
largest = left
if len(self.heap) > right and self.heap[largest] < self.heap[right]:
largest = right
if largest != index:
self.__swap(index, largest)
self.__bubbleDown(largest)
"""
self.heap[largest] < self.heap[left] : largest = left
current value and lower left value is bigger largest = left
self.heap[largest] > self.heap[right]
current value and lower value right value if lower right value is bigger than largest value
after getting the largest value we will swap larger value and smaller value and them again check that the current value is
bigger than is down value then again swap space and check again until every node is settled at its the correct place
"""
def __str__(self):
return str(self.heap)
"""
To str representation of the list
"""
m = MaxHeap([95, 3, 21])
m.push(10)
print(m)
print(m.pop())
print(m.peek())
A simple example loading images into the tiles.
import 'package:flutter/material.dart';
void main() {
runApp( MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
color: Colors.white30,
child: GridView.count(
crossAxisCount: 4,
childAspectRatio: 1.0,
padding: const EdgeInsets.all(4.0),
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: <String>[
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
'http://www.for-example.org/img/main/forexamplelogo.png',
].map((String url) {
return GridTile(
child: Image.network(url, fit: BoxFit.cover));
}).toList()),
);
}
}
The Flutter Gallery app contains a real world example, which can be found here.
Check if you have the correct file mentioned in form statement in HTML:
For eg:
form action="insert.php" method="POST">
</form>
when you are in trial.php but instead you give another fileName
Here's an example: App.config
<applicationSettings>
<MyApp.My.MySettings>
<setting name="Printer" serializeAs="String">
<value>1234 </value>
</setting>
</MyApp.My.MySettings>
</applicationSettings>
Dim strPrinterName as string = My.settings.Printer
I don't know about MySQL, but in MS SQL, you can use the column index in the order by
clause. I've done this before when doing counts with group by
s as it tends to be easier to work with.
So
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY COUNT(id) DESC
LIMIT 20
Becomes
SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER 1 DESC
LIMIT 20
No version 2 doesn't actually work but if you want this kind of approach you can do the following (probably not the speediest, but arguably more intuitive):
switch (true) {
case ($var === 'something' || $var === 'something else'):
// do some stuff
break;
}
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash
value in it's name. So problem is this HASH
is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4
here 6AB17FE4
is the hash value(8 bit). So I am referring a single script which will be fruitful to all
DECLARE @Command NVARCHAR(MAX)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'ProcedureAlerts'
set @col_name = N'EmailSent'
select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name) + ']'
--print @Command
exec sp_executesql @Command
It will drop your default constraint. However if you want to create it again you can simply try this
ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
Finally, just simply run a DROP
command to drop the column.
If you are using this for Angular, then export a function via a named export. Such as:
function someFunc(){}
export { someFunc as someFuncName }
otherwise, Angular will complain that object is not a function.
In CakePHP 1.2 ..
$db =& ConnectionManager::getDataSource('default');
$db->showLog();
Open cmd type adb shell
then press enter.
Type ls
to view files list.
Base on accepted answer, I made an extension method to check column exist in table as
I shared for whom concern.
public static class DatatableHelper
{
public static bool ContainColumn(this DataTable table, string columnName)
{
DataColumnCollection columns = table.Columns;
if (columns.Contains(columnName))
{
return true;
}
return false;
}
}
And use as dtTagData.ContainColumn("SystemName")
You've probably fixed this by now but just so this doesn't stay unanswered,
Try adding this to your build.gradle
:
configurations {
all*.exclude group: 'com.android.support', module: 'support-v4'
}
You need to add some style for span6
, smthg like that:
.row-fluid .span6 {
display: table-cell;
vertical-align: bottom;
float: none;
}
and this is your fiddle: http://jsfiddle.net/sgB3T/
#!/bin/bash
process_install()
{
commands...
commands...
}
process_exit()
{
commands...
commands...
}
if [ "$choice" = "true" ] then
process_install
else
process_exit
fi
As you know JBoss is a purely filesystem based installation. To install you simply unzip a file and thats it. Once you install a certain folder structure is created by default and as you run the JBoss instance for the first time, it creates additional folders for runtime operation. For comparison here is the structure of JBoss AS 7 before and after you start for the first time
Before
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
|
|---> domain
|....
After
jboss-as-7
|
|---> standalone
| |----> lib
| |----> configuration
| |----> deployments
| |----> tmp
| |----> data
| |----> log
|
|---> domain
|....
As you can see 3 new folders are created (log, data & tmp). These folders can all be deleted without effecting the application deployed in deployments folder unless your application generated Data that's stored in those folders. In development, its ok to delete all these 3 new folders assuming you don't have any need for the logs and data stored in "data" directory.
For production, ITS NOT RECOMMENDED to delete these folders as there maybe application generated data that stores certain state of the application. For ex, in the data folder, the appserver can save critical Tx rollback logs. So contact your JBoss Administrator if you need to delete those folders for any reason in production.
Good luck!
VideoView myVideo = (VideoView) rootView.findViewById(R.id.definition_video_view);
//Set video name (no extension)
String myVideoName = "my_video";
//Set app package
String myAppPackage = "com.myapp";
//Get video URI from raw directory
Uri myVideoUri = Uri.parse("android.resource://"+myAppPackage+"/raw/"+myVideoName);
//Set the video URI
myVideo.setVideoURI(myVideoUri);
//Play the video
myVideo.start();
Simple answer is that: Go to your console app's properties(project's properties).In the "Application" tab, just change the "Output type" to "Windows Application". That's all.
Default initial capacity of the HashMap
takes is 16 and load factor is 0.75f (i.e 75% of current map size). The load factor represents at what level the HashMap
capacity should be doubled.
For example product of capacity and load factor as 16 * 0.75 = 12
. This represents that after storing the 12th key – value pair into the HashMap
, its capacity becomes 32.
You can use Expressions windows: while debugging, menu window -> Show View -> Expressions, then it has place to type variables of which you need to see contents
I used the following code, it's working!
using System.Data.OleDb;
using System.IO;
using System.Text.RegularExpressions;
private void btopen_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openFileDialog1 = new OpenFileDialog(); //create openfileDialog Object
openFileDialog1.Filter = "XML Files (*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb) |*.xml; *.xls; *.xlsx; *.xlsm; *.xlsb";//open file format define Excel Files(.xls)|*.xls| Excel Files(.xlsx)|*.xlsx|
openFileDialog1.FilterIndex = 3;
openFileDialog1.Multiselect = false; //not allow multiline selection at the file selection level
openFileDialog1.Title = "Open Text File-R13"; //define the name of openfileDialog
openFileDialog1.InitialDirectory = @"Desktop"; //define the initial directory
if (openFileDialog1.ShowDialog() == DialogResult.OK) //executing when file open
{
string pathName = openFileDialog1.FileName;
fileName = System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
DataTable tbContainer = new DataTable();
string strConn = string.Empty;
string sheetName = fileName;
FileInfo file = new FileInfo(pathName);
if (!file.Exists) { throw new Exception("Error, file doesn't exists!"); }
string extension = file.Extension;
switch (extension)
{
case ".xls":
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
case ".xlsx":
strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'";
break;
default:
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'";
break;
}
OleDbConnection cnnxls = new OleDbConnection(strConn);
OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls);
oda.Fill(tbContainer);
dtGrid.DataSource = tbContainer;
}
}
catch (Exception)
{
MessageBox.Show("Error!");
}
}
Do you mean append
?
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x.append(y)
>>> x
[1, 2, 3, [4, 5, 6]]
Or merge?
>>> x = [1,2,3]
>>> y = [4,5,6]
>>> x + y
[1, 2, 3, 4, 5, 6]
>>> x.extend(y)
>>> x
[1, 2, 3, 4, 5, 6]
You can make rounded border with width of border of any control in this way:-
CALayer * l1 = [lblName layer];
[l1 setMasksToBounds:YES];
[l1 setCornerRadius:5.0];
// You can even add a border
[l1 setBorderWidth:5.0];
[l1 setBorderColor:[[UIColor darkGrayColor] CGColor]];
Just replace lblName
with your UILabel
.
Note:- Don't forget to import <QuartzCore/QuartzCore.h>
No need for the specificity .navbar-default
in your CSS. Background color requires background-color:#cc333333
(or just background:#cc3333
). Finally, probably best to consolidate all your customizations into a single class, as below:
.navbar-custom {
color: #FFFFFF;
background-color: #CC3333;
}
..
<div id="menu" class="navbar navbar-default navbar-custom">
Example: http://www.bootply.com/OusJAAvFqR#
In simple terms,
SNS - sends messages to the subscriber using push mechanism and no need of pull.
SQS - it is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components.
A common pattern is to use SNS to publish messages to Amazon SQS queues to reliably send messages to one or many system components asynchronously.
Reference from Amazon SNS FAQs.
Variables in Javascript don't have a type. Non-zero, non-null, non-empty and true
are "true". Zero, null, undefined, empty string and false
are "false".
There's a Boolean type though, as are literals true
and false
.
Well, If you really want to do it in your DB there is a more accurate way as given in MSDN:
SET STATISTICS TIME ON
You can read this information from your application as well.
I ran across this while on a hunt for answers myself after attempting to follow a guide using pm2. The goal is to automatically start a node.js application on a server. Some guides call out using pm2 startup systemd
, which is the path that leads to the question of using systemctl on Ubuntu 14.04. Instead, use pm2 startup ubuntu
.
Just like ASP.NET variant, except put the hidden input with the same name before the actual checkbox (of the same name). Only last values will be sent. This way if a box is checked then its name and value "on" is sent, whereas if it's unchecked then the name of the corresponding hidden input and whatever value you might like to give it will be sent. In the end you will get the $_POST array to read, with all checked and unchecked elements in it, "on" and "false" values, no duplicate keys. Easy to process in PHP.
The problem lies in position: static
. Static means don't do anyting at all with the position. position: absolute
is what you want. Centering the element is still tricky though. The following should work:
#whatever {
position: absolute;
bottom: 0px;
margin-right: auto;
margin-left: auto;
left: 0px;
right: 0px;
}
or
#whatever {
position: absolute;
bottom: 0px;
margin-right: auto;
margin-left: auto;
left: 50%;
transform: translate(-50%, 0);
}
But I recommend the first method. I used centering techniques from this answer: How to center absolutely positioned element in div?
use jQuery's $.getJSON
$.getJSON('mydata.json', function(data) {
//do stuff with your data here
});
According to this: http://www.vistax64.com/vista-installation-setup/33219-regsvr32-error-0x80004005.html
Run it in a elevated command prompt.
Use the -J
compression option for xz
. And remember to man tar
:)
tar cfJ <archive.tar.xz> <files>
Edit 2015-08-10:
If you're passing the arguments to tar
with dashes (ex: tar -cf
as opposed to tar cf
), then the -f
option must come last, since it specifies the filename (thanks to @A-B-B for pointing that out!). In that case, the command looks like:
tar -cJf <archive.tar.xz> <files>
If you want to read that file from inside your application use:
InputStream input = getClass().getResourceAsStream("/classpath/to/my/file");
The path starts with "/", but that is not the path in your file-system, but in your classpath. So if your file is at the classpath "org.xml" and is called myxml.xml your path looks like "/org/xml/myxml.xml".
The InputStream reads the content of your file. You can wrap it into an Reader, if you want.
I hope that helps.
In Spark 2.0 (I didn't tested with earlier versions). Simply:
print myRDD.take(n)
Where n is the number of lines and myRDD is wc in your case.
You use it like this:
SELECT age, name
FROM users
UNION
SELECT 25 AS age, 'Betty' AS name
Use UNION ALL
to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION
.
If any one have any interest on multiple icheck(). Then you can go for it with the below one:
$("#mother_checkbox").on("ifChanged", function(){
if($(this).is(':checked')) {
$('.child_checkbox').prop('checked', true);
$('.child_checkbox').iCheck('update');
}
else{
$('.child_checkbox').prop('checked', false);
$('.child_checkbox').iCheck('update');
}
});
It will Check/Uncheck all the child checkbox. Good Day !
<input type="number" min="1" step="1">
_x000D_
For Windows 7 with NIO 2:
public static void main(String[] args) throws IOException {
Path file = Paths.get("c:/touch.txt");
AclFileAttributeView aclAttr = Files.getFileAttributeView(file, AclFileAttributeView.class);
System.out.println(aclAttr.getOwner());
for (AclEntry aclEntry : aclAttr.getAcl()) {
System.out.println(aclEntry);
}
System.out.println();
UserPrincipalLookupService upls = file.getFileSystem().getUserPrincipalLookupService();
UserPrincipal user = upls.lookupPrincipalByName(System.getProperty("user.name"));
AclEntry.Builder builder = AclEntry.newBuilder();
builder.setPermissions( EnumSet.of(AclEntryPermission.READ_DATA, AclEntryPermission.EXECUTE,
AclEntryPermission.READ_ACL, AclEntryPermission.READ_ATTRIBUTES, AclEntryPermission.READ_NAMED_ATTRS,
AclEntryPermission.WRITE_ACL, AclEntryPermission.DELETE
));
builder.setPrincipal(user);
builder.setType(AclEntryType.ALLOW);
aclAttr.setAcl(Collections.singletonList(builder.build()));
}
JQuery 10.1.2 has a nice show and hide functions that encapsulate the behavior you are talking about. This would save you having to write a new function or keep track of css classes.
$("tr1").show();
$("tr1").hide();
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String dateInString = "07/06/2013";
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatter.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
Output:
2014/08/06 16:06:54
2014/08/06 16:06:54
which theme you have used in activity add below one line code
for white
<style name="AppTheme.NoActionBar">
<item name="android:tint">#ffffff</item>
</style>
or
<style name="AppThemeName" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:tint">#ffffff</item>
</style>
for black
<style name="AppTheme.NoActionBar">
<item name="android:tint">#000000</item>
</style>
or
<style name="AppThemeName" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:tint">#000000</item>
</style>
I got here with a bit more general problem - I wanted to find files in directories matching pattern but not in their subdirectories.
My solution (assuming we're looking for all cpp
files living directly in arch
directories):
find . -path "*/arch/*/*" -prune -o -path "*/arch/*.cpp" -print
I couldn't use maxdepth since it limited search in the first place, and didn't know names of subdirectories that I wanted to exclude.
I have written a node module that provides a wrapper around setInterval using moment durations providing a declarative interface:
npm install every-moment
var every = require('every-moment');
var timer = every(5, 'seconds', function() {
console.log(this.duration);
});
every(2, 'weeks', function() {
console.log(this.duration);
timer.stop();
this.set(1, 'week');
this.start();
});
This is what worked for me:
.pdf::before {
content: url('path/to/image.png');
display: flex;
align-items: center;
justify-content: center;
height: inherit;
}
there is another way wich you don't have to overwrite uibModal classes and use them if needed : you call $uibModal.open function with your own size type like "xlg" and then you define a class named "modal-xlg" like below :
.modal-xlg{
width:1200px;
}
call $uibModal.open as :
var modalInstance = $uibModal.open({
...
size: "xlg",
});
and this will work . because whatever string you pass as size bootstrap will cocant it with "modal-" and this will play the role of class for window.
Ah, got it myselfs.
The quirks and quarks of LINQ-2-entities.
This looks most understandable:
var query2 = (
from users in Repo.T_Benutzer
from mappings in Repo.T_Benutzer_Benutzergruppen
.Where(mapping => mapping.BEBG_BE == users.BE_ID).DefaultIfEmpty()
from groups in Repo.T_Benutzergruppen
.Where(gruppe => gruppe.ID == mappings.BEBG_BG).DefaultIfEmpty()
//where users.BE_Name.Contains(keyword)
// //|| mappings.BEBG_BE.Equals(666)
//|| mappings.BEBG_BE == 666
//|| groups.Name.Contains(keyword)
select new
{
UserId = users.BE_ID
,UserName = users.BE_User
,UserGroupId = mappings.BEBG_BG
,GroupName = groups.Name
}
);
var xy = (query2).ToList();
Remove the .DefaultIfEmpty()
, and you get an inner join.
That was what I was looking for.
If Invalidating caches not helps, just close the project then re-open it. Steps:
EDIT: Bootstrap 3.3.4 has solved this problem (and other modal issues) so if you can update your bootstrap CSS and JS that would be the best solution. If you can't update the solution below will still work and essentially does the same thing as bootstrap 3.3.4 (recalculate and apply padding).
As Bass Jobsen pointed out, newer versions of Bootstrap have the z-index solved. The modal-open class and padding-right were still problems for me but this scripts inspired by Yermo Lamers solution solves it. Just drop it in your JS file and enjoy.
$(document).on('hide.bs.modal', '.modal', function (event) {
var padding_right = 0;
$.each($('.modal'), function(){
if($(this).hasClass('in') && $(this).modal().data('bs.modal').scrollbarWidth > padding_right) {
padding_right = $(this).modal().data('bs.modal').scrollbarWidth
}
});
$('body').data('padding_right', padding_right + 'px');
});
$(document).on('hidden.bs.modal', '.modal', function (event) {
$('body').data('open_modals', $('body').data('open_modals') - 1);
if($('body').data('open_modals') > 0) {
$('body').addClass('modal-open');
$('body').css('padding-right', $('body').data('padding_right'));
}
});
$(document).on('shown.bs.modal', '.modal', function (event) {
if (typeof($('body').data('open_modals')) == 'undefined') {
$('body').data('open_modals', 0);
}
$('body').data('open_modals', $('body').data('open_modals') + 1);
$('body').css('padding-right', (parseInt($('body').css('padding-right')) / $('body').data('open_modals') + 'px'));
});
Adding to the above answers, you can also use
!which python
Type this in a cell and this will show the path of the environment. I'm not sure of the reason, but in my installation, there is no segregation of environments in the notebook, but on activating the environment and launching jupyter notebook, the path used is the python installed in the environment.
This is possible with switch enhancements in Java 14. Following is a fairly intuitive example of how the same can be achieved.
switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> System.out.println("this month has 31 days");
case 4, 6, 9 -> System.out.println("this month has 30 days");
case 2 -> System.out.println("February can have 28 or 29 days");
default -> System.out.println("invalid month");
}
been going thru a lot of posts on getting a form centered in the page and none of them worked. code below is from a react component using bootstrap 4.1. height should be 100vh and not 100%
<div className="container">
<div className="d-flex justify-content-center align-items-center" style={height}>
<form>
<div className="form-group">
<input className="form-control form-control-lg" placeholder="Email" type="email"/>
</div>
<div className="form-group">
<input className="form-control form-control-lg" placeholder="Password" type="password"/>
</div>
<div className="form-group">
<button className="btn btn-info btn-lg btn-block">Sign In</button>
</div>
</form>
</div>
</div>
where height in style is:
const height = { height: '100vh' }
It needs to be clarified that not only data should be cache-friendly, it is just as important for the code. This is in addition to branch predicition, instruction reordering, avoiding actual divisions and other techniques.
Typically the denser the code, the fewer cache lines will be required to store it. This results in more cache lines being available for data.
The code should not call functions all over the place as they typically will require one or more cache lines of their own, resulting in fewer cache lines for data.
A function should begin at a cache line-alignment-friendly address. Though there are (gcc) compiler switches for this be aware that if the the functions are very short it might be wasteful for each one to occupy an entire cache line. For example, if three of the most often used functions fit inside one 64 byte cache line, this is less wasteful than if each one has its own line and results in two cache lines less available for other usage. A typical alignment value could be 32 or 16.
So spend some extra time to make the code dense. Test different constructs, compile and review the generated code size and profile.
In that case lists {"a", "b"} and {"b","a"} are equal. And {"a", "b"} and {"b","a","c"} are not equal. If you use list of complex objects, remember to override equals method, as containsAll uses it inside.
if (oneList.size() == secondList.size() && oneList.containsAll(secondList)){
areEqual = true;
}
Give it a try :
public LatLng getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
Double lat,lon;
try {
lat = location.getLatitude ();
lon = location.getLongitude ();
return new LatLng(lat, lon);
}
catch (NullPointerException e){
e.printStackTrace();
return null;
}
}
if (strcmp("hello", "hello") = 0)
Is trying to assign 0 to function return value which isn't lvalue.
Function return values are not lvalue (no storage for it), so any attempt to assign value to something that is not lvalue result in error.
Best practice to avoid such mistakes in if conditions is to use constant value on left side of comparison, so even if you use "=" instead "==", constant being not lvalue will immediately give error and avoid accidental value assignment and causing false positive if condition.
I know this is an older post but it may be useful for those who are looking to show a .NET server side image using jQuery.
You have to use a slightly different logic.
So, $("#<%=myServerimg.ClientID%>").show() will not work if you hid the image using myServerimg.visible = false.
Instead, use the following on server side:
myServerimg.Style.Add("display", "none")
Disclaimer: I am involved in the rest2mobile open source project
Another alternative as a REST client is to use rest2mobile.
The approach is slightly different as it uses concrete rest examples to generate the client code for the REST service. The code replaces the REST URL and JSON payloads with native java methods and POJOs. It also automatically handles server connections, asynchronous invocations and POJO to/from JSON conversions.
Note that this tool comes in different flavors (cli, plugins, android/ios/js support) and you can use the android studio plugin to generate the API directly into your app.
All the code can be found on github here.
What you are going to read is rather hacky, so don't try this at home!
In SQL in general the answer to your question is NO, but because of the relaxed mode of the GROUP BY
(mentioned by @bluefeet), the answer is YES in MySQL.
Suppose, you have a BTREE index on (post_status, post_type, post_author, post_date). How does the index look like under the hood?
(post_status='publish', post_type='post', post_author='user A', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user A', post_date='2012-12-31') (post_status='publish', post_type='post', post_author='user B', post_date='2012-10-01') (post_status='publish', post_type='post', post_author='user B', post_date='2012-12-01')
That is data is sorted by all those fields in ascending order.
When you are doing a GROUP BY
by default it sorts data by the grouping field (post_author
, in our case; post_status, post_type are required by the WHERE
clause) and if there is a matching index, it takes data for each first record in ascending order. That is the query will fetch the following (the first post for each user):
(post_status='publish', post_type='post', post_author='user A', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user B', post_date='2012-10-01')
But GROUP BY
in MySQL allows you to specify the order explicitly. And when you request post_user
in descending order, it will walk through our index in the opposite order, still taking the first record for each group which is actually last.
That is
...
WHERE wp_posts.post_status='publish' AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author DESC
will give us
(post_status='publish', post_type='post', post_author='user B', post_date='2012-12-01') (post_status='publish', post_type='post', post_author='user A', post_date='2012-12-31')
Now, when you order the results of the grouping by post_date, you get the data you wanted.
SELECT wp_posts.*
FROM wp_posts
WHERE wp_posts.post_status='publish' AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author DESC
ORDER BY wp_posts.post_date DESC;
NB:
This is not what I would recommend for this particular query. In this case, I would use a slightly modified version of what @bluefeet suggests. But this technique might be very useful. Take a look at my answer here: Retrieving the last record in each group
Pitfalls: The disadvantages of the approach is that
The advantage is performance in hard cases. In this case, the performance of the query should be the same as in @bluefeet's query, because of amount of data involved in sorting (all data is loaded into a temporary table and then sorted; btw, his query requires the (post_status, post_type, post_author, post_date)
index as well).
What I would suggest:
As I said, those queries make MySQL waste time sorting potentially huge amounts of data in a temporary table. In case you need paging (that is LIMIT is involved) most of the data is even thrown off. What I would do is minimize the amount of sorted data: that is sort and limit a minimum of data in the subquery and then join back to the whole table.
SELECT *
FROM wp_posts
INNER JOIN
(
SELECT max(post_date) post_date, post_author
FROM wp_posts
WHERE post_status='publish' AND post_type='post'
GROUP BY post_author
ORDER BY post_date DESC
-- LIMIT GOES HERE
) p2 USING (post_author, post_date)
WHERE post_status='publish' AND post_type='post';
The same query using the approach described above:
SELECT *
FROM (
SELECT post_id
FROM wp_posts
WHERE post_status='publish' AND post_type='post'
GROUP BY post_author DESC
ORDER BY post_date DESC
-- LIMIT GOES HERE
) as ids
JOIN wp_posts USING (post_id);
All those queries with their execution plans on SQLFiddle.
Try this which uses globs rather than regular expressions so it will only pick out the file names that end in .dbf
filenames <- Sys.glob("*.dbf")
Given the rules you specified:
upto length 13 and including character + infront.
(and also incorporating the min length of 10 in your code)
You're going to want a regex that looks like this:
^\+[0-9]{10,13}$
With the min and max lengths encoded in the regex, you can drop those conditions from your if()
block.
Off topic: I'd suggest that a range of 10 - 13 is too limiting for an international phone number field; you're almost certain to find valid numbers that are both longer and shorter than this. I'd suggest a range of 8 - 20 to be safe.
[EDIT] OP states the above regex doesn't work due to the escape sequence. Not sure why, but an alternative would be:
^[+][0-9]{10,13}$
[EDIT 2]
OP now adds that the +
sign should be optional. In this case, the regex needs a question mark after the +
, so the example above would now look like this:
^[+]?[0-9]{10,13}$
Most of you are wrong. If you want to close existing activity stack regardless of what's in there and create new root, correct set of flags is the following:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
public static final int FLAG_ACTIVITY_CLEAR_TASK
Added in API level 11If set in an Intent passed to
Context.startActivity()
, this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started. That is, the activity becomes the new root of an otherwise empty task, and any old activities are finished. This can only be used in conjunction withFLAG_ACTIVITY_NEW_TASK
.
If you want to apply comma in a List of object's properties. This is the way i found most useful.
here getName() is a string property of a class i have been trying to add "," to.
String message = listName.stream().map(list -> list.getName()).collect(Collectors.joining(", "));
I do like this,you can have a try
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
Use these lines in the code, because the textEntryView is the parent of username edittext and password edittext.
final EditText input1 = (EditText) textEntryView .findViewById(R.id.username);
final EditText input2 = (EditText) textEntryView .findViewById(R.id.password);
For anyone who might stumble upon this, if all the other answers do not help and you are on Windows, know that there is currently a big issue with spawn
on Windows and the PATHEXT
environment variable that can cause certain calls to spawn to not work depending on how the target command is installed.
what about using CSS on UIWebView? something like
<style type="text/css">
<!—-
* {
-webkit-user-select: none;
}
-->
</style>
also you can read detail about block copy-paste using CSS http://rakaz.nl/2009/09/iphone-webapps-101-getting-safari-out-of-the-way.html
You could try the FLOOR function like this:
SELECT FLOOR(columnName), moreColumns, etc
FROM myTable
WHERE ...
You could also try the FORMAT function, provided you know the decimal places can be omitted:
SELECT FORMAT(columnName,0), moreColumns, etc
FROM myTable
WHERE ...
You could combine the two functions
SELECT FORMAT(FLOOR(columnName),0), moreColumns, etc
FROM myTable
WHERE ...
Use the filename
property like this:
uriContent = "data:application/octet-stream;filename=filename.txt," +
encodeURIComponent(codeMirror.getValue());
newWindow=window.open(uriContent, 'filename.txt');
EDIT:
Apparently, there is no reliable way to do this. See: Is there any way to specify a suggested filename when using data: URI?
Try
if (!(i == 'InvKey' || i == 'PostDate')) {
or
if (i != 'InvKey' || i != 'PostDate') {
that says if i does not equals InvKey
OR PostDate
There is contextlib.redirect_stdout()
function in Python 3.4+:
from contextlib import redirect_stdout
with open('help.txt', 'w') as f:
with redirect_stdout(f):
print('it now prints to `help.text`')
It is similar to:
import sys
from contextlib import contextmanager
@contextmanager
def redirect_stdout(new_target):
old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
try:
yield new_target # run some code with the replaced stdout
finally:
sys.stdout = old_target # restore to the previous value
that can be used on earlier Python versions. The latter version is not reusable. It can be made one if desired.
It doesn't redirect the stdout at the file descriptors level e.g.:
import os
from contextlib import redirect_stdout
stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, redirect_stdout(f):
print('redirected to a file')
os.write(stdout_fd, b'not redirected')
os.system('echo this also is not redirected')
b'not redirected'
and 'echo this also is not redirected'
are not redirected to the output.txt
file.
To redirect at the file descriptor level, os.dup2()
could be used:
import os
import sys
from contextlib import contextmanager
def fileno(file_or_fd):
fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
if not isinstance(fd, int):
raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
return fd
@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
if stdout is None:
stdout = sys.stdout
stdout_fd = fileno(stdout)
# copy stdout_fd before it is overwritten
#NOTE: `copied` is inheritable on Windows when duplicating a standard stream
with os.fdopen(os.dup(stdout_fd), 'wb') as copied:
stdout.flush() # flush library buffers that dup2 knows nothing about
try:
os.dup2(fileno(to), stdout_fd) # $ exec >&to
except ValueError: # filename
with open(to, 'wb') as to_file:
os.dup2(to_file.fileno(), stdout_fd) # $ exec > to
try:
yield stdout # allow code to be run with the redirected stdout
finally:
# restore stdout to its previous value
#NOTE: dup2 makes stdout_fd inheritable unconditionally
stdout.flush()
os.dup2(copied.fileno(), stdout_fd) # $ exec >&copied
The same example works now if stdout_redirected()
is used instead of redirect_stdout()
:
import os
import sys
stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, stdout_redirected(f):
print('redirected to a file')
os.write(stdout_fd, b'it is redirected now\n')
os.system('echo this is also redirected')
print('this is goes back to stdout')
The output that previously was printed on stdout now goes to output.txt
as long as stdout_redirected()
context manager is active.
Note: stdout.flush()
does not flush
C stdio buffers on Python 3 where I/O is implemented directly on read()
/write()
system calls. To flush all open C stdio output streams, you could call libc.fflush(None)
explicitly if some C extension uses stdio-based I/O:
try:
import ctypes
from ctypes.util import find_library
except ImportError:
libc = None
else:
try:
libc = ctypes.cdll.msvcrt # Windows
except OSError:
libc = ctypes.cdll.LoadLibrary(find_library('c'))
def flush(stream):
try:
libc.fflush(None)
stream.flush()
except (AttributeError, ValueError, IOError):
pass # unsupported
You could use stdout
parameter to redirect other streams, not only sys.stdout
e.g., to merge sys.stderr
and sys.stdout
:
def merged_stderr_stdout(): # $ exec 2>&1
return stdout_redirected(to=sys.stdout, stdout=sys.stderr)
Example:
from __future__ import print_function
import sys
with merged_stderr_stdout():
print('this is printed on stdout')
print('this is also printed on stdout', file=sys.stderr)
Note: stdout_redirected()
mixes buffered I/O (sys.stdout
usually) and unbuffered I/O (operations on file descriptors directly). Beware, there could be buffering issues.
To answer, your edit: you could use python-daemon
to daemonize your script and use logging
module (as @erikb85 suggested) instead of print
statements and merely redirecting stdout for your long-running Python script that you run using nohup
now.
You can set also blank condition, in place of set null
var isDisable=true;
RaisedButton(
padding: const EdgeInsets.all(20),
textColor: Colors.white,
color: Colors.green,
onPressed: isDisable
? () => (){} : myClickingData(),
child: Text('Button'),
)
public static int? Timesaday { get; set; } = null;
OR
public static Nullable<int> Timesaday { get; set; }
or
public static int? Timesaday = null;
or
public static int? Timesaday
or just
public static int? Timesaday { get; set; }
static void Main(string[] args)
{
Console.WriteLine(Timesaday == null);
//you also can check using
Console.WriteLine(Timesaday.HasValue);
Console.ReadKey();
}
The null keyword is a literal that represents a null reference, one that does not refer to any object. In programming, nullable types are a feature of the type system of some programming languages which allow the value to be set to the special value NULL instead of the usual possible values of the data type.
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/null https://en.wikipedia.org/wiki/Null
For this you just need to add content
attribute and font-family
attribute to the required element via :before or :after wherever applicable.
For example: I wanted to attach an attachment icon after all the a
element inside my post. So, first I need to search if such icon exists in fontawesome. Like in the case I found it here, i.e. fa fa-paperclip
. Then I would right click the icon there, and go the ::before
pseudo property to fetch out the content
tag it is using, which in my case I found to be \f0c6
. Then I would use that in my css like this:
.post a:after {
font-family: FontAwesome,
content: " \f0c6" /* I added a space before \ for better UI */
}
If you have msi installer open it with Orca (tool from Microsoft), table Property (rows UpgradeCode, ProductCode, Product version etc) or table Upgrade column Upgrade Code.
Try to find instller via registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall find required subkey and watch value InstallSource. Maybe along the way you'll be able to find the MSI file.
Posts by John Peter and Dileep kurahe helped me to develop what I consider as being a simpler and cleaner solution, just in case anyone else is still looking. (I am not showing any database code because I actually used a $_SESSION variable.)
The above solutions invariably caused an error upon loading in Excel, about the extension not matching the formatting type. And some of these solutions create a spreadsheet with the data across the page in columns where it would be more traditional to have column headings and list the data down the rows. So here is my simple solution:
$filename = "webreport.csv";
header("Content-Type: application/xls");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
foreach($results as $x => $x_value){
echo '"'.$x.'",' . '"'.$x_value.'"' . "\r\n";
}
$results
so the spreadsheet looked even nicer.In Bash 4 (as well as ZSH 4.3.11):
cmd &>>outfile
just out of box
You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use
ping -n 11 127.0.0.1 > nul
This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)
Self-explanatory code follows which first creates a std::tm
corresponding to 10-10-2012 12:38:40, converts that to a std::chrono::system_clock::time_point
, adds 0.123456 seconds, and then prints that out by converting back to a std::tm
. How to handle the fractional seconds is in the very last step.
#include <iostream>
#include <chrono>
#include <ctime>
int main()
{
// Create 10-10-2012 12:38:40 UTC as a std::tm
std::tm tm = {0};
tm.tm_sec = 40;
tm.tm_min = 38;
tm.tm_hour = 12;
tm.tm_mday = 10;
tm.tm_mon = 9;
tm.tm_year = 112;
tm.tm_isdst = -1;
// Convert std::tm to std::time_t (popular extension)
std::time_t tt = timegm(&tm);
// Convert std::time_t to std::chrono::system_clock::time_point
std::chrono::system_clock::time_point tp =
std::chrono::system_clock::from_time_t(tt);
// Add 0.123456 seconds
// This will not compile if std::chrono::system_clock::time_point has
// courser resolution than microseconds
tp += std::chrono::microseconds(123456);
// Now output tp
// Convert std::chrono::system_clock::time_point to std::time_t
tt = std::chrono::system_clock::to_time_t(tp);
// Convert std::time_t to std::tm (popular extension)
tm = std::tm{0};
gmtime_r(&tt, &tm);
// Output month
std::cout << tm.tm_mon + 1 << '-';
// Output day
std::cout << tm.tm_mday << '-';
// Output year
std::cout << tm.tm_year+1900 << ' ';
// Output hour
if (tm.tm_hour <= 9)
std::cout << '0';
std::cout << tm.tm_hour << ':';
// Output minute
if (tm.tm_min <= 9)
std::cout << '0';
std::cout << tm.tm_min << ':';
// Output seconds with fraction
// This is the heart of the question/answer.
// First create a double-based second
std::chrono::duration<double> sec = tp -
std::chrono::system_clock::from_time_t(tt) +
std::chrono::seconds(tm.tm_sec);
// Then print out that double using whatever format you prefer.
if (sec.count() < 10)
std::cout << '0';
std::cout << std::fixed << sec.count() << '\n';
}
For me this outputs:
10-10-2012 12:38:40.123456
Your std::chrono::system_clock::time_point
may or may not be precise enough to hold microseconds.
Update
An easier way is to just use this date library. The code simplifies down to (using C++14 duration literals):
#include "date.h"
#include <iostream>
#include <type_traits>
int
main()
{
using namespace date;
using namespace std::chrono;
auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
static_assert(std::is_same<decltype(t),
time_point<system_clock, microseconds>>{}, "");
std::cout << t << '\n';
}
which outputs:
2012-10-10 12:38:40.123456
You can skip the static_assert
if you don't need to prove that the type of t
is a std::chrono::time_point
.
If the output isn't to your liking, for example you would really like dd-mm-yyyy ordering, you could:
#include "date.h"
#include <iomanip>
#include <iostream>
int
main()
{
using namespace date;
using namespace std::chrono;
using namespace std;
auto t = sys_days{10_d/10/2012} + 12h + 38min + 40s + 123456us;
auto dp = floor<days>(t);
auto time = make_time(t-dp);
auto ymd = year_month_day{dp};
cout.fill('0');
cout << ymd.day() << '-' << setw(2) << static_cast<unsigned>(ymd.month())
<< '-' << ymd.year() << ' ' << time << '\n';
}
which gives exactly the requested output:
10-10-2012 12:38:40.123456
Update
Here is how to neatly format the current time UTC with milliseconds precision:
#include "date.h"
#include <iostream>
int
main()
{
using namespace std::chrono;
std::cout << date::format("%F %T\n", time_point_cast<milliseconds>(system_clock::now()));
}
which just output for me:
2016-10-17 16:36:02.975
C++17 will allow you to replace time_point_cast<milliseconds>
with floor<milliseconds>
. Until then date::floor
is available in "date.h"
.
std::cout << date::format("%F %T\n", date::floor<milliseconds>(system_clock::now()));
In C++20 this is now simply:
#include <chrono>
#include <iostream>
int
main()
{
using namespace std::chrono;
auto t = sys_days{10d/10/2012} + 12h + 38min + 40s + 123456us;
std::cout << t << '\n';
}
Or just:
std::cout << std::chrono::system_clock::now() << '\n';
std::format
will be available to customize the output.
Is it possible to make a search by
querySelectorAll
using multiple unrelated conditions?
Yes, because querySelectorAll
accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector. For instance:
var list = document.querySelectorAll("form, p, legend");
...will return a list containing any element that is a form
or p
or legend
.
CSS also has the other concept: Restricting based on more criteria. You just combine multiple aspects of a selector. For instance:
var list = document.querySelectorAll("div.foo");
...will return a list of all div
elements that also (and) have the class foo
, ignoring other div
elements.
You can, of course, combine them:
var list = document.querySelectorAll("div.foo, p.bar, div legend");
...which means "Include any div
element that also has the foo
class, any p
element that also has the bar
class, and any legend
element that's also inside a div
."
Steps:
Example
x=pd.DataFrame([1,2,3,4])
def add(i1, i2):
return i1+i2
x.apply(add,i2=9)
The outcome of this example is that each number in the dataframe will be added to the number 9.
0
0 10
1 11
2 12
3 13
Explanation:
The "add" function has two parameters: i1, i2. The first parameter is going to be the value in data frame and the second is whatever we pass to the "apply" function. In this case, we are passing "9" to the apply function using the keyword argument "i2".
You should add following lines while creating a project. It will always ignore .DS_Store
to be pushed to the repository.
*.DS_Store
this will ignore .DS_Store while code commit.
git rm --cached .DS_Store
this is to remove .DS_Store files from your repository, in case you need it, you can uncomment it.
## ignore .DS_Store file.
# git rm --cached .DS_Store
*.DS_Store
A related issue on the emulator is when there isn'y any space left in the /data
partition.
For example,
% adb shell df
Filesystem Size Used Free Blksize
/dev 252M 32K 252M 4096
/mnt/asec 252M 0K 252M 4096
/mnt/obb 252M 0K 252M 4096
/system 154M 154M 0K 4096
/data 64M 57M 6M 4096
/cache 64M 1M 62M 4096
Here is a sample view of the /data/app
directory:
% adb shell ls -l /data/app
-rw-r--r-- system system 19949 2011-10-12 17:09 CubeLiveWallpapers.apk
-rw-r--r-- system system 27670 2011-10-12 17:09 GestureBuilder.apk
-rw-r--r-- system system 34341 2011-10-12 17:09 SoftKeyboard.apk
-rw-r--r-- system system 20151 2011-10-12 17:09 WidgetPreview.apk
I removed the extra APK files. It seems upon every install you get a new APK file. Just remove the extra APK files.
For example,
adb shell rm /data/app/com.brooklynmarathon.calendarapi2-1.apk
First, don't use print
s for logging, there is astable, proven and well-thought out stdlib module to do that: logging
. You definitely should use it instead.
Second, don't be tempted to do a mess with unrelated tools when there is native and simple approach. Here it is:
log = logging.getLogger(__name__)
try:
call_code_that_fails()
except MyError:
log.exception('Any extra info you want to see in your logs')
That's it. You are done now.
What log.exception
is actually doing is just a call to log.error
(that is, log event with level ERROR
) and print traceback then.
Well, here is some considerations:
traceback
or call logger with exc_info=True
or get their hands dirty with sys.exc_info
?Well, just because! They all exist for different purposes. For example, traceback.print_exc
's output is a little bit different from tracebacks produced by the interpreter itself. If you use it, you will confuse anyone who reads your logs, they will be banging their heads against them.
Passing exc_info=True
to log calls is just inappropriate. But, it is useful when catching recoverable errors and you want to log them (using, e.g INFO
level) with tracebacks as well, because log.exception
produces logs of only one level - ERROR
.
And you definitely should avoid messing with sys.exc_info
as much as you can. It's just not a public interface, it's an internal one - you can use it if you definitely know what you are doing. It is not intended for just printing exceptions.
I prefer the Execute via SQL*Plus option. It's in the little down-arrow menu under the "Execute as script" toolbar button.
Well try ini_set('memory_limit', '256M');
134217728 bytes = 128 MB
Or rewrite the code to consume less memory.
If you want to make a change global to the whole notebook:
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]
This has nothing to do with using PDO, it's just that you are confusing INSERT and UPDATE.
Here's the difference:
INSERT
creates a new row. I'm guessing that you really want to create a new row.UPDATE
changes the values in an existing row, but if this is what you're doing you probably should use a WHERE clause to restrict the change to a specific row, because the default is that it applies to every row.So this will probably do what you want:
$sql = "INSERT INTO `access_users`
(`contact_first_name`,`contact_surname`,`contact_email`,`telephone`)
VALUES (:firstname, :surname, :email, :telephone);
";
Note that I've also changed the order of columns; the order of your columns must match the order of values in your VALUES clause.
MySQL also supports an alternative syntax for INSERT:
$sql = "INSERT INTO `access_users`
SET `contact_first_name` = :firstname,
`contact_surname` = :surname,
`contact_email` = :email,
`telephone` = :telephone
";
This alternative syntax looks a bit more like an UPDATE statement, but it creates a new row like INSERT. The advantage is that it's easier to match up the columns to the correct parameters.
Explanation with an example:
Consider you have a game (iso) image in your computer.
When you run
(mount your image as a virtual drive), a virtual drive is created with all the game contents in the virtual drive and the game installation file is automatically launched. [Running your docker image - creating a container and then starting it.]
But when you stop
(similar to docker stop) it, the virtual drive still exists but stopping all the processes. [As the container exists till it is not deleted]
And when you do start
(similar to docker start), from the virtual drive the games files start its execution. [starting the existing container]
In this example - The game image is your Docker image and virtual drive is your container.
Check that right version is referenced in your project. E.g. the dll it is complaining about, could be from an older version and that's why there could be a version mismatch.
Nested classes are just like regular classes, but:
Some examples:
Assume you want to have a class SomeSpecificCollection
which would aggregate objects of class Element
. You can then either:
declare two classes: SomeSpecificCollection
and Element
- bad, because the name "Element" is general enough in order to cause a possible name clash
introduce a namespace someSpecificCollection
and declare classes someSpecificCollection::Collection
and someSpecificCollection::Element
. No risk of name clash, but can it get any more verbose?
declare two global classes SomeSpecificCollection
and SomeSpecificCollectionElement
- which has minor drawbacks, but is probably OK.
declare global class SomeSpecificCollection
and class Element
as its nested class. Then:
SomeSpecificCollection
you refer to just Element
, and everywhere else as SomeSpecificCollection::Element
- which looks +- the same as 3., but more clearSomeSpecificCollection
is also a class.In my opinion, the last variant is definitely the most intuitive and hence best design.
Let me stress - It's not a big difference from making two global classes with more verbose names. It just a tiny little detail, but imho it makes the code more clear.
This is especially useful for introducing typedefs or enums. I'll just post a code example here:
class Product {
public:
enum ProductType {
FANCY, AWESOME, USEFUL
};
enum ProductBoxType {
BOX, BAG, CRATE
};
Product(ProductType t, ProductBoxType b, String name);
// the rest of the class: fields, methods
};
One then will call:
Product p(Product::FANCY, Product::BOX);
But when looking at code completion proposals for Product::
, one will often get all the possible enum values (BOX, FANCY, CRATE) listed and it's easy to make a mistake here (C++0x's strongly typed enums kind of solve that, but never mind).
But if you introduce additional scope for those enums using nested classes, things could look like:
class Product {
public:
struct ProductType {
enum Enum { FANCY, AWESOME, USEFUL };
};
struct ProductBoxType {
enum Enum { BOX, BAG, CRATE };
};
Product(ProductType::Enum t, ProductBoxType::Enum b, String name);
// the rest of the class: fields, methods
};
Then the call looks like:
Product p(Product::ProductType::FANCY, Product::ProductBoxType::BOX);
Then by typing Product::ProductType::
in an IDE, one will get only the enums from the desired scope suggested. This also reduces the risk of making a mistake.
Of course this may not be needed for small classes, but if one has a lot of enums, then it makes things easier for the client programmers.
In the same way, you could "organise" a big bunch of typedefs in a template, if you ever had the need to. It's a useful pattern sometimes.
The PIMPL (short for Pointer to IMPLementation) is an idiom useful to remove the implementation details of a class from the header. This reduces the need of recompiling classes depending on the class' header whenever the "implementation" part of the header changes.
It's usually implemented using a nested class:
X.h:
class X {
public:
X();
virtual ~X();
void publicInterface();
void publicInterface2();
private:
struct Impl;
std::unique_ptr<Impl> impl;
}
X.cpp:
#include "X.h"
#include <windows.h>
struct X::Impl {
HWND hWnd; // this field is a part of the class, but no need to include windows.h in header
// all private fields, methods go here
void privateMethod(HWND wnd);
void privateMethod();
};
X::X() : impl(new Impl()) {
// ...
}
// and the rest of definitions go here
This is particularly useful if the full class definition needs the definition of types from some external library which has a heavy or just ugly header file (take WinAPI). If you use PIMPL, then you can enclose any WinAPI-specific functionality only in .cpp
and never include it in .h
.
As already mentioned, you can get a performance increase from having your python code compiled into bytecode. This is usually handled by python itself, for imported scripts only.
Another reason you might want to compile your python code, could be to protect your intellectual property from being copied and/or modified.
You can read more about this in the Python documentation.
I renamed the executable of python.exe
to e.g. python27.exe
. In respect to the answer of Archimedix I opened my pip.exe with a Hex-Editor, scrolled to the end of the file and changed the python.exe
in the path to python27.exe
. While editing make shure you don't override other informations.
This is known as type assertion
in golang, and it is a common practice.
Here is the explanation from a tour of go:
A type assertion provides access to an interface value's underlying concrete value.
t := i.(T)
This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
t, ok := i.(T)
If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T, and no panic occurs.
NOTE: value i
should be interface type.
Even if i
is an interface type, []i
is not interface type. As a result, in order to convert []i
to its value type, we have to do it individually:
// var items []i
for _, item := range items {
value, ok := item.(T)
dosomethingWith(value)
}
As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.
I made this into a jQuery function:
jQuery.fn.sortDivs = function sortDivs() {
$("> div", this[0]).sort(dec_sort).appendTo(this[0]);
function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}
So you have a big div like "#boo" and all your little divs inside of there:
$("#boo").sortDivs();
You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html
cout << fixed << setprecision(2) << total;
setprecision
specifies the minimum precision. So
cout << setprecision (2) << 1.2;
will print 1.2
fixed
says that there will be a fixed number of decimal digits after the decimal point
cout << setprecision (2) << fixed << 1.2;
will print 1.20
That is a Python bug between "*" and special characters.
Instead of
re.compile(r"\w*")
Try:
re.compile(r"[a-zA-Z0-9]*")
It works, however does not make the same regular expression.
This bug seems to have been fixed between 2.7.5 and 2.7.6.
Using sup on the letter "o" and a capital "C"
<sup>o</sup>C
_x000D_
Should work in all browsers and IE6+
Here is a Swift way to get screen status bar height:
var screenStatusBarHeight: CGFloat {
return UIApplication.sharedApplication().statusBarFrame.height
}
These are included as a standard function in a project of mine: https://github.com/goktugyil/EZSwiftExtensions
Tried all of the options above. What worked for me was:
Domain
Path=/
Resulting Set-Cookie
header:
Set-Cookie: session_token=74528588-7c48-4546-a3ae-4326e22449e5; Expires=Sun, 16 Aug 2020 04:40:42 GMT; Path=/
The header just denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. That's what HTTP headers are for, they tell the recipient what kind of content they're (supposedly) dealing with.
Content-type: application/json; charset=utf-8
designates the content to be in JSON format, encoded in the UTF-8 character encoding. Designating the encoding is somewhat redundant for JSON, since the default (only?) encoding for JSON is UTF-8. So in this case the receiving server apparently is happy knowing that it's dealing with JSON and assumes that the encoding is UTF-8 by default, that's why it works with or without the header.
Does this encoding limit the characters that can be in the message body?
No. You can send anything you want in the header and the body. But, if the two don't match, you may get wrong results. If you specify in the header that the content is UTF-8 encoded but you're actually sending Latin1 encoded content, the receiver may produce garbage data, trying to interpret Latin1 encoded data as UTF-8. If of course you specify that you're sending Latin1 encoded data and you're actually doing so, then yes, you're limited to the 256 characters you can encode in Latin1.
The code compiles ok for me. May be you have forgotten to add the import:
import android.app.AlertDialog;
Anyway, you have a good tutorial here.
This is the fastest way I have found, inspired by @divingTobi's answer. All The answers based on xlrd, openpyxl or pandas are slow for me, as they all load the whole file first.
from zipfile import ZipFile
from bs4 import BeautifulSoup # you also need to install "lxml" for the XML parser
with ZipFile(file) as zipped_file:
summary = zipped_file.open(r'xl/workbook.xml').read()
soup = BeautifulSoup(summary, "xml")
sheets = [sheet.get("name") for sheet in soup.find_all("sheet")]
What I do is create a view that performs the same select as the table variable and link that view into the second view. So a view can select from another view. This achieves the same result
This should get you started:
R> qplot(hwy, cty, data = mpg) +
facet_grid(. ~ manufacturer) +
theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))
See also this question: How can I manipulate the strip text of facet plots in ggplot2?
In my case, I sloved problem with inserting font-face style code
<style type="text/css">
@font-face {
font-family: 'Amazone';font-style: normal;
/*font-weight:100; -webkit-font-smoothing: antialiased; font-smooth:always;*/
src: local('Amazone'), url(font/Amazone.woff) format('woff');}
</style>
direclty in header on your index.html or php page, in style tag. Works for me!
Everything that is business logic belongs in a model, whether it is a database query, calculations, a REST call, etc.
You can have the data access in the model itself, the MVC pattern doesn't restrict you from doing that. You can sugar coat it with services, mappers and what not, but the actual definition of a model is a layer that handles business logic, nothing more, nothing less. It can be a class, a function, or a complete module with a gazillion objects if that's what you want.
It's always easier to have a separate object that actually executes the database queries instead of having them being executed in the model directly: this will especially come in handy when unit testing (because of the easiness of injecting a mock database dependency in your model):
class Database {
protected $_conn;
public function __construct($connection) {
$this->_conn = $connection;
}
public function ExecuteObject($sql, $data) {
// stuff
}
}
abstract class Model {
protected $_db;
public function __construct(Database $db) {
$this->_db = $db;
}
}
class User extends Model {
public function CheckUsername($username) {
// ...
$sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
return $this->_db->ExecuteObject($sql, $data);
}
}
$db = new Database($conn);
$model = new User($db);
$model->CheckUsername('foo');
Also, in PHP, you rarely need to catch/rethrow exceptions because the backtrace is preserved, especially in a case like your example. Just let the exception be thrown and catch it in the controller instead.
Is there an easy way to view all methods which contain this comment? Some sort of menu option?
Yes, choose one of the following:
Go to Window ? Show View ? Tasks (Not TaskList). The new view will show up where the "Console" and "Problems" tabs are by default.
As mentioned elsewhere, you can see them next to the scroll bar as little blue rectangles if you have the source file in question open.
If you just want the // TODO Auto-generated method stub
messages (rather than all // TODO
messages) you should use the search function (Ctrl-F for ones in this file Search ? Java Search ? Search string for the ability to specify this workspace, that file, this project, etc.)
You could do it this way but it leaves it as a varchar
declare @s varchar(50)
set @s = '2011-09-28 18:01:00'
select convert(varchar, cast(@s as datetime), 105) + RIGHT(@s, 9)
or
select convert(varchar(20), @s, 105)
In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.
static private String dumpResponse(HttpServletResponse resp){
StringBuilder sb = new StringBuilder();
sb.append("Response Status = [" + resp.getStatus() + "], ");
String headers = resp.getHeaderNames().stream()
.map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
.collect(Collectors.joining(", "));
if (headers.isEmpty()) {
sb.append("Response headers: NONE,");
} else {
sb.append("Response headers: "+headers+",");
}
return sb.toString();
}
USE BINARY_CHECKSUM
SELECT
FROM Users
WHERE
BINARY_CHECKSUM(Username) = BINARY_CHECKSUM(@Username)
AND BINARY_CHECKSUM(Password) = BINARY_CHECKSUM(@Password)
Total programmatic approach to set rounded corners and add random background color to a View. I have not tested the code, but you get the idea.
GradientDrawable shape = new GradientDrawable();
shape.setCornerRadius( 8 );
// add some color
// You can add your random color generator here
// and set color
if (i % 2 == 0) {
shape.setColor(Color.RED);
} else {
shape.setColor(Color.BLUE);
}
// now find your view and add background to it
View view = (LinearLayout) findViewById( R.id.my_view );
view.setBackground(shape);
Here we are using gradient drawable so that we can make use of GradientDrawable#setCornerRadius
because ShapeDrawable
DOES NOT provide any such method.
You don't need to use a type assertion, instead just use the %v
format specifier with Sprintf
:
hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])
Your question is: are these not modules capable of declaring variables at global scope?
Answer: YES, they are "capable"
The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1
, e.g.)
References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).
For instance, place in Sheet1 code
Public glob_sh1 As String
Sub test_sh1()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
place in ThisWorkbook code
Public glob_this As String
Sub test_this()
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
and in a Standard Module code
Public glob_mod As String
Sub test_mod()
glob_mod = "glob_mod"
ThisWorkbook.glob_this = "glob_this"
Sheet1.glob_sh1 = "glob_sh1"
Debug.Print (glob_mod)
Debug.Print (ThisWorkbook.glob_this)
Debug.Print (Sheet1.glob_sh1)
End Sub
All three subs work fine.
PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).
PS2: Your line Debug.Print ("Hello")
will give you the compile error Invalid outside procedure
.
PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.
PS4: Check also Put Excel-VBA code in module or sheet?.
PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.
PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.
I've been stuck with this problem, my solution was creating a mixin which allows me to specify in SCSS, the actual gutter size I want ...
Solution: 1)
@mixin add-gutter($size) {
margin-right: -$size;
margin-left: -$size;
> [class*="col-"] {
padding-right: $size;
padding-left: $size;
}
}
.that-special-row{
@include add-gutter(7px);
}
And to use it...
<div class="row that-special-row"></div>
The actual solution came about from this issue mentionned on github, which I believe addresses the same problem.
Solution: 2)
Another solution, would be simply to create your custom CSS class
.small-gutters {
margin-right: -10px;
margin-left: -10px;
> [class*="col-"] {
padding-right: 10px;
padding-left: 10px;
}
}
Hope that helps!
Also be aware that deleting a base class pointer when there is no virtual destructor will result in undefined behavior. Something that I learned just recently:
How should overriding delete in C++ behave?
I've been using C++ for years and I still manage to hang myself.
I want to make a more comprehensive answer based off of the most of the potential solutions that are already provided. I also want to point out one more potential aid that may help reading process.
Option 1: dtypes
"dtypes" is a pretty powerful parameter that you can use to reduce the memory pressure of read
methods. See this and this answer. Pandas, on default, try to infer dtypes of the data.
Referring to data structures, every data stored, a memory allocation takes place. At a basic level refer to the values below (The table below illustrates values for C programming language):
The maximum value of UNSIGNED CHAR = 255
The minimum value of SHORT INT = -32768
The maximum value of SHORT INT = 32767
The minimum value of INT = -2147483648
The maximum value of INT = 2147483647
The minimum value of CHAR = -128
The maximum value of CHAR = 127
The minimum value of LONG = -9223372036854775808
The maximum value of LONG = 9223372036854775807
Refer to this page to see the matching between NumPy and C types.
Let's say you have an array of integers of digits. You can both theoretically and practically assign, say array of 16-bit integer type, but you would then allocate more memory than you actually need to store that array. To prevent this, you can set dtype
option on read_csv
. You do not want to store the array items as long integer where actually you can fit them with 8-bit integer (np.int8
or np.uint8
).
Observe the following dtype map.
Source: https://pbpython.com/pandas_dtypes.html
You can pass dtype
parameter as a parameter on pandas methods as dict on read
like {column: type}.
import numpy as np
import pandas as pd
df_dtype = {
"column_1": int,
"column_2": str,
"column_3": np.int16,
"column_4": np.uint8,
...
"column_n": np.float32
}
df = pd.read_csv('path/to/file', dtype=df_dtype)
Option 2: Read by Chunks
Reading the data in chunks allows you to access a part of the data in-memory, and you can apply preprocessing on your data and preserve the processed data rather than raw data. It'd be much better if you combine this option with the first one, dtypes.
I want to point out the pandas cookbook sections for that process, where you can find it here. Note those two sections there;
Option 3: Dask
Dask is a framework that is defined in Dask's website as:
Dask provides advanced parallelism for analytics, enabling performance at scale for the tools you love
It was born to cover the necessary parts where pandas cannot reach. Dask is a powerful framework that allows you much more data access by processing it in a distributed way.
You can use dask to preprocess your data as a whole, Dask takes care of the chunking part, so unlike pandas you can just define your processing steps and let Dask do the work. Dask does not apply the computations before it is explicitly pushed by compute
and/or persist
(see the answer here for the difference).
Other Aids (Ideas)
In all these scenarios outerScopeVar
is modified or assigned a value asynchronously or happening in a later time(waiting or listening for some event to occur),for which the current execution will not wait.So all these cases current execution flow results in outerScopeVar = undefined
Let's discuss each examples(I marked the portion which is called asynchronously or delayed for some events to occur):
1.
Here we register an eventlistner which will be executed upon that particular event.Here loading of image.Then the current execution continuous with next lines img.src = 'lolcat.png';
and alert(outerScopeVar);
meanwhile the event may not occur. i.e, funtion img.onload
wait for the referred image to load, asynchrously. This will happen all the folowing example- the event may differ.
2.
Here the timeout event plays the role, which will invoke the handler after the specified time. Here it is 0
, but still it registers an asynchronous event it will be added to the last position of the Event Queue
for execution, which makes the guaranteed delay.
3.
4.
Node can be consider as a king of asynchronous coding.Here the marked function is registered as a callback handler which will be executed after reading the specified file.
5.
Obvious promise (something will be done in future) is asynchronous. see What are the differences between Deferred, Promise and Future in JavaScript?
https://www.quora.com/Whats-the-difference-between-a-promise-and-a-callback-in-Javascript
This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.
In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.
[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.
in php
echo '<a href="' . $folder_path . '">Link text</a>';
or
<a href="<?=$folder_path?>">Link text</a>;
or
<a href="<?php echo $folder_path ?>">Link text</a>;
The downloaded sdk software does not contain sdk platform tools.
For this, using cmd
go to "C:\Program Files\Android\android-sdk\tools"
directory and then type the following command to download those missing tools:
android.bat update sdk --no-ui
Then type y
to accept all the licenses in cmd
. Downloading will start in cmd
itself.
Try:
select id, game, min(point) from t
group by id
You can only close a window using javascript that was opened using javascript, i.e. when the window was opened using :
window.open
then
window.close
will work. Or else not.
This is what worked for me, it required moment-tz as well as moment though.
const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()
_x000D_
I have also tried all the posted code until I found out this one
if(math.toLowerCase(Locale.ENGLISH));
Here whatever character the user input will be converted to lower cases.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
<?php if( $_product->getTypeId() == 'simple' ): ?>
//your code for simple products only
<?php endif; ?>
<?php if( $_product->getTypeId() == 'grouped' ): ?>
//your code for grouped products only
<?php endif; ?>
So on. It works! Magento 1.6.1, place in the view.phtml
The problem is that the 'and' is being treated as an 'or'.
No, the problem is that you are using the XPath !=
operator and you aren't aware of its "weird" semantics.
Solution:
Just replace the any x != y
expressions with a not(x = y)
expression.
In your specific case:
Replace:
<xsl:when test="$AccountNumber != '12345' and $Balance != '0'">
with:
<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')">
Explanation:
By definition whenever one of the operands of the !=
operator is a nodeset, then the result of evaluating this operator is true if there is a node in the node-set, whose value isn't equal to the other operand.
So:
$someNodeSet != $someValue
generally doesn't produce the same result as:
not($someNodeSet = $someValue)
The latter (by definition) is true exactly when there isn't a node in $someNodeSet
whose string value is equal to $someValue
.
Lesson to learn:
Never use the !=
operator, unless you are absolutely sure you know what you are doing.
Used implementation 'androidx.appcompat:appcompat:1.1.2' in App gradle fixed the issue for me
This is my solution:
Request.Url.AbsoluteUri.Replace(Request.Url.Query, String.Empty);
Why not use a library function to validate the ip address?
>>> ip="241.1.1.112343434"
>>> socket.inet_aton(ip)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton
I found this suggestion useful in my case:
def product_params
params.require(:product).permit(:name).tap do |whitelisted|
whitelisted[:data] = params[:product][:data]
end
end
Check this link of Xavier's comment on github.
This approach whitelists the entire params[:measurement][:groundtruth] object.
Using the original questions attributes:
def product_params
params.require(:measurement).permit(:name, :groundtruth).tap do |whitelisted|
whitelisted[:groundtruth] = params[:measurement][:groundtruth]
end
end
Use an SQLiteStatement.
e.g.
SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );
long count = s.simpleQueryForLong();
this query will auto-update the nulls
ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) DEFAULT 'whatever' NOT NULL;
Open a terminal and run the keytool utility provided with Java to get the SHA-1 fingerprint of the certificate. You should get both the release and debug certificate fingerprints.
To get the release certificate fingerprint: keytool -exportcert -list -v \ -alias -keystore
best way is to use Java7: Java 7 introduces a new way of working with the filesystem, along with a new utility class – Files. Using the Files class, we can create, move, copy, delete files and directories as well; it also can be used to read and write to a file.
public void saveDataInFile(String data) throws IOException {
Path path = Paths.get(fileName);
byte[] strToBytes = data.getBytes();
Files.write(path, strToBytes);
}
Write with FileChannel If you are dealing with large files, FileChannel can be faster than standard IO. The following code write String to a file using FileChannel:
public void saveDataInFile(String data)
throws IOException {
RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
FileChannel channel = stream.getChannel();
byte[] strBytes = data.getBytes();
ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
buffer.put(strBytes);
buffer.flip();
channel.write(buffer);
stream.close();
channel.close();
}
Write with DataOutputStream
public void saveDataInFile(String data) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
outStream.writeUTF(data);
outStream.close();
}
Write with FileOutputStream
Let’s now see how we can use FileOutputStream to write binary data to a file. The following code converts a String int bytes and writes the bytes to file using a FileOutputStream:
public void saveDataInFile(String data) throws IOException {
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = data.getBytes();
outputStream.write(strToBytes);
outputStream.close();
}
Write with PrintWriter we can use a PrintWriter to write formatted text to a file:
public void saveDataInFile() throws IOException {
FileWriter fileWriter = new FileWriter(fileName);
PrintWriter printWriter = new PrintWriter(fileWriter);
printWriter.print("Some String");
printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
printWriter.close();
}
Write with BufferedWriter: use BufferedWriter to write a String to a new file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(data);
writer.close();
}
append a String to the existing file:
public void saveDataInFile(String data) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
writer.append(' ');
writer.append(data);
writer.close();
}
You are using the wrong parameters name, try:
if($_POST){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['text'];
//send email
mail("[email protected]", "51 Deep comment from" .$email, $message);
}
maybe map
, but since you don't want to make a list, you can write your own...
def call_for_all(f, seq):
for i in seq:
f(i)
then you can do:
call_for_all(lamda x: x.start(), all)
call_for_all(lamda x: x.stop(), all)
by the way, all is a built in function, don't overwrite it ;-)
In the later PHP version self::staticMethod();
also will not work. It will throw the strict standard error.
In this case, we can create object of same class and call by object
here is the example
class Foo {
public function fun1() {
echo 'non-static';
}
public static function fun2() {
echo (new self)->fun1();
}
}
Try the following command:
openssl ciphers
This should produce a list of all of the ciphers supported in your version of openssl.
To see just a particular set of ciphers (e.g. just sslv3 ciphers) try:
openssl ciphers -ssl3
See https://www.openssl.org/docs/apps/ciphers.html for more info.
from subprocess import call
def cp_dir(source, target):
call(['cp', '-a', source, target]) # Linux
cp_dir('/a/b/c/', '/x/y/z/')
It works for me. Basically, it executes shell command cp.
Does the server actually get the requests, and are you handling the host name (alias) properly?
after adding to my .hosts file
Check your webserver log, to see how the request came in...
curl has options to dump the request sent, and response received, it is called trace, which will will be saved to a file.
--trace
If you are missing host or header information - you can force those headers with the config option.
I would get the curl request working on the command line, and then try to implement in PHP.
the config option is
-K/--config
the options that are relevant in curl are here
--trace Enables a full trace dump of all incoming and outgoing data, including descriptive information, to the given output file. Use "-" as filename to have the output sent to stdout.
This option overrides previous uses of -v/--verbose or --trace-ascii.
If this option is used several times, the last one will be used.
-K/--config Specify which config file to read curl arguments from. The config file is a text file in which command line arguments can be written which then will be used as if they were written on the actual command line. Options and their parameters must be specified on the same config file line, separated by whitespace, colon, the equals sign or any combination thereof (however, the preferred separa- tor is the equals sign). If the parameter is to contain whitespace, the parameter must be enclosed within quotes. Within double quotes, the following escape sequences are available: \, \", \t, \n, \r and \v. A backslash preceding any other letter is ignored. If the first column of a config line is a '#' character, the rest of the line will be treated as a comment. Only write one option per physical line in the config file.
Specify the filename to -K/--config as '-' to make curl read the file from stdin.
Note that to be able to specify a URL in the config file, you need to specify it using the --url option, and not by simply writing the URL on its own line. So, it could look similar to this:
url = "http://curl.haxx.se/docs/"
Long option names can optionally be given in the config file without the initial double dashes.
When curl is invoked, it always (unless -q is used) checks for a default config file and uses it if found. The default config file is checked for in the following places in this order:
1) curl tries to find the "home dir": It first checks for the CURL_HOME and then the HOME environment variables. Failing that, it uses getpwuid() on UNIX-like systems (which returns the home dir
given the current user in your system). On Windows, it then checks for the APPDATA variable, or as a last resort the '%USERPROFILE%\Application Data'.
2) On windows, if there is no _curlrc file in the home dir, it checks for one in the same dir the curl executable is placed. On UNIX-like systems, it will simply try to load .curlrc from the deter-
mined home dir.
# --- Example file ---
# this is a comment
url = "curl.haxx.se"
output = "curlhere.html"
user-agent = "superagent/1.0"
# and fetch another URL too
url = "curl.haxx.se/docs/manpage.html"
-O
referer = "http://nowhereatall.com/"
# --- End of example file ---
This option can be used multiple times to load multiple config files.
As of January 2017 and the release of Chrome 56, most browsers in common use support the position: sticky
property in CSS.
#thing_to_stick {
position: sticky;
top: 0px;
}
does the trick for me in Firefox and Chrome.
In Safari you still need to use position: -webkit-sticky
.
Polyfills are available for Internet Explorer and Edge; https://github.com/wilddeer/stickyfill seems to be a good one.
i used return $this->db->insert_id();
for Codeigniter
Everything. They're unrelated languages.
Enum
enum MyEnum {
First,
Second,
Three
}
Sample usage
const parsed = Parser.parseEnum('FiRsT', MyEnum);
// parsed = MyEnum.First
const parsedInvalid= Parser.parseEnum('other', MyEnum);
// parsedInvalid = undefined
Ignore case sensitive parse
class Parser {
public static parseEnum<T>(value: string, enumType: T): T[keyof T] | undefined {
if (!value) {
return undefined;
}
for (const property in enumType) {
const enumMember = enumType[property];
if (typeof enumMember === 'string') {
if (enumMember.toUpperCase() === value.toUpperCase()) {
const key = enumMember as string as keyof typeof enumType;
return enumType[key];
}
}
}
return undefined;
}
}
The view (blade template): Inside the loop you can retrieve whatever column you looking for
@foreach ($products as $product)
{{$product->sku}}
@endforeach
Plain old Java on plain old Java 7 and no other dependencies demonstrates the difference...
I put file.txt
in c:\temp\
and I put c:\temp\
on the classpath.
There is only one case where there is a difference between the two call.
class J {
public static void main(String[] a) {
// as "absolute"
// ok
System.err.println(J.class.getResourceAsStream("/file.txt") != null);
// pop
System.err.println(J.class.getClassLoader().getResourceAsStream("/file.txt") != null);
// as relative
// ok
System.err.println(J.class.getResourceAsStream("./file.txt") != null);
// ok
System.err.println(J.class.getClassLoader().getResourceAsStream("./file.txt") != null);
// no path
// ok
System.err.println(J.class.getResourceAsStream("file.txt") != null);
// ok
System.err.println(J.class.getClassLoader().getResourceAsStream("file.txt") != null);
}
}
Perhaps the "replace" module (www.npmjs.org/package/replace) also would work for you. It would not require you to read and then write the file.
Adapted from the documentation:
// install:
npm install replace
// require:
var replace = require("replace");
// use:
replace({
regex: "string to be replaced",
replacement: "replacement string",
paths: ['path/to/your/file'],
recursive: true,
silent: true,
});
I had the same problem. I tried everything I found in the Internet except setting bit in CPU. My friend suggeted me to install VirtualBox. And it works now)
Messing with mapping is borderline moving into real ORM land. Instead of fighting with it and keeping Dapper in its true simple (fast) form, just modify your SQL slightly like so:
var sql = @"select top 1 person_id as PersonId,FirstName,LastName from Person";
Try this:
yAxis: {min: 0, max: 100}
See this jsfiddle example
C++20 std::numbers::pi
At last, it has arrived: http://eel.is/c++draft/numbers
main.cpp
#include <numbers> // std::numbers
#include <iomanip>
#include <iostream>
int main() {
std::cout << std::fixed << std::setprecision(20);
std::cout << "float " << std::numbers::pi_v<float> << std::endl;
std::cout << "double " << std::numbers::pi << std::endl;
std::cout << "long double " << std::numbers::pi_v<long double> << std::endl;
std::cout << "exact " << "3.141592653589793238462643383279502884197169399375105820974944" << std::endl;
}
where the exact result was calculated with:
echo "scale=60; 4*a(1)" | BC_LINE_LENGTH=0 bc -l
as per: How can I calculate pi using Bash command
Compile and run:
g++-10 -ggdb3 -O0 -std=c++20 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
Output:
float 3.14159274101257324219
double 3.14159265358979311600
long double 3.14159265358979323851
exact 3.141592653589793238462643383279502884197169399375105820974944
Tested on Ubuntu 20.04 amd64, GCC 10.2.0
The accepted proposal describes:
5.0. “Headers” [headers] In the table [tab:cpp.library.headers], a new
<math>
header needs to be added.[...]
namespace std { namespace math { template<typename T > inline constexpr T pi_v = unspecified; inline constexpr double pi = pi_v<double>;
There is also a std::numbers::e
of course :-) How to calculate Euler constant or Euler powered in C++?
These constants use the C++14 variable template feature: C++14 Variable Templates: what is their purpose? Any usage example?
In earlier versions of the draft, the constant was under std::math::pi
: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0631r7.pdf
Edit: This particular users problem was solved by starting a new terminal session.
A ?
before the protocol (https) is not support. You want this:
git clone [email protected]:octocat/Spoon-Knife.git
or this:
git clone https://github.com/octocat/Spoon-Knife.git
There is nice example how to deal with this kind of problem modyfing built-in validators angulardocs. I have only added more strict validation pattern.
app.directive('validateEmail', function() {
var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
return {
require: 'ngModel',
restrict: '',
link: function(scope, elm, attrs, ctrl) {
// only apply the validator if ngModel is present and Angular has added the email validator
if (ctrl && ctrl.$validators.email) {
// this will overwrite the default Angular email validator
ctrl.$validators.email = function(modelValue) {
return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
};
}
}
};
});
And simply add
<input type='email' validate-email name='email' id='email' ng-model='email' required>
I would rather use the Date valueOf method instead of === or !==
Seems like === is comparing internal Object's references and nothing concerning date.
If you want to use jQuery, there is $.merge()
Example:
a = [1, 2];
b = [3, 4, 5];
$.merge(a,b);
Result: a = [1, 2, 3, 4, 5]
SQLite doesn't support removing or modifying columns, apparently. But do remember that column data types aren't rigid in SQLite, either.
See also:
You can use the str_replace
when you declare your variable $b like that :
$b = str_replace(" ", "", '88 8888');
echo (int)$b;
Or the most beautiful solution is to use intval :
$b = intval(str_replace(" ", "", '88 8888');
echo $b;
If your value '88 888' is from an other variable, just replace the '88 888' by the variable who contains your String.
Near the top of the code with the Public Workshop(), I am assumeing this bit,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
suitButton = new JCheckBox("Denim Jeans");
suitButton.setMnemonic(KeyEvent.VK_U);
should maybe be,
suitButton = new JCheckBox("Suit");
suitButton.setMnemonic(KeyEvent.VK_Y);
denimjeansButton = new JCheckBox("Denim Jeans");
denimjeansButton.setMnemonic(KeyEvent.VK_U);
1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.