In case anyone doesn't get results from the other answers, I fixed a similar problem by:
adding --hidden-import
flags as needed for any missing modules
cleaning up the associated folders and spec files:
rmdir /s /q dist
rmdir /s /q build
del /s /q my_service.spec
Solution for me is: I clean both the solution and the project. And just rebuild the project. This error happens because I tried to delete the main file (only keep library files) in the previous build so at the current build the old stuff is still kept in the built directory. That's why unresolved things happened. "unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ) "
"C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe"
.Paste the value into Location of the item, and append --kiosk <your url>
:
"C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe" --kiosk http://www.google.com
Press Apply, then OK.
You can scale the image with pygame.transform.scale
:
import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))
You can then get the bounding rectangle of picture
with
rect = picture.get_rect()
and move the picture with
rect = rect.move((x, y))
screen.blit(picture, rect)
where screen
was set with something like
screen = pygame.display.set_mode((1600, 900))
To allow your widgets to adjust to various screen sizes, you could make the display resizable:
import os
import pygame
from pygame.locals import *
pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
pygame.event.pump()
event = pygame.event.wait()
if event.type == QUIT:
pygame.display.quit()
elif event.type == VIDEORESIZE:
screen = pygame.display.set_mode(
event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
pygame.display.flip()
you need to initialize the object elements of the array.
GameObject[] houses = new GameObject[200];
for (int i=0;`i<house` i<houses.length; i++)
{ houses[i] = new GameObject();}
Of course you initialize elements selectively using different constructors anywhere else before you reference them.
based on OP's answer to question:
Please see this link. Its having a different solution, which looks working for the person who asked the question. I'm trying to figure out a solution like this.
Paginated query using sorting on different columns using ROW_NUMBER() OVER () in SQL Server 2005
~Joseph
"method 1" is like the OP's query from the linked question, and "method 2" is like the query from the selected answer. You had to look at the code linked in this answer to see what was really going on, since the code in the selected answer was modified to make it work. Try this:
DECLARE @YourTable table (RowID int not null primary key identity, Value1 int, Value2 int, value3 int)
SET NOCOUNT ON
INSERT INTO @YourTable VALUES (1,1,1)
INSERT INTO @YourTable VALUES (1,1,2)
INSERT INTO @YourTable VALUES (1,1,3)
INSERT INTO @YourTable VALUES (1,2,1)
INSERT INTO @YourTable VALUES (1,2,2)
INSERT INTO @YourTable VALUES (1,2,3)
INSERT INTO @YourTable VALUES (1,3,1)
INSERT INTO @YourTable VALUES (1,3,2)
INSERT INTO @YourTable VALUES (1,3,3)
INSERT INTO @YourTable VALUES (2,1,1)
INSERT INTO @YourTable VALUES (2,1,2)
INSERT INTO @YourTable VALUES (2,1,3)
INSERT INTO @YourTable VALUES (2,2,1)
INSERT INTO @YourTable VALUES (2,2,2)
INSERT INTO @YourTable VALUES (2,2,3)
INSERT INTO @YourTable VALUES (2,3,1)
INSERT INTO @YourTable VALUES (2,3,2)
INSERT INTO @YourTable VALUES (2,3,3)
INSERT INTO @YourTable VALUES (3,1,1)
INSERT INTO @YourTable VALUES (3,1,2)
INSERT INTO @YourTable VALUES (3,1,3)
INSERT INTO @YourTable VALUES (3,2,1)
INSERT INTO @YourTable VALUES (3,2,2)
INSERT INTO @YourTable VALUES (3,2,3)
INSERT INTO @YourTable VALUES (3,3,1)
INSERT INTO @YourTable VALUES (3,3,2)
INSERT INTO @YourTable VALUES (3,3,3)
SET NOCOUNT OFF
DECLARE @PageNumber int
DECLARE @PageSize int
DECLARE @SortBy int
SET @PageNumber=3
SET @PageSize=5
SET @SortBy=1
--SELECT * FROM @YourTable
--Method 1
;WITH PaginatedYourTable AS (
SELECT
RowID,Value1,Value2,Value3
,CASE @SortBy
WHEN 1 THEN ROW_NUMBER() OVER (ORDER BY Value1 ASC)
WHEN 2 THEN ROW_NUMBER() OVER (ORDER BY Value2 ASC)
WHEN 3 THEN ROW_NUMBER() OVER (ORDER BY Value3 ASC)
WHEN -1 THEN ROW_NUMBER() OVER (ORDER BY Value1 DESC)
WHEN -2 THEN ROW_NUMBER() OVER (ORDER BY Value2 DESC)
WHEN -3 THEN ROW_NUMBER() OVER (ORDER BY Value3 DESC)
END AS RowNumber
FROM @YourTable
--WHERE
)
SELECT
RowID,Value1,Value2,Value3,RowNumber
,@PageNumber AS PageNumber, @PageSize AS PageSize, @SortBy AS SortBy
FROM PaginatedYourTable
WHERE RowNumber>=(@PageNumber-1)*@PageSize AND RowNumber<=(@PageNumber*@PageSize)-1
ORDER BY RowNumber
--------------------------------------------
--Method 2
;WITH PaginatedYourTable AS (
SELECT
RowID,Value1,Value2,Value3
,ROW_NUMBER() OVER
(
ORDER BY
CASE @SortBy
WHEN 1 THEN Value1
WHEN 2 THEN Value2
WHEN 3 THEN Value3
END ASC
,CASE @SortBy
WHEN -1 THEN Value1
WHEN -2 THEN Value2
WHEN -3 THEN Value3
END DESC
) RowNumber
FROM @YourTable
--WHERE more conditions here
)
SELECT
RowID,Value1,Value2,Value3,RowNumber
,@PageNumber AS PageNumber, @PageSize AS PageSize, @SortBy AS SortBy
FROM PaginatedYourTable
WHERE
RowNumber>=(@PageNumber-1)*@PageSize AND RowNumber<=(@PageNumber*@PageSize)-1
--AND more conditions here
ORDER BY
CASE @SortBy
WHEN 1 THEN Value1
WHEN 2 THEN Value2
WHEN 3 THEN Value3
END ASC
,CASE @SortBy
WHEN -1 THEN Value1
WHEN -2 THEN Value2
WHEN -3 THEN Value3
END DESC
OUTPUT:
RowID Value1 Value2 Value3 RowNumber PageNumber PageSize SortBy
------ ------ ------ ------ ---------- ----------- ----------- -----------
10 2 1 1 10 3 5 1
11 2 1 2 11 3 5 1
12 2 1 3 12 3 5 1
13 2 2 1 13 3 5 1
14 2 2 2 14 3 5 1
(5 row(s) affected
RowID Value1 Value2 Value3 RowNumber PageNumber PageSize SortBy
------ ------ ------ ------ ---------- ----------- ----------- -----------
10 2 1 1 10 3 5 1
11 2 1 2 11 3 5 1
12 2 1 3 12 3 5 1
13 2 2 1 13 3 5 1
14 2 2 2 14 3 5 1
(5 row(s) affected)
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>com</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
<key>net</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
<key>org</key>
<dict>
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
This will allow to connect to .com .net .org
MSDN: Header: Winbase.h (include Windows.h)
Bit late to this party but I came up with, what I think, is a unique solution. Rather than trying to insert your own ellipsis through css trickery or js I thought i'd try and roll with the single line only restriction. So I duplicate the text for every "line" and just use a negative text-indent to make sure one line starts where the last one stops. FIDDLE
CSS:
#wrapper{
font-size: 20pt;
line-height: 22pt;
width: 100%;
overflow: hidden;
padding: 0;
margin: 0;
}
.text-block-line{
height: 22pt;
display: inline-block;
max-width: 100%;
overflow: hidden;
white-space: nowrap;
width: auto;
}
.text-block-line:last-child{
text-overflow: ellipsis;
}
/*the follwing is suboptimal but neccesary I think. I'd probably just make a sass mixin that I can feed a max number of lines to and have them avialable. Number of lines will need to be controlled by server or client template which is no worse than doing a character count clip server side now. */
.line2{
text-indent: -100%;
}
.line3{
text-indent: -200%;
}
.line4{
text-indent: -300%;
}
HTML:
<p id="wrapper" class="redraw">
<span class="text-block-line line1">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
<span class="text-block-line line2">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
<span class="text-block-line line3">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
<span class="text-block-line line4">This text is repeated for every line that you want to be displayed in your element. This example has a max of 4 lines before the ellipsis occurs. Try scaling the preview window width to see the effect.</span>
</p>
More details in the fiddle. There is an issue with the browser reflowing that I use a JS redraw for and such so do check it out but this is the basic concept. Any thoughts/suggestions are much appreciated.
Dependency Injection (DI) is part of Dependency Inversion Principle (DIP) practice, which is also called Inversion of Control (IoC). Basically you need to do DIP because you want to make your code more modular and unit testable, instead of just one monolithic system. So you start identifying parts of the code that can be separated from the class and abstracted away. Now the implementation of the abstraction need to be injected from outside of the class. Normally this can be done via constructor. So you create a constructor that accepts the abstraction as a parameter, and this is called dependency injection (via constructor). For more explanation about DIP, DI, and IoC container you can read Here
Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.
Associative Array
var a = new Array(1,2,3);
a['key'] = 'experiment';
Array.isArray(a);
returns true
Keep in mind that a.length
will be undefined, because length
is treated as a key, you should use Object.keys(a).length
to get the length of an Associative Array.
Object
var a = {1:1, 2:2, 3:3,'key':'experiment'};
Array.isArray(a)
returns false
JSON returns an Object ... could return an Associative Array ... but it is not like that
Yes, there are a few of them.
ReDoc [Article on swagger.io] [GitHub] [demo] - Reinvented OpenAPI/Swagger-generated API Reference Documentation (I'm the author)
OpenAPI GUI [GitHub] [demo] - GUI / visual editor for creating and editing OpenApi / Swagger definitions (has OpenAPI 3 support)
SwaggerUI-Angular [GitHub] [demo] - An angularJS implementation of Swagger UI
angular-swagger-ui-material [GitHub] [demo] - Material Design template for angular-swager-ui
` Please include either of these:
`#include<sstream>`
using std::istringstream;
What is the young generation?
The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. A young generation full of dead objects is collected very quickly. Some survived objects are aged and eventually move to the old generation.
What is the old generation?
The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection
What is the permanent generation?
The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application.
PermGen has been replaced with Metaspace since Java 8 release.
PermSize & MaxPermSize parameters will be ignored now
How does the three generations interact/relate to each other?
Image source & oracle technetwork tutorial article: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html
"The General Garbage Collection Process" in above article explains the interactions between them with many diagrams.
Have a look at summary diagram:
Here is a strategy that gives a result similar to the ListView
implementation in that you can define the listener in the Activity
or Fragment
level instead of the Adapter
or ViewHolder
level. It also defines some abstract classes that take care of a lot of the boilerplate work of adapters and holders.
First, define an abstract Holder
that extends RecyclerView.ViewHolder
and defines a generic data type, T
, used to bind data to the views. The bindViews
method will be implemented by a subclass to map data to the views.
public abstract class Holder<T> extends RecyclerView.ViewHolder {
T data;
public Holder(View itemView) {
super(itemView);
}
public void bindData(T data){
this.data = data;
bindViews(data);
}
abstract protected void bindViews(T data);
}
Also, create an abstract Adapter
that extends RecyclerView.Adapter<Holder<T>>
. This defines 2 of the 3 interface methods, and a subclass will need to implement the last, onViewHolderCreated
method.
public abstract class Adapter<T> extends RecyclerView.Adapter<Holder<T>> {
List<T> list = new ArrayList<>();
@Override
public void onBindViewHolder(Holder<T> holder, int position) {
holder.bindData(list.get(position));
}
@Override
public int getItemCount() {
return list.size();
}
public T getItem(int adapterPosition){
return list.get(adapterPosition);
}
}
Now create a new concrete class that extends Holder
. This method only has to define the Views and handle the binding. Here I'm using the ButterKnife library, but feel free to use itemView.findViewById(...)
methods instead.
public class PersonHolder extends Holder<Person>{
@Bind(R.id.firstname) TextView firstname;
@Bind(R.id.lastname) TextView lastname;
public PersonHolder(View view){
super(view);
ButterKnife.bind(this, view);
}
@Override
protected void bindViews(Person person) {
firstname.setText(person.firstname);
lastname.setText(person.lastname);
}
}
Finally, in your Activity
or Fragment
class that holds the RecyclerView
you would have this code:
// Create adapter, this happens in parent Activity or Fragment of RecyclerView
adapter = new Adapter<Person>(){
@Override
public PersonHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.layout_person_view, parent, false);
PersonHolder holder = new PersonHolder(v);
v.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
int itemPos = holder.getAdapterPosition();
Person person = getItem(itemPos);
// do something with person
EventBus.getDefault().postSticky(new PersonClickedEvent(itemPos, person));
}
});
return holder;
}
};
var uniqueColors = (from dbo in database.MainTable
where dbo.Property == true
select dbo.Color.Name).Distinct();
For Windows slave, please use Execute Windows batch command
.
For Unix-like slave like linux or Mac, Execute shell
is the option.
The scope of a variable is always the block it is inside. For example if you do something like
if(...)
{
int y = 5; //y is created
} //y leaves scope, since the block ends.
else
{
int y = 8; //y is created
} //y leaves scope, since the block ends.
cout << y << endl; //Gives error since y is not defined.
The solution is to define y outside of the if blocks
int y; //y is created
if(...)
{
y = 5;
}
else
{
y = 8;
}
cout << y << endl; //Ok
In your program you have to move the definition of y and c out of the if blocks into the higher scope. Your Function then would look like this:
//Using the Gaussian algorithm
int dayofweek(int date, int month, int year )
{
int y, c;
int d=date;
if (month==1||month==2)
{
y=((year-1)%100);
c=(year-1)/100;
}
else
{
y=year%100;
c=year/100;
}
int m=(month+9)%12+1;
int product=(d+(2.6*m-0.2)+y+y/4+c/4-2*c);
return product%7;
}
request.user.get_username()
will return a string of the users email.
request.user.username
will return a method.
This answer below does not directly answer the OP's question. However, I'm adding this answer here because this page is the first result when you Google "The total number of locks exceeds the lock table size".
If the query you are running is parsing an entire table that spans millions of rows, you can try a while loop instead of changing limits in the configuration.
The while look will break it into pieces. Below is an example looping over an indexed column that is DATETIME.
# Drop
DROP TABLE IF EXISTS
new_table;
# Create (we will add keys later)
CREATE TABLE
new_table
(
num INT(11),
row_id VARCHAR(255),
row_value VARCHAR(255),
row_date DATETIME
);
# Change the delimimter
DELIMITER //
# Create procedure
CREATE PROCEDURE do_repeat(IN current_loop_date DATETIME)
BEGIN
# Loops WEEK by WEEK until NOW(). Change WEEK to something shorter like DAY if you still get the lock errors like.
WHILE current_loop_date <= NOW() DO
# Do something
INSERT INTO
user_behavior_search_tagged_keyword_statistics_with_type
(
num,
row_id,
row_value,
row_date
)
SELECT
# Do something interesting here
num,
row_id,
row_value,
row_date
FROM
old_table
WHERE
row_date >= current_loop_date AND
row_date < current_loop_date + INTERVAL 1 WEEK;
# Increment
SET current_loop_date = current_loop_date + INTERVAL 1 WEEK;
END WHILE;
END//
# Run
CALL do_repeat('2017-01-01');
# Cleanup
DROP PROCEDURE IF EXISTS do_repeat//
# Change the delimimter back
DELIMITER ;
# Add keys
ALTER TABLE
new_table
MODIFY COLUMN
num int(11) NOT NULL,
ADD PRIMARY KEY
(num),
ADD KEY
row_id (row_id) USING BTREE,
ADD KEY
row_date (row_date) USING BTREE;
You can also adapt it to loop over the "num" column if your table doesn't use a date.
Hope this helps someone!
By now there are 4 different ways to document objects as parameters/types. Each has its own uses. Only 3 of them can be used to document return values, though.
For objects with a known set of properties (Variant A)
/**
* @param {{a: number, b: string, c}} myObj description
*/
This syntax is ideal for objects that are used only as parameters for this function and don't require further description of each property.
It can be used for @returns
as well.
For objects with a known set of properties (Variant B)
Very useful is the parameters with properties syntax:
/**
* @param {Object} myObj description
* @param {number} myObj.a description
* @param {string} myObj.b description
* @param {} myObj.c description
*/
This syntax is ideal for objects that are used only as parameters for this function and that require further description of each property.
This can not be used for @returns
.
For objects that will be used at more than one point in source
In this case a @typedef comes in very handy. You can define the type at one point in your source and use it as a type for @param
or @returns
or other JSDoc tags that can make use of a type.
/**
* @typedef {Object} Person
* @property {string} name how the person is called
* @property {number} age how many years the person lived
*/
You can then use this in a @param
tag:
/**
* @param {Person} p - Description of p
*/
Or in a @returns
:
/**
* @returns {Person} Description
*/
For objects whose values are all the same type
/**
* @param {Object.<string, number>} dict
*/
The first type (string) documents the type of the keys which in JavaScript is always a string or at least will always be coerced to a string. The second type (number) is the type of the value; this can be any type.
This syntax can be used for @returns
as well.
Resources
Useful information about documenting types can be found here:
https://jsdoc.app/tags-type.html
PS:
to document an optional value you can use []
:
/**
* @param {number} [opt_number] this number is optional
*/
or:
/**
* @param {number|undefined} opt_number this number is optional
*/
Assuming your server side script doesn't set the proper Content-Type: application/json
response header you will need to indicate to jQuery that this is JSON by using the dataType: 'json'
parameter.
Then you could use the $.each()
function to loop through the data:
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
}
});
or use the $.getJSON
method:
$.getJSON('/functions.php', { get_param: 'value' }, function(data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.name
}));
});
});
$eval
and $parse
don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.
Q: What exactly is $eval doing? Why does it need its own mini parsing language?
From the docs:
Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.
It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).
Q: Why isn't plain old javascript "eval" being used?
Because it's not actually evaluating JavaScript. As the docs say:
If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.
The docs linked to above have a lot more information.
For those who are getting this error in DBeaver the solution was found here at line:
@lcustodio on the SSL page, set SSL mode: require and either leave the SSL Factory blank or use the org.postgresql.ssl.NonValidatingFactory
Under Network -> SSL tab I checked the Use SLL checkbox and set Advance -> SSL Mode = require and it now works.
This situation happens because you haven't installed/start service of ASP.net.
Use below command in windows 7,8,10.
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -i
Another option would be to just use the excellent corrr
package https://github.com/drsimonj/corrr and do
require(corrr)
require(dplyr)
myData %>%
select(x,y,z) %>% # or do negative or range selections here
correlate() %>%
rearrange() %>% # rearrange by correlations
shave() # Shave off the upper triangle for a cleaner result
Steps 3 and 4 are entirely optional and are just included to demonstrate the usefulness of the package.
Another way is to create an interface like this:
public interface GlobalConstants
{
String name = "Chilly Billy";
String address = "10 Chicken head Lane";
}
Any class that needs to use them only has to implement the interface:
public class GlobalImpl implements GlobalConstants
{
public GlobalImpl()
{
System.out.println(name);
}
}
A stateful server keeps state between connections. A stateless server does not.
So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.
When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.
HTTP and NFS are stateless protocols. Each request stands on its own.
Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.
SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.
The problem is that your PATH does not include the location of the node executable.
You can likely run node as "/usr/local/bin/node
".
You can add that location to your path by running the following command to add a single line to your bashrc file:
echo 'export PATH=$PATH:/usr/local/bin' >> $HOME/.bashrc
If you are linking to many files, create a whitelist, and then use sendFile():
app.get('/npm/:pkg/:file', (req, res) => {
const ok = ['jquery','bootstrap','interactjs'];
if (!ok.includes(req.params.pkg)) res.status(503).send("Not Permitted.");
res.sendFile(__dirname + `/node_modules/${req.params.pkg}/dist/${req.params.file}`);
});
For example, You can then safely link to /npm/bootstrap/bootsrap.js, /npm/bootstrap/bootsrap.css, etc.
As an aside, I would love to know if there was a way to whitelist using express.static
Check Safari developer reference on Touch class.
According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX
and not PageX
In the new world, we should be moving towards the standard Intl
JavaScript object, that has a handy DateTimeFormat
constructor with .format()
method:
function format_time(s) {
const dtFormat = new Intl.DateTimeFormat('en-GB', {
timeStyle: 'medium',
timeZone: 'UTC'
});
return dtFormat.format(new Date(s * 1e3));
}
console.log( format_time(12345) ); // "03:25:45"
_x000D_
But to be 100% compatible with all legacy JavaScript engines, here is the shortest one-liner solution to format seconds as hh:mm:ss
:
function format_time(s) {
return new Date(s * 1e3).toISOString().slice(-13, -5);
}
console.log( format_time(12345) ); // "03:25:45"
_x000D_
Method
Date.prototype.toISOString()
returns time in simplified extended ISO 8601 format, which is always 24 or 27 characters long (i.e.YYYY-MM-DDTHH:mm:ss.sssZ
or±YYYYYY-MM-DDTHH:mm:ss.sssZ
respectively). The timezone is always zero UTC offset.
This solution does not require any third-party libraries and is supported in all browsers and JavaScript engines.
As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
It's easy enough to write the equivalent of CopyTo
in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream
.
For efficient purposes you could check whether the stream returned is already a MemoryStream
:
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
I feel like reinventing the wheel...
public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
if (enumerable == null)
throw new ArgumentNullException("enumerable");
return enumerable as T[] ?? enumerable.ToArray();
}
I would love the ability to use a role as a collection of tasks such that, in my playbook, I can choose which subset of tasks to run. Unfortunately, the playbook can only load them all in and then you have to use the --tags
option on the cmdline to choose which tasks to run. The problem with this is that all of the tasks will run unless you remember to set --tags
or --skip-tags
.
I have set up some tasks, however, with a when:
clause that will only fire if a var is set.
e.g.
# role/stuff/tasks/main.yml
- name: do stuff
when: stuff|default(false)
Now, this task will not fire by default, but only if I set the stuff=true
$ ansible-playbook -e '{"stuff":true}'
or in a playbook:
roles:
- {"role":"stuff", "stuff":true}
SELECT DISTINCT * FROM MyFooTable;
If you group by all columns, you are just requesting that duplicate data be removed.
For example a table with the following data:
id | value
----+----------------
1 | foo
2 | bar
1 | foo
3 | something else
If you perform the following query which is essentially the same as SELECT * FROM MyFooTable GROUP BY *
if you are assuming * means all columns:
SELECT * FROM MyFooTable GROUP BY id, value;
id | value
----+----------------
1 | foo
3 | something else
2 | bar
It removes all duplicate values, which essentially makes it semantically identical to using the DISTINCT keyword with the exception of the ordering of results. For example:
SELECT DISTINCT * FROM MyFooTable;
id | value
----+----------------
1 | foo
2 | bar
3 | something else
The basic colours are RGB not RYB. Yes most of the softwares use the traditional RGB which can be used to mix together to form any other color i.e. RGB are the fundamental colours (as defined in Physics & Chemistry texts).
The printer user CMYK (cyan, magenta, yellow, and black) coloring as said by @jcomeau_ictx. You can view the following article to know about RGB vs CMYK: RGB Vs CMYK
A bit more information from the extract about them:
Red, Green, and Blue are "additive colors". If we combine red, green and blue light you will get white light. This is the principal behind the T.V. set in your living room and the monitor you are staring at now. Additive color, or RGB mode, is optimized for display on computer monitors and peripherals, most notably scanning devices.
Cyan, Magenta and Yellow are "subtractive colors". If we print cyan, magenta and yellow inks on white paper, they absorb the light shining on the page. Since our eyes receive no reflected light from the paper, we perceive black... in a perfect world! The printing world operates in subtractive color, or CMYK mode.
If I get you right, you want something that seems to be the opposite of what is desired normally: you want a horizontal layout for small screens and vertically stacked elements on large screens. You may achieve this in a way like this:
<div class="container">
<div class="row">
<div class="hidden-md hidden-lg col-xs-3 col-xs-offset-6">a</div>
<div class="hidden-md hidden-lg col-xs-3">b</div>
</div>
<div class="row">
<div class="hidden-xs hidden-sm">c</div>
</div>
</div>
On small screens, i.e. xs and sm, this generates one row with two columns with an offset of 6. On larger screens, i.e. md and lg, it generates two vertically stacked elements in full width (12 columns).
I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.
I also had the added complication of using Apache rewrite to change example.com/page-name
into example.com/index.pl?page=page-name
. I found that changing the form's action caused example.com/index.pl
(with no page parameter) to be rendered, even though the expected URL (example.com/page-name
) was displayed in the address bar.
To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.
function setAction (element, page)
{
if(checkCondition(page))
{
/* Insert a hidden input into the form to set the page as a parameter.
*/
var input = document.createElement("input");
input.setAttribute("type","hidden");
input.setAttribute("name","page");
input.setAttribute("value",page);
element.form.appendChild(input);
/* Change the form's action. This doesn't chage which page is displayed,
* it just make the URL look right.
*/
element.form.action = '/' + page;
element.form.submit();
}
}
In the form:
<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />
Here are my Apache rewrite rules:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}
I'd be interested in any explanation as to why just setting the action didn't work.
Easy way to convert base64 image into file and save as some random id or name.
// to create some random id or name for your image name
const imgname = new Date().getTime().toString();
// to declare some path to store your converted image
const path = yourpath.png
// image takes from body which you uploaded
const imgdata = req.body.image;
// to convert base64 format into random filename
const base64Data = imgdata.replace(/^data:([A-Za-z-+/]+);base64,/, '');
fs.writeFile(path, base64Data, 'base64', (err) => {
console.log(err);
});
// assigning converted image into your database
req.body.coverImage = imgname
You could use the HttpUtility.ParseQueryString
method and an UriBuilder
which provides a nice way to work with query string parameters without worrying about things like parsing, url encoding, ...:
string longurl = "http://somesite.com/news.php?article=1&lang=en";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["action"] = "login1";
query["attempts"] = "11";
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
// "http://somesite.com:80/news.php?article=1&lang=en&action=login1&attempts=11"
A slight improvement using column name, IMHO:
Private Sub GridView1_Init(sender As Object, e As System.EventArgs) Handles GridView1.Init
For Each dcf As DataControlField In GridView1.Columns
Select Case dcf.HeaderText.ToUpper
Case "CBSELECT"
dcf.Visible = Me.CheckBoxVisible
dcf.HeaderText = "<small>Select</small>"
End Select
Next
End Sub
This allows control over multiple column. I initially use a 'technical' column name, matching the control name within. This makes it obvious within the ASCX page that it's a control column. Then swap out the name as desired for presentation. If I spy the odd name in production, I know I skipped something. The "ToUpper" avoids case-issues.
Finally, this runs ONE time on any post instead of capturing the event during row-creation.
Disabled controls do not submit their values which does not help in knowing if the user clicked save or delete.
So I store the button value in a hidden which does get submitted. The name of the hidden is the same as the button name. I call all my buttons by the name of button
.
E.g. <button type="submit" name="button" value="save">Save</button>
Based on this I found here. Just store the clicked button in a variable.
$(document).ready(function(){
var submitButton$;
$(document).on('click', ":submit", function (e)
{
// you may choose to remove disabled from all buttons first here.
submitButton$ = $(this);
});
$(document).on('submit', "form", function(e)
{
var form$ = $(this);
var hiddenButton$ = $('#button', form$);
if (IsNull(hiddenButton$))
{
// add the hidden to the form as needed
hiddenButton$ = $('<input>')
.attr({ type: 'hidden', id: 'button', name: 'button' })
.appendTo(form$);
}
hiddenButton$.attr('value', submitButton$.attr('value'));
submitButton$.attr("disabled", "disabled");
}
});
Here is my IsNull
function. Use or substitue your own version for IsNull or undefined etc.
function IsNull(obj)
{
var is;
if (obj instanceof jQuery)
is = obj.length <= 0;
else
is = obj === null || typeof obj === 'undefined' || obj == "";
return is;
}
String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);
If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)
mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);
Enter the command to start up the server in that directory: py -3.7 -m http.server
If you don't mind dipping into Rx as part of the monad, you can use TakeLast
:
IEnumerable<int> source = Enumerable.Range(1, 10000);
IEnumerable<int> lastThree = source.AsObservable().TakeLast(3).AsEnumerable();
If you wish to run one script and only one script, you can make it that users default shell.
echo "/usr/bin/uptime" >> /etc/shells
vim /etc/passwd
* username:x:uid:grp:message:homedir:/usr/bin/uptime
can have interesting effects :) ( its not secure tho, so don't trust it too much. nothing like setting your default shell to be a script that wipes your drive. ... although, .. I can imagine a scenario where that could be amazingly useful )
Defining a specific version to upgrade helped me instead of only the upgrade command.
pip3 install larapy-installer==0.4.01 -U
As suggested by @The Berga You can add android:layoutDirection="rtl"
but it's only available with API 17.
for dynamic implementation, here it goes
chkBox.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
Use jquery attr method. It works in all browsers.
var hiddenInput = document.createElement("input");
$(hiddenInput).attr({
'id':'uniqueIdentifier',
'type': 'hidden',
'value': ID,
'class': 'ListItem'
});
Or you could use folowing code:
var e = $('<input id = "uniqueIdentifier" type="hidden" value="' + ID + '" class="ListItem" />');
Can do this in jQuery. Try all options .height()
, .innerHeight()
or .outerHeight()
.
$('document').ready(function() {
$('#right_div').css({'height': $('#left_div').innerHeight()});
});
Example Screenshot
Hope this helps. Thanks!!
I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:
If they are separate classes you can do something like the following:
class A
{
private $name;
public function __construct()
{
$this->name = 'Some Name';
}
public function getName()
{
return $this->name;
}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
function getNameOfA()
{
return $this->a->getName();
}
}
$a = new A();
$b = new B($a);
$b->getNameOfA();
What I have done in this example is first create a new instance of the A
class. And after that I have created a new instance of the B
class to which I pass the instance of A
into the constructor. Now B
can access all the public members of the A
class using $this->a
.
Also note that I don't instantiate the A
class inside the B
class because that would mean I tighly couple the two classes. This makes it hard to:
B
classA
class for another classDifferent Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.
But more importantly why do you want to read an HTTPOnly
cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly
flag and "secure flag" (which forces the cookie to be sent over https) should always be set.
If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly
flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.
People have too much faith in the HTTPOnly
flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.
I like Linq and to make it exit on first mismatch you can do this
string str = '0129834X33';
bool isAllDigits = !str.Any( ch=> ch < '0' || ch > '9' );
One area where address lookups have to be performed reliably is for VOIP E911 services. I know companies reliably using the following services for this:
Bandwidth.com 9-1-1 Access API MSAG Address Validation
MSAG = Master Street Address Guide
https://www.bandwidth.com/9-1-1/
SmartyStreet US Street Address API
This worked for me:
svn add `svn status . | grep "^?" | awk '{print $2}'`
(Source)
As you already solved your problem for Windows, this is a UNIX solution (following Sam). I added here as I think it is still useful for those who reach this question asking for the same thing (as the title does not include the keyword "WINDOWS").
Note (Feb, 2015): As commented by "bdrx", the above command could be further simplified in this way:
svn add `svn status . | awk '/^[?]/{print $2}'`
The document says:
Copy the file into the
app/
folder of your Android Studio project, or into theapp/src/{build_type}
folder if you are using multiple build types.
_nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_nameLabel.font = [UIFont boldSystemFontOfSize:19.0f];
_nameLabel.textColor = [UIColor whiteColor];
_nameLabel.backgroundColor = [UIColor clearColor];
_nameLabel.shadowColor = [UIColor colorWithWhite:0 alpha:0.2];
_nameLabel.shadowOffset = CGSizeMake(0, 1);
i think you should use the [UIColor colorWithWhite:0 alpha:0.2] to set the alpha value.
You could use array_map()
to do it.
$tags = array_map(function($tag) {
return array(
'name' => $tag['name'],
'value' => $tag['url']
);
}, $tags);
Sometimes the Sql Server service has not been started. This may generate the error. Go to Services and start Sql Server. This should make it work.
Warning: Don't do this if you've already pushed
You want to do:
git reset HEAD~
If you don't want the changes and blow everything away:
git reset --hard HEAD~
Integrated application pool mode
When an application pool is in Integrated mode, you can take advantage of the integrated request-processing architecture of IIS and ASP.NET. When a worker process in an application pool receives a request, the request passes through an ordered list of events. Each event calls the necessary native and managed modules to process portions of the request and to generate the response.
There are several benefits to running application pools in Integrated mode. First the request-processing models of IIS and ASP.NET are integrated into a unified process model. This model eliminates steps that were previously duplicated in IIS and ASP.NET, such as authentication. Additionally, Integrated mode enables the availability of managed features to all content types.
Classic application pool mode
When an application pool is in Classic mode, IIS 7.0 handles requests as in IIS 6.0 worker process isolation mode. ASP.NET requests first go through native processing steps in IIS and are then routed to Aspnet_isapi.dll for processing of managed code in the managed runtime. Finally, the request is routed back through IIS to send the response.
This separation of the IIS and ASP.NET request-processing models results in duplication of some processing steps, such as authentication and authorization. Additionally, managed code features, such as forms authentication, are only available to ASP.NET applications or applications for which you have script mapped all requests to be handled by aspnet_isapi.dll.
Be sure to test your existing applications for compatibility in Integrated mode before upgrading a production environment to IIS 7.0 and assigning applications to application pools in Integrated mode. You should only add an application to an application pool in Classic mode if the application fails to work in Integrated mode. For example, your application might rely on an authentication token passed from IIS to the managed runtime, and, due to the new architecture in IIS 7.0, the process breaks your application.
Taken from: What is the difference between DefaultAppPool and Classic .NET AppPool in IIS7?
Original source: Introduction to IIS Architecture
Set following php parameters to same value in seconds:
session.cookie_lifetime
session.gc_maxlifetime
in php.ini, .htaccess or for example with
ini_set('session.cookie_lifetime', 86400);
ini_set('session.gc_maxlifetime', 86400);
for a day.
Links:
Make the exception happen like this:
when(obj.someMethod()).thenThrow(new AnException());
Verify it has happened either by asserting that your test will throw such an exception:
@Test(expected = AnException.class)
Or by normal mock verification:
verify(obj).someMethod();
The latter option is required if your test is designed to prove intermediate code handles the exception (i.e. the exception won't be thrown from your test method).
Not done this yet myself, but a quick bit of Google-Fu reveals a tech tip on blogs.oracle.com with examples of exactly what you ask for.
Example taken from the blog post:
MultivaluedMap formData = new MultivaluedMapImpl();
formData.add("name1", "val1");
formData.add("name2", "val2");
ClientResponse response = webResource
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.post(ClientResponse.class, formData);
That any help?
I know a lot of answers has been given but in my case I added web.{Environment}.config versions in my project and when publishing for a particular environment the value gets replaced.
For example, for Staging (web.Staging.config)
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<location>
<system.webServer>
<aspNetCore>
<environmentVariables xdt:Transform="InsertIfMissing">
<environmentVariable name="ASPNETCORE_ENVIRONMENT"
value="Staging"
xdt:Locator="Match(name)"
xdt:Transform="InsertIfMissing" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
For Release or Production I will do this (web.Release.config)
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<location>
<system.webServer>
<aspNetCore>
<environmentVariables xdt:Transform="InsertIfMissing">
<environmentVariable name="ASPNETCORE_ENVIRONMENT"
value="Release"
xdt:Locator="Match(name)"
xdt:Transform="InsertIfMissing" />
</environmentVariables>
</aspNetCore>
</system.webServer>
</location>
</configuration>
Then when publishing I will choose or set the environment name. And this will replace the value of the environment in the eventual web.config file.
in priciple it's the same idea as @Landeeyos. anyhow, expanding on that response: a bit late to the party but here are my two cents:
scenario:
I have a unique case of adding some (roughly 28 text files) predefined, template files with my WPF application. So, the idea is that everytime this app is to be installed, these template, text files will be readily available for usage. anyhow, what I did was that made a seperate library to hold the files by adding a resource.resx. Then I added all those files to this resource file (if you double click a .resx file, its designer gets opened in visual studio). I had set the Access Modifier to public for all. Also, each file was marked as an embedded resource via the Build Action of each text file (you can get that by looking at its properties). let's call this bibliothek1.dll i referenced this above library (bibliothek1.dll) in another library (call it bibliothek2.dll) and then consumed this second library in mf wpf app.
actual fun:
// embedded resource file name <i>with out extension</i>(this is vital!)
string fileWithoutExt = Path.GetFileNameWithoutExtension(fileName);
// is required in the next step
// without specifying the culture
string wildFile = IamAResourceFile.ResourceManager.GetString(fileWithoutExt);
Console.Write(wildFile);
// with culture
string culturedFile = IamAResourceFile.ResourceManager.GetString(fileWithoutExt, CultureInfo.InvariantCulture);
Console.Write(culturedFile);
sample: checkout 'testingresourcefilesusage' @ https://github.com/Natsikap/samples.git
I hope it helps someone, some day, somewhere!
Here are the steps-
Download openssl from Google code (If you have a 64 bit machine you must download openssl-0.9.8e X64 not the latest version)
Extract it. create a folder- OpenSSL in C:/ and copy the extracted code here.
detect debug.keystore file path. If u didn't find, then do a search in C:/ and use the Path in the command in next step.
detect your keytool.exe path and go to that dir/ in command prompt and run this command in 1 line-
$ keytool -exportcert -alias androiddebugkey -keystore "C:\Documents and Settings\Administrator.android\debug.keystore" | "C:\OpenSSL\bin\openssl" sha1 -binary |"C:\OpenSSL\bin\openssl" base64
For more info visit here
E = exponent expression, simply means power(10, n) or 10 ^ n
F = fraction expression, default 6 digits precision
G = gerneral expression, somehow smart to show the number in a concise way (but really?)
See the below example,
The code
void main(int argc, char* argv[])
{
double a = 4.5;
printf("=>>>> below is the example for printf 4.5\n");
printf("%%e %e\n",a);
printf("%%f %f\n",a);
printf("%%g %g\n",a);
printf("%%E %E\n",a);
printf("%%F %F\n",a);
printf("%%G %G\n",a);
double b = 1.79e308;
printf("=>>>> below is the exbmple for printf 1.79*10^308\n");
printf("%%e %e\n",b);
printf("%%f %f\n",b);
printf("%%g %g\n",b);
printf("%%E %E\n",b);
printf("%%F %F\n",b);
printf("%%G %G\n",b);
double d = 2.25074e-308;
printf("=>>>> below is the example for printf 2.25074*10^-308\n");
printf("%%e %e\n",d);
printf("%%f %f\n",d);
printf("%%g %g\n",d);
printf("%%E %E\n",d);
printf("%%F %F\n",d);
printf("%%G %G\n",d);
}
The output
=>>>> below is the example for printf 4.5
%e 4.500000e+00
%f 4.500000
%g 4.5
%E 4.500000E+00
%F 4.500000
%G 4.5
=>>>> below is the exbmple for printf 1.79*10^308
%e 1.790000e+308
%f 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%g 1.79e+308
%E 1.790000E+308
%F 178999999999999996376899522972626047077637637819240219954027593177370961667659291027329061638406108931437333529420935752785895444161234074984843178962619172326295244262722141766382622299223626438470088150218987997954747866198184686628013966119769261150988554952970462018533787926725176560021258785656871583744.000000
%G 1.79E+308
=>>>> below is the example for printf 2.25074*10^-308
%e 2.250740e-308
%f 0.000000
%g 2.25074e-308
%E 2.250740E-308
%F 0.000000
%G 2.25074E-308
Today I was facing same problem, I did as below while reloading select box. (In Plain JS)
var select = document.getElementById("item");
select.options.length = 0;
var opt = document.createElement('option');
opt.value = 0;
opt.innerHTML = "Select Item ...";
opt.selected = "selected";
select.appendChild(opt);
for (var key in lands) {
var opt = document.createElement('option');
opt.value = lands[key].id;
opt.innerHTML = lands[key].surveyNo;
select.appendChild(opt);
}
You can use a jQuery plugin called Array Utilities to get an array of unique items. It can be done like this:
var distinctArray = $.distinct([1, 2, 2, 3])
distinctArray = [1,2,3]
You can temporarily increase the cache size and do one dummy select and then reset the cache size back to 1. So for example
ALTER SEQUENCE mysequence INCREMENT BY 100;
select mysequence.nextval from dual;
ALTER SEQUENCE mysequence INCREMENT BY 1;
if you use more thread ExecutionServices SEQUENTIALLY and want to wait EACH EXECUTIONSERVICE to be finished. The best way is like below;
ExecutorService executer1 = Executors.newFixedThreadPool(THREAD_SIZE1);
for (<loop>) {
executer1.execute(new Runnable() {
@Override
public void run() {
...
}
});
}
executer1.shutdown();
try{
executer1.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
ExecutorService executer2 = Executors.newFixedThreadPool(THREAD_SIZE2);
for (true) {
executer2.execute(new Runnable() {
@Override
public void run() {
...
}
});
}
executer2.shutdown();
} catch (Exception e){
...
}
Start menu → Accessories → right click on "Command prompt". In the menu, click "Run as Administrator" (on Windows XP you can just run it as usual), run netstat -anb
, and then look through output for your program.
BTW, Skype by default tries to use ports 80 and 443 for incoming connections.
You can also run netstat -anb >%USERPROFILE%\ports.txt
followed by start %USERPROFILE%\ports.txt
to open the port and process list in a text editor, where you can search for the information you want.
You can also use PowerShell to parse netstat
output and present it in a better way (or process it any way you want):
$proc = @{};
Get-Process | ForEach-Object { $proc.Add($_.Id, $_) };
netstat -aon | Select-String "\s*([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+)?\s+([^\s]+)" | ForEach-Object {
$g = $_.Matches[0].Groups;
New-Object PSObject |
Add-Member @{ Protocol = $g[1].Value } -PassThru |
Add-Member @{ LocalAddress = $g[2].Value } -PassThru |
Add-Member @{ LocalPort = [int]$g[3].Value } -PassThru |
Add-Member @{ RemoteAddress = $g[4].Value } -PassThru |
Add-Member @{ RemotePort = $g[5].Value } -PassThru |
Add-Member @{ State = $g[6].Value } -PassThru |
Add-Member @{ PID = [int]$g[7].Value } -PassThru |
Add-Member @{ Process = $proc[[int]$g[7].Value] } -PassThru;
#} | Format-Table Protocol,LocalAddress,LocalPort,RemoteAddress,RemotePort,State -GroupBy @{Name='Process';Expression={$p=$_.Process;@{$True=$p.ProcessName; $False=$p.MainModule.FileName}[$p.MainModule -eq $Null] + ' PID: ' + $p.Id}} -AutoSize
} | Sort-Object PID | Out-GridView
Also it does not require elevation to run.
Try putting anchor tag inside and adding a{display:block;}....it will work fine
a {
color: orange !important;
}
!important
has the effect that the property in question cannot be overridden unless another !important
is used. It is generally considered bad practice to use !important
unless absolutely necessary; however, I can't think of any other way of ‘disabling’ :visited
using CSS only.
First, it violates two principles of Zen of Python:
What it means, is that you intentionally make your error pass silently. Moreover, you don't event know, which error exactly occurred, because except: pass
will catch any exception.
Second, if we try to abstract away from the Zen of Python, and speak in term of just sanity, you should know, that using except:pass
leaves you with no knowledge and control in your system. The rule of thumb is to raise an exception, if error happens, and take appropriate actions. If you don't know in advance, what actions these should be, at least log the error somewhere (and better re-raise the exception):
try:
something
except:
logger.exception('Something happened')
But, usually, if you try to catch any exception, you are probably doing something wrong!
<!-- const cars=['Audi','Merc','BMW','Volvo','Tesla'] -->
<ul>
<li *ngFor="let car of cars">{{car}}</li>
</ul>
/*
*ngFor="let c of oneDimArray | sortBy:'asc'"
*ngFor="let c of arrayOfObjects | sortBy:'asc':'propertyName'"
*/
import { Pipe, PipeTransform } from '@angular/core';
import { orderBy } from 'lodash';
@Pipe({ name: 'sortBy' })
export class SortByPipe implements PipeTransform {
transform(value: any[], order = '', column: string = ''): any[] {
if (!value || order === '' || !order) { return value; } // no array
if (!column || column === '') { return sortBy(value); } // sort 1d array
if (value.length <= 1) { return value; } // array with only one item
return orderBy(value, [column], [order]);
}
}
xlrd.xldate_as_tuple
is nice, but there's xlrd.xldate.xldate_as_datetime
that converts to datetime as well.
import xlrd
wb = xlrd.open_workbook(filename)
xlrd.xldate.xldate_as_datetime(41889, wb.datemode)
=> datetime.datetime(2014, 9, 7, 0, 0)
Here is another library.
Changes required are -
Add sorttable js
Add class name sortable
to table.
Click the table headers to sort the table accordingly:
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>
<table class="sortable">
<tr>
<th>Name</th>
<th>Address</th>
<th>Sales Person</th>
</tr>
<tr class="item">
<td>user:0001</td>
<td>UK</td>
<td>Melissa</td>
</tr>
<tr class="item">
<td>user:0002</td>
<td>France</td>
<td>Justin</td>
</tr>
<tr class="item">
<td>user:0003</td>
<td>San Francisco</td>
<td>Judy</td>
</tr>
<tr class="item">
<td>user:0004</td>
<td>Canada</td>
<td>Skipper</td>
</tr>
<tr class="item">
<td>user:0005</td>
<td>Christchurch</td>
<td>Alex</td>
</tr>
</table>
_x000D_
JSTransform is deprecated , please use babel instead.
<script type="text/babel" src="./lander.js"></script>
I encountered difficulties with Roi-Kyi Bryant's solution when multiple add-ins tried to modify the ribbon. I also don't have admin access on my work-computer, which ruled out installing the Custom UI Editor
. So, if you're in the same boat as me, here's an alternative example to customising the ribbon using only Excel. Note, my solution is derived from the Microsoft guide.
.xlam
files, Chart Tools.xlam
and Priveleged UDFs.xlam
, to demonstrate how multiple add-ins can interact with the Ribbon. customUI
and _rels
folder.customUI
folder, create a customUI.xml
file. The customUI.xml
file details how Excel files interact with the ribbon. Part 2 of the Microsoft guide covers the elements in the customUI.xml
file.My customUI.xml
file for Chart Tools.xlam
looks like this
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
<ribbon>
<tabs>
<tab idQ="x:chartToolsTab" label="Chart Tools">
<group id="relativeChartMovementGroup" label="Relative Chart Movement" >
<button id="moveChartWithRelativeLinksButton" label="Copy and Move" imageMso="ResultsPaneStartFindAndReplace" onAction="MoveChartWithRelativeLinksCallBack" visible="true" size="normal"/>
<button id="moveChartToManySheetsWithRelativeLinksButton" label="Copy and Distribute" imageMso="OutlineDemoteToBodyText" onAction="MoveChartToManySheetsWithRelativeLinksCallBack" visible="true" size="normal"/>
</group >
<group id="chartDeletionGroup" label="Chart Deletion">
<button id="deleteAllChartsInWorkbookSharingAnAddressButton" label="Delete Charts" imageMso="CancelRequest" onAction="DeleteAllChartsInWorkbookSharingAnAddressCallBack" visible="true" size="normal"/>
</group>
</tab>
</tabs>
</ribbon>
</customUI>
My customUI.xml
file for Priveleged UDFs.xlam
looks like this
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
<ribbon>
<tabs>
<tab idQ="x:privelgedUDFsTab" label="Privelged UDFs">
<group id="privelgedUDFsGroup" label="Toggle" >
<button id="initialisePrivelegedUDFsButton" label="Activate" imageMso="TagMarkComplete" onAction="InitialisePrivelegedUDFsCallBack" visible="true" size="normal"/>
<button id="deInitialisePrivelegedUDFsButton" label="De-Activate" imageMso="CancelRequest" onAction="DeInitialisePrivelegedUDFsCallBack" visible="true" size="normal"/>
</group >
</tab>
</tabs>
</ribbon>
</customUI>
.zip
to their file name. In my case, I renamed Chart Tools.xlam
to Chart Tools.xlam.zip
, and Privelged UDFs.xlam
to Priveleged UDFs.xlam.zip
..zip
file, and navigate to the _rels
folder. Copy the .rels
file to the _rels
folder you created in Step 3. Edit each .rels
file with a text editor. From the Microsoft guideBetween the final
<Relationship>
element and the closing<Relationships>
element, add a line that creates a relationship between the document file and the customization file. Ensure that you specify the folder and file names correctly.
<Relationship Type="http://schemas.microsoft.com/office/2006/
relationships/ui/extensibility" Target="/customUI/customUI.xml"
Id="customUIRelID" />
My .rels
file for Chart Tools.xlam
looks like this
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
<Relationship Type="http://schemas.microsoft.com/office/2006/relationships/ui/extensibility" Target="/customUI/customUI.xml" Id="chartToolsCustomUIRel" />
</Relationships>
My .rels
file for Priveleged UDFs
looks like this.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/>
<Relationship Type="http://schemas.microsoft.com/office/2006/relationships/ui/extensibility" Target="/customUI/customUI.xml" Id="privelegedUDFsCustomUIRel" />
</Relationships>
.rels
files in each .zip
file with the .rels
file/files you modified in the previous step..customUI
folder you created into the home directory of the .zip
file/files..zip
file extension from the Excel files you created..xlam
files, back in Excel, add them to your Excel add-ins.onAction
keywords in my buttons. The onAction
keyword indicates that, when the containing element is triggered, the Excel application will trigger the sub-routine encased in quotation marks directly after the onAction
keyword. This is known as a callback. In my .xlam
files, I have a module called CallBacks
where I've included my callback sub-routines.My CallBacks
module for Chart Tools.xlam
looks like
Option Explicit
Public Sub MoveChartWithRelativeLinksCallBack(ByRef control As IRibbonControl)
MoveChartWithRelativeLinks
End Sub
Public Sub MoveChartToManySheetsWithRelativeLinksCallBack(ByRef control As IRibbonControl)
MoveChartToManySheetsWithRelativeLinks
End Sub
Public Sub DeleteAllChartsInWorkbookSharingAnAddressCallBack(ByRef control As IRibbonControl)
DeleteAllChartsInWorkbookSharingAnAddress
End Sub
My CallBacks
module for Priveleged UDFs.xlam
looks like
Option Explicit
Public Sub InitialisePrivelegedUDFsCallBack(ByRef control As IRibbonControl)
ThisWorkbook.InitialisePrivelegedUDFs
End Sub
Public Sub DeInitialisePrivelegedUDFsCallBack(ByRef control As IRibbonControl)
ThisWorkbook.DeInitialisePrivelegedUDFs
End Sub
Different elements have a different callback sub-routine signature. For buttons, the required sub-routine parameter is ByRef control As IRibbonControl
. If you don't conform to the required callback signature, you will receive an error while compiling your VBA project/projects. Part 3 of the Microsoft guide defines all the callback signatures.
Here's what my finished example looks like
Some closing tips
idQ
and xlmns:
keyword. In my example, the Chart Tools.xlam
and Priveleged UDFs.xlam
both have access to the elements with idQ
's equal to x:chartToolsTab
and x:privelgedUDFsTab
. For this to work, the x:
is required, and, I've defined its namespace in the first line of my customUI.xml
file, <customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui" xmlns:x="sao">
. The section Two Ways to Customize the Fluent UI in the Microsoft guide gives some more details.isMSO
keyword. The section Two Ways to Customize the Fluent UI in the Microsoft guide gives some more details.By far, the easiest one I've used is: http://datatables.net/
Amazingly simple...just make sure if you go the DOM replacement route (IE, building a table and letting DataTables reformat it) then make sure to format your table with <thead>
and <tbody>
or it won't work. That's about the only gotcha.
There's also support for AJAX, etc. As with all really good pieces of code, it's also VERY easy to turn it all off. You'd be suprised what you might use, though. I started with a "bare" DataTable that only sorted one field and then realized that some of the features were really relevant to what I'm doing. Clients LOVE the new features.
Bonus points to DataTables for full ThemeRoller support....
I've also had ok luck with tablesorter, but it's not nearly as easy, not quite as well documented, and has only ok features.
HTML:
<button onclick="scrollToTop(1000);"></button>
1# JavaScript (linear):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const totalScrollDistance = document.scrollingElement.scrollTop;
let scrollY = totalScrollDistance, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollY will be -Infinity
scrollY -= totalScrollDistance * (newTimestamp - oldTimestamp) / duration;
if (scrollY <= 0) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = scrollY;
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
2# JavaScript (ease in and out):
function scrollToTop (duration) {
// cancel if already on top
if (document.scrollingElement.scrollTop === 0) return;
const cosParameter = document.scrollingElement.scrollTop / 2;
let scrollCount = 0, oldTimestamp = null;
function step (newTimestamp) {
if (oldTimestamp !== null) {
// if duration is 0 scrollCount will be Infinity
scrollCount += Math.PI * (newTimestamp - oldTimestamp) / duration;
if (scrollCount >= Math.PI) return document.scrollingElement.scrollTop = 0;
document.scrollingElement.scrollTop = cosParameter + cosParameter * Math.cos(scrollCount);
}
oldTimestamp = newTimestamp;
window.requestAnimationFrame(step);
}
window.requestAnimationFrame(step);
}
/*
Explanation:
- pi is the length/end point of the cosinus intervall (see below)
- newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
(for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
- newTimestamp - oldTimestamp equals the delta time
a * cos (bx + c) + d | c translates along the x axis = 0
= a * cos (bx) + d | d translates along the y axis = 1 -> only positive y values
= a * cos (bx) + 1 | a stretches along the y axis = cosParameter = window.scrollY / 2
= cosParameter + cosParameter * (cos bx) | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
= cosParameter + cosParameter * (cos scrollCount * x)
*/
Note:
3# Simple scrolling library on Github
Expanding on @Tomalak's answer. The formula works for days other than Sunday and Monday but you need to use different values for where the 5 is. A way to arrive at the value you need is
Value Needed = 7 - (Value From Date First Documentation for Desired Day Of Week) - 1
here is a link to the document: https://msdn.microsoft.com/en-us/library/ms181598.aspx
And here is a table that lays it out for you.
| DATEFIRST VALUE | Formula Value | 7 - DATEFIRSTVALUE - 1
Monday | 1 | 5 | 7 - 1- 1 = 5
Tuesday | 2 | 4 | 7 - 2 - 1 = 4
Wednesday | 3 | 3 | 7 - 3 - 1 = 3
Thursday | 4 | 2 | 7 - 4 - 1 = 2
Friday | 5 | 1 | 7 - 5 - 1 = 1
Saturday | 6 | 0 | 7 - 6 - 1 = 0
Sunday | 7 | -1 | 7 - 7 - 1 = -1
But you don't have to remember that table and just the formula, and actually you could use a slightly different one too the main need is to use a value that will make the remainder the correct number of days.
Here is a working example:
DECLARE @MondayDateFirstValue INT = 1
DECLARE @FridayDateFirstValue INT = 5
DECLARE @TestDate DATE = GETDATE()
SET @MondayDateFirstValue = 7 - @MondayDateFirstValue - 1
SET @FridayDateFirstValue = 7 - @FridayDateFirstValue - 1
SET DATEFIRST 6 -- notice this is saturday
SELECT
DATEADD(DAY, 0 - (@@DATEFIRST + @MondayDateFirstValue + DATEPART(dw,@TestDate)) % 7, @TestDate) as MondayStartOfWeek
,DATEADD(DAY, 6 - (@@DATEFIRST + @MondayDateFirstValue + DATEPART(dw,@TestDate)) % 7, @TestDate) as MondayEndOfWeek
,DATEADD(DAY, 0 - (@@DATEFIRST + @FridayDateFirstValue + DATEPART(dw,@TestDate)) % 7, @TestDate) as FridayStartOfWeek
,DATEADD(DAY, 6 - (@@DATEFIRST + @FridayDateFirstValue + DATEPART(dw,@TestDate)) % 7, @TestDate) as FridayEndOfWeek
SET DATEFIRST 2 --notice this is tuesday
SELECT
DATEADD(DAY, 0 - (@@DATEFIRST + @MondayDateFirstValue + DATEPART(dw,@TestDate)) % 7, @TestDate) as MondayStartOfWeek
,DATEADD(DAY, 6 - (@@DATEFIRST + @MondayDateFirstValue + DATEPART(dw,@TestDate)) % 7, @TestDate) as MondayEndOfWeek
,DATEADD(DAY, 0 - (@@DATEFIRST + @FridayDateFirstValue + DATEPART(dw,@TestDate)) % 7, @TestDate) as FridayStartOfWeek
,DATEADD(DAY, 6 - (@@DATEFIRST + @FridayDateFirstValue + DATEPART(dw,@TestDate)) % 7, @TestDate) as FridayEndOfWeek
This method would be agnostic of the DATEFIRST
Setting which is what I needed as I am building out a date dimension with multiple week methods included.
So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.
While ENV
, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG
and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args
at every build without changing our docker file.
For more details, you can refer this.
document.getElementsByClassName("classstringhere").length
The document.getElementsByClassName("classstringhere")
method returns an array of all the elements with that class name, so .length
gives you the amount of them.
Console.Read()
is used to read next charater from the standard input stream.
When we want to read only the single character then use Console.Read()
.
Console.ReadLine()
is used to read aline of characters from the standard input stream.
when we want to read a line of characters use Console.ReadLine()
.
Yes, it's built in to jQuery. See the docs at jquery documentation.
ajaxError may be what you want.
Other slightly different methods:
with t1_count as (select count(*) c1 from t1),
t2_count as (select count(*) c2 from t2)
select c1,
c2
from t1_count,
t2_count
/
select c1,
c2
from (select count(*) c1 from t1) t1_count,
(select count(*) c2 from t2) t2_count
/
var e = $('<div style="display:block; id="myid" float:left;width:'+width+'px; height:'+height+'px; margin-top:'+positionY+'px;margin-left:'+positionX+'px;border:1px dashed #CCCCCC;"></div>');
$("#box").html(e);
Yep, you'll want to do something like this:
echo -n "Enter Fullname: "
read fullname
Another option would be to have them supply this information on the command line. Getopts is your best bet there.
Using getopts in bash shell script to get long and short command line options
You have to free()
the allocated memory in exact reverse order of how it was allocated using malloc()
.
Note that You should free the memory only after you are done with your usage of the allocated pointers.
memory allocation for 1D arrays:
buffer = malloc(num_items*sizeof(double));
memory deallocation for 1D arrays:
free(buffer);
memory allocation for 2D arrays:
double **cross_norm=(double**)malloc(150 * sizeof(double *));
for(i=0; i<150;i++)
{
cross_norm[i]=(double*)malloc(num_items*sizeof(double));
}
memory deallocation for 2D arrays:
for(i=0; i<150;i++)
{
free(cross_norm[i]);
}
free(cross_norm);
If anyone wants to do this with a IHttpActionResult
may be in a Web API project, Below might be helpful.
// GET: api/Default/
public IHttpActionResult Get()
{
//return Ok();//200
//return StatusCode(HttpStatusCode.Accepted);//202
//return BadRequest();//400
//return InternalServerError();//500
//return Unauthorized();//401
return Ok();
}
Simply you could use:
PartialView("../ABC/XXX")
The code was most likely compiled with a later JDK (without using cross-compilation options) and is being run on an earlier JRE. While upgrading the JRE is one solution, it would be better to use the cross-compilation options to ensure the code will run on whatever JRE is intended as the minimum version for the app.
You need to call GetResponse().
Stream receiveStream = response.GetResponseStream ();
StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);
txtBlock.Text = readStream.ReadToEnd();
Check out the DirectoryIterator class.
From one of the comments on that page:
// output all files and directories except for '.' and '..'
foreach (new DirectoryIterator('../moodle') as $fileInfo) {
if($fileInfo->isDot()) continue;
echo $fileInfo->getFilename() . "<br>\n";
}
The recursive version is RecursiveDirectoryIterator.
The simple answer is that you can't. box-shadow applies to the whole element only. You could use a different approach and use ::before in CSS to insert an 1-pixel high element into header nav and set the box-shadow on that instead.
The problem is not in your Spring annotations but your design pattern. You mix together different scopes and threads:
The singleton is available anywhere, it is ok. However session/request scope is not available outside a thread that is attached to a request.
Asynchronous job can run even the request or session doesn't exist anymore, so it is not possible to use a request/session dependent bean. Also there is no way to know, if your are running a job in a separate thread, which thread is the originator request (it means aop:proxy is not helpful in this case).
I think your code looks like that you want to make a contract between ReportController, ReportBuilder, UselessTask and ReportPage. Is there a way to use just a simple class (POJO) to store data from UselessTask and read it in ReportController or ReportPage and do not use ReportBuilder anymore?
The XMLHttpRequest.timeout
property represents a number of milliseconds a request can take before automatically being terminated. The default value is 0
, which means there is no timeout. An important note the timeout shouldn't be used for synchronous XMLHttpRequests
requests, used in a document environment or it will throw an InvalidAccessError
exception. You may not use a timeout for synchronous requests with an owning window.
IE10 and 11 do not support synchronous requests, with support being phased out in other browsers too. This is due to detrimental effects resulting from making them.
More info can be found here.
PATH
C:\Program Files\Mozilla Firefox15\Firefox.exe
It will be probably not here - because thats what the error says. How to fix it?
It his does not help then change the constructor like this:
File pathToBinary = new File("C:\\Program Files\\Mozilla Firefox15\\Firefox.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
FirefoxDriver _driver = new FirefoxDriver(ffBinary,firefoxProfile);
Here is my working env path variables after much troubleshooting
CLASSPATH
.;C:\Program Files (x86)\Java\jre7\lib\ext\QTJava.zip;C:\Program Files (x86)\Java\jdk1.6.0_27\bin
PATH <---sometimes this PATH fills up with too many paths and you can't add a path(which was my case!)
bunchofpaths;C:\Program Files (x86)\Java\jdk1.6.0_27\bin
Additionally, when you try to use the cmd to execute the file...make sure your in the local directory as the file your trying to execute (which you did.)
Just a little checklist for people that have this problem still.
To whoever also needs this problem solved:
Firstly, I grab my image with getElementByID
, and save the image as a Base64. Then I save the Base64 string as my localStorage
value.
bannerImage = document.getElementById('bannerImg');
imgData = getBase64Image(bannerImage);
localStorage.setItem("imgData", imgData);
Here is the function that converts the image to a Base64 string:
function getBase64Image(img) {
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}
Then, on my next page I created an image with a blank src
like so:
<img src="" id="tableBanner" />
And straight when the page loads, I use these next three lines to get the Base64 string from localStorage
, and apply it to the image with the blank src
I created:
var dataImage = localStorage.getItem('imgData');
bannerImg = document.getElementById('tableBanner');
bannerImg.src = "data:image/png;base64," + dataImage;
Tested it in quite a few different browsers and versions, and it seems to work quite well.
Pax is correct about the reasons for TIME_WAIT, and why you should be careful about lowering the default setting.
A better solution is to vary the port numbers used for the originating end of your sockets. Once you do this, you won't really care about time wait for individual sockets.
For listening sockets, you can use SO_REUSEADDR to allow the listening socket to bind despite the TIME_WAIT sockets sitting around.
Here's a one-liner for you:
singleton = lambda c: c()
Here's how you use it:
@singleton
class wat(object):
def __init__(self): self.x = 1
def get_x(self): return self.x
assert wat.get_x() == 1
Your object gets instantiated eagerly. This may or may not be what you want.
Let us say you have a data frame you created and named "Data_output", you can simply export it to same directory by using the following syntax.
write.csv(Data_output, "output.csv", row.names = F, quote = F)
You can also use min-height and max-height. It was very useful for me
May be this is useful to you.
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = @"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
}
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//use simple alert from my library (see previous post for details)
[ASFunctions alert:content];
[content release];
}
I suggest
l = re.compile("(?<!^)\s+(?=[A-Z])(?!.\s)").split(s)
Check this demo.
text-align: center
will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0;
(you will probably also have to give the span a display: block
property)
You can also do it by using the Timer()
function.
Code:
from threading import Timer
def hello():
print("Hello")
t = Timer(0.05, hello)
t.start() # After 0.05 seconds, "Hello" will be printed
Where do these values come from? The documentation for android:fontFamily does not list this information in any place
These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.
In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:
Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:
<item name="android:fontFamily">sans-serif</item>
Like the linked answer already stated, 12 variants are possible:
Regular (default):
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item>
Italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>
Bold:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>
Bold-italic:
<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>
Light:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>
Light-italic:
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>
Thin :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>
Thin-italic :
<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>
Condensed regular:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>
Condensed italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>
Condensed bold:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>
Condensed bold-italic:
<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>
Medium:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>
Medium-italic:
<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>
Black:
<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>
For quick reference, this is how they all look like:
protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding, JsonRequestBehavior behavior)
{
return new JsonResult()
{
Data = data,
ContentType = contentType,
ContentEncoding = contentEncoding,
JsonRequestBehavior = behavior,
MaxJsonLength = Int32.MaxValue
};
}
Was the fix for me in MVC 4.
called_from
must be null
. Add a test against that condition like
if (called_from != null && called_from.equalsIgnoreCase("add")) {
or you could use Yoda conditions (per the Advantages in the linked Wikipedia article it can also solve some types of unsafe null
behavior they can be described as placing the constant portion of the expression on the left side of the conditional statement)
if ("add".equalsIgnoreCase(called_from)) { // <-- safe if called_from is null
I found out that inflating the header view as:
inflater.inflate(R.layout.listheader, container, false);
being container the Fragment's ViewGroup, inflates the headerview with a LayoutParam that extends from FragmentLayout but ListView expect it to be a AbsListView.LayoutParams instead.
So, my problem was solved solved by inflating the header view passing the list as container:
ListView list = fragmentview.findViewById(R.id.listview);
View headerView = inflater.inflate(R.layout.listheader, list, false);
then
list.addHeaderView(headerView, null, false);
Kinda late answer but I hope this can help someone
If you only need two decimal places, simplest way is..
SELECT CAST(12 AS DECIMAL(16,2))
OR
SELECT CAST('12' AS DECIMAL(16,2))
Output
12.00
In my case the "SQL Server" Server service stopped. When I restarted the service that enabled me to run the query and eliminate the error.
Its also a good idea to examine your query to find out why the query made this service stop
How about..
var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s)
Edit: This will give you shifts where there is an associated employeeshift (because of the join). For the "not exists" I'd do what @ArsenMkrt or @hyp suggest
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Yes, the error you are getting means that there is not a private key on your Mac associated with the distribution certificate you are trying to use to sign the app.
There are two possible solutions, depending on whether the computer who requested the distribution certificate is available or not.
If the computer who requested the distribution certificate is available (or there is a backup of the distribution assets somewhere)
If the computer where the distribution profile was created is not accessible anymore (and there is not a backup)
You have to revoke the certificate and create a new one.
You may need to ask your team admin or agent to give you some privileges in order to generate distribution certificates. Once you have enough privileges, follow these steps (accurate as of 15-May-2013):
Reopen Xcode and check your project configuration to see if you can now select an "iPhone Distribution" certificate (i.e. it's not grayed out).
You can use gettimeofday()
together with the timedifference_msec()
function below to calculate the number of milliseconds elapsed between two samples:
#include <sys/time.h>
#include <stdio.h>
float timedifference_msec(struct timeval t0, struct timeval t1)
{
return (t1.tv_sec - t0.tv_sec) * 1000.0f + (t1.tv_usec - t0.tv_usec) / 1000.0f;
}
int main(void)
{
struct timeval t0;
struct timeval t1;
float elapsed;
gettimeofday(&t0, 0);
/* ... YOUR CODE HERE ... */
gettimeofday(&t1, 0);
elapsed = timedifference_msec(t0, t1);
printf("Code executed in %f milliseconds.\n", elapsed);
return 0;
}
Note that, when using gettimeofday()
, you need to take seconds into account even if you only care about microsecond differences because tv_usec
will wrap back to zero every second and you have no way of knowing beforehand at which point within a second each sample is obtained.
This image sums pretty well the difference between both:
Source here
Without defaultdict:
words = "apple banana apple strawberry banana lemon"
my_count = {}
for word in words.split():
try: my_count[word] += 1
except KeyError: my_count[word] = 1
Something like this if you're into regex, not sure of the exact syntax for the replace tho!
MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.
Instead use the .NET 2.0 Page.ClientScript.Register* methods. - (The ClientScript property expresses an instance of the ClientScriptManager class )
Guessing the problem
If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.
Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.
Although Other Answers work well, i want to give you alternate short version which i use very often:
Customer::select('customers.*')
->leftJoin('orders', 'customers.id', '=', 'orders.customer_id')
->whereNull('orders.customer_id')->first();
And as in laravel version 5.3
added one more feature which will make your work even simpler look below for example:
Customer::doesntHave('orders')->get();
I don't have enough reputation to comment, but if you like working with QT, they have their own version.
#include <QtCore/qmath.h>
qPow(x, y); // returns x raised to the y power.
Or if you aren't using QT, cmath has basically the same thing.
#include <cmath>
double x = 5, y = 7; //As an example, 5 ^ 7 = 78125
pow(x, y); //Should return this: 78125
It also works if you change the content type
<form method="POST"
action="http://localhost:8080/cms/customer/create_customer"
id="frmRegister" name="frmRegister"
enctype="application/x-www-form-urlencoded">
In the controller also add the header value as follows:
@RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")
The find library is designed for this task specifically: https://ruby-doc.org/stdlib-2.5.1/libdoc/find/rdoc/Find.html
require 'find'
Find.find(path) do |file|
# process
end
This is a standard ruby library, so it should be available
Agree @Drixson Oseña: You should not write localhost/xampp/...., else write for e.g: localhost/mw-config/index.php
Use System.Diagnostics.Process to launch an instance of Notepad.exe.
An answer to a slightly different question: You can use vh
units to pad elements to the center of the viewport:
.centerme {
margin-top: 50vh;
background: red;
}
<div class="centerme">middle</div>
If the task is only copying 4 characters, try for loops. If it's going to be more advanced and you're asking for a function, try strncpy. http://www.cplusplus.com/reference/clibrary/cstring/strncpy/
strncpy(sub1, baseString, 4);
strncpy(sub1, baseString+4, 4);
strncpy(sub1, baseString+8, 4);
or
for(int i=0; i<4; i++)
sub1[i] = baseString[i];
sub1[4] = 0;
for(int i=0; i<4; i++)
sub2[i] = baseString[i+4];
sub2[4] = 0;
for(int i=0; i<4; i++)
sub3[i] = baseString[i+8];
sub3[4] = 0;
Prefer strncpy if possible.
This is because findViewById()
searches in the activity_main
layout, while the button is located in the fragment's layout fragment_main
.
Move that piece of code in the onCreateView()
method of the fragment:
//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button buttonClick = (Button)rootView.findViewById(R.id.button);
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onButtonClick((Button) view);
}
});
Notice that now you access it through rootView
view:
Button buttonClick = (Button)rootView.findViewById(R.id.button);
otherwise you would get again NullPointerException.
I found it is better to use the command Serial.readString()
to replace the Serial.read()
to obtain the continuous I/O for Arduino.
php -i |grep 'Configuration File'
Personnaly I like to do all the initialisations in the constructor
public Test()
{
symbolsPresent = new ArrayList<String>();
symbolsPresent.add("ONE");
symbolsPresent.add("TWO");
symbolsPresent.add("THREE");
symbolsPresent.add("FOUR");
}
Edit : It is a choice of course and others prefer to initialize in the declaration. Both are valid, I have choosen the constructor because all type of initialitions are possible there (if you need a loop or parameters, ...). However I initialize the constants in the declaration on the top on the source.
The most important is to follow a rule that you like and be consistent in our classes.
If you are fond of functional programming style, here is a useful function, self-documented and tested code using doctest.
def decompose(a_list):
"""Turns a list into a set of all elements and a set of duplicated elements.
Returns a pair of sets. The first one contains elements
that are found at least once in the list. The second one
contains elements that appear more than once.
>>> decompose([1,2,3,5,3,2,6])
(set([1, 2, 3, 5, 6]), set([2, 3]))
"""
return reduce(
lambda (u, d), o : (u.union([o]), d.union(u.intersection([o]))),
a_list,
(set(), set()))
if __name__ == "__main__":
import doctest
doctest.testmod()
From there you can test unicity by checking whether the second element of the returned pair is empty:
def is_set(l):
"""Test if there is no duplicate element in l.
>>> is_set([1,2,3])
True
>>> is_set([1,2,1])
False
>>> is_set([])
True
"""
return not decompose(l)[1]
Note that this is not efficient since you are explicitly constructing the decomposition. But along the line of using reduce, you can come up to something equivalent (but slightly less efficient) to answer 5:
def is_set(l):
try:
def func(s, o):
if o in s:
raise Exception
return s.union([o])
reduce(func, l, set())
return True
except:
return False
If you want extended auto-completion for PHP (not only for the code in the current window or standard classes), try out the "ACCPC" plugin: https://github.com/StanDog/npp-phpautocompletion
$("td:contains('c')").html("new");
or, more precisely $("#table_headers td:contains('c')").html("new");
and maybe for reuse you could create a function to call
function ReplaceCellContent(find, replace)
{
$("#table_headers td:contains('" + find + "')").html(replace);
}
Yes, they are all the same.
We can review the interpreted machine code to confirm that that they're all doing the exact same thing.
import dis
def f1():
print "Hello World"
return None
def f2():
print "Hello World"
return
def f3():
print "Hello World"
dis.dis(f1)
4 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f2)
9 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
10 5 LOAD_CONST 0 (None)
8 RETURN_VALUE
dis.dis(f3)
14 0 LOAD_CONST 1 ('Hello World')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
Just set
webView.mediaPlaybackRequiresUserAction = NO;
The autoplay works for me on iOS.
Found it at http://www.linuxquestions.org/questions/suse-novell-60/howto-kill-defunct-processes-574612/
2) Here a great tip from another user (Thxs Bill Dandreta): Sometimes
kill -9 <pid>
will not kill a process. Run
ps -xal
the 4th field is the parent process, kill all of a zombie's parents and the zombie dies!
Example
4 0 18581 31706 17 0 2664 1236 wait S ? 0:00 sh -c /usr/bin/gcc -fomit-frame-pointer -O -mfpmat
4 0 18582 18581 17 0 2064 828 wait S ? 0:00 /usr/i686-pc-linux-gnu/gcc-bin/3.3.6/gcc -fomit-fr
4 0 18583 18582 21 0 6684 3100 - R ? 0:00 /usr/lib/gcc-lib/i686-pc-linux-gnu/3.3.6/cc1 -quie
18581
, 18582
, 18583
are zombies -
kill -9 18581 18582 18583
has no effect.
kill -9 31706
removes the zombies.
Try eUML2. its a single click generator no need to drag n drop.
Try the following.
Execute a database backup query from PHP file. Below is an example of using SELECT INTO OUTFILE query for creating table backup:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
?>
To restore the backup you just need to run LOAD DATA INFILE query like this:
<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";
$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
die('Connection failed [' . $con->connect_error . ']');
}
$tableName = 'yourtable';
$backupFile = 'yourtable.sql';
$query = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
?>
Thanks to earlier answers, this blocks serves well as a general purpose solution for applying a configurable string into a RegEx .. for filtering text:
var permittedChars = '^a-z0-9 _,.?!@+<>';
permittedChars = '[' + permittedChars + ']';
var flags = 'gi';
var strFilterRegEx = new RegExp(permittedChars, flags);
log.debug ('strFilterRegEx: ' + strFilterRegEx);
strVal = strVal.replace(strFilterRegEx, '');
// this replaces hard code solt:
// strVal = strVal.replace(/[^a-z0-9 _,.?!@+]/ig, '');
If you go to the visualstudio.com Visual Studio 2015 RC cross-platform and mobile apps page, then read and scroll to the bottom, it appears that Microsoft is including Xamarin, and upon installing it you do have, as James said, the Xamarin Starter edition. In 2015 RC go to Tools, Xamarin Account to see your Xamarin license. I do not know the limitations, or any expiration date, of this Starter Xamarin Account.
Still, I don't know about you, but the Visual Studio 2015 RC "Community" edition I installed expires in less than 180 days. (Check the Help menu, go to "About...", and click on your license status to check.)
Let's say Xamarin Starter edition is free, but Visual Studio 2015 "Community" has an expiration date. So the bigger question might be whether Visual Studio 2015 "Community" will be free.
Without Xamarin though, Microsoft is offering C++ tools for cross-platform development, but scroll down to the bottom of the page and you might be surprised or confused at the download link description.
In addition, if you want to override all instances and not just that one special instance, this one might help.
function MyClass() {}
MyClass.prototype.myMethod = function() {
alert( "doing original");
};
MyClass.prototype.myMethod_original = MyClass.prototype.myMethod;
MyClass.prototype.myMethod = function() {
MyClass.prototype.myMethod_original.call( this );
alert( "doing override");
};
myObj = new MyClass();
myObj.myMethod();
result:
doing original
doing override
For anyone who wants a quick-fix, this simply replaces all single quotes with double quotes:
import json
predictions = []
def get_top_k_predictions(predictions_path):
'''load the predictions'''
with open (predictions_path) as json_lines_file:
for line in json_lines_file:
predictions.append(json.loads(line.replace("'", "\"")))
get_top_k_predictions("/sh/sh-experiments/outputs/john/baseline_1000/test_predictions.jsonl")
Here's my improvement: added parseInt. for some weird reason it didn't work without it.
// usage: jQuery('#my_div1').hasVerticalScrollBar();
// Credit: http://stackoverflow.com/questions/4814398/how-can-i-check-if-a-scrollbar-is-visible
(function($) {
$.fn.hasVerticalScrollBar = function() {
return this.get(0) ? parseInt( this.get(0).scrollHeight ) > parseInt( this.innerHeight() ) : false;
};
})(jQuery);
Disabling tracking will also cause your result sets to be streamed into memory. This is more efficient when you're working with large sets of data and don't need the entire set of data all at once.
References:
I've found a way (workaround) to do this without making it sync.
So as it was mentioned before Promise.all
is all of none.
so... Use an enclosing promise to catch and force resolve.
let safePromises = originalPrmises.map((imageObject) => {
return new Promise((resolve) => {
// Do something error friendly
promise.then(_res => resolve(res)).catch(_err => resolve(err))
})
})
})
// safe
return Promise.all(safePromises)
The icons you are seeing on desktop is not a icon file. They are either executable files .exe or shortcuts of any application .lnk. So can only set icon which have .ico extension.
Go to Project Menu -> Your_Project_Name Properties -> Application TAB -> Resources -> Icon
browse for your Icon, remember it must have .ico extension
You can make your icon in Visual Studio
Go to Project Menu -> Add New Item -> Icon File
What exactly do you mean by "validation failure"? What are you validating? Are you referring to something like a syntax error (e.g. malformed XML)?
If that's the case, I'd say 400 Bad Request is probably the right thing, but without knowing what it is you're "validating", it's impossible to say.
QuerySelectorAll will get all the matching elements with defined selector. Here on the example I've used element's name(li
tag) to get all of the li
present inside the div with navbar
element.
let navbar = document_x000D_
.getElementById("navbar")_x000D_
.querySelectorAll('li');_x000D_
_x000D_
navbar.forEach((item, index) => {_x000D_
console.log({ index, item })_x000D_
});
_x000D_
_x000D_
<div id="navbar">_x000D_
<ul>_x000D_
<li id="navbar-One">One</li>_x000D_
<li id="navbar-Two">Two</li>_x000D_
<li id="navbar-Three">Three</li>_x000D_
<li id="navbar-Four">Four</li>_x000D_
<li id="navbar-Five">Five</li>_x000D_
</ul>_x000D_
</div>
_x000D_
Numbers have higher precedence than strings so of course the +
operators want to convert your strings into numbers before adding.
You could do:
print 'There are ' + CONVERT(varchar(10),@Number) +
' alias combinations did not match a record'
or use the (rather limited) formatting facilities of RAISERROR
:
RAISERROR('There are %i alias combinations did not match a record',10,1,@Number)
WITH NOWAIT
You seem to be unnecessarily setting properties on your ComboBox
. You can remove the DisplayMemberPath
and SelectedValuePath
properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:
<ComboBox Name="cbxSalesPeriods"
ItemsSource="{Binding SalesPeriods}"
SelectedItem="{Binding SelectedSalesPeriod}"
IsSynchronizedWithCurrentItem="True"/>
Furthermore, it is pointless using your displayPeriod
property, as the WPF Framework would call the ToString
method automatically for objects that it needs to display that don't have a DataTemplate
set up for them explicitly.
UPDATE >>>
As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless displayPeriod
property and also your SalesPeriodVO
property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:
public class SalesPeriodV
{
private int month, year;
public int Year
{
get { return year; }
set
{
if (year != value)
{
year = value;
NotifyPropertyChanged("Year");
}
}
}
public int Month
{
get { return month; }
set
{
if (month != value)
{
month = value;
NotifyPropertyChanged("Month");
}
}
}
public override string ToString()
{
return String.Format("{0:D2}.{1}", Month, Year);
}
public virtual event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(params string[] propertyNames)
{
if (PropertyChanged != null)
{
foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
}
}
}
Then I added two properties into the view model:
private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
get { return salesPeriods; }
set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
get { return selectedItem; }
set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}
Then initialised the collection with your values:
SalesPeriods.Add(new SalesPeriodV() { Month = 3, Year = 2013 } );
SalesPeriods.Add(new SalesPeriodV() { Month = 4, Year = 2013 } );
And then data bound only these two properties to a ComboBox
:
<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />
That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the ToString
method without your displayPeriod
property. Hopefully, you can work out your mistakes from this code example.
document.location.href="/";
If the to-be-updated component is not inside the same NamingContainer
component (ui:repeat
, h:form
, h:dataTable
, etc), then you need to specify the "absolute" client ID. Prefix with :
(the default NamingContainer
separator character) to start from root.
<p:ajax process="@this" update="count :subTotal"/>
To be sure, check the client ID of the subTotal
component in the generated HTML for the actual value. If it's inside for example a h:form
as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.
<p:ajax process="@this" update="count :formId:subTotal"/>
Space separation of IDs is more recommended as <f:ajax>
doesn't support comma separation and starters would otherwise get confused.
You Should choose the first one. They have no difference except the performance the first one will be the fast in the comparison of second one.
If the variable inside the double quote PHP take time to parse variable.
Check out this Single quotes or double quotes for variable concatenation?
This is another example Is there a performance benefit single quote vs double quote in php?
I did not understand why this answer in above link get upvoted and why this answer got downvote.
As I said same thing.
You can look at here as well
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
It's possible you're seeing OpenDirectory/ActiveDirectory/LDAP users "automounted" into your home directory.
In *nix, ~
will resolve to your home directory. Likewise ~X
will resolve to 'user X'.
Similar to automount for directories, OpenDirectory/ActiveDirectory/LDAP is used in larger/corporate environments to automount user directories. These users may be actual people or they can be machine accounts created to provide various features.
If you type ~Tab you'll see a list of the users on your machine.
After making no changes to a production server we began receiving this error. After trying several different things and thinking that perhaps there were DNS issues, restarting IIS fixed the issue (restarting only the site did not fix the issue). It likely won't work for everyone but if we tried that first it would have saved a lot of time.
"On Windows and Mac OS X, the CPython installers now default to installing pip along with CPython itself (users may opt out of installing it during the installation process). Window users will need to opt in to the automatic PATH modifications to have pip available from the command line by default, otherwise it can still be accessed through the Python launcher for Windows as py -m pip."
Have you tried it?
serialVersionUID
facilitates versioning of serialized data. Its value is stored with the data when serializing. When de-serializing, the same version is checked to see how the serialized data matches the current code.
If you want to version your data, you normally start with a serialVersionUID
of 0, and bump it with every structural change to your class which alters the serialized data (adding or removing non-transient fields).
The built-in de-serialization mechanism (in.defaultReadObject()
) will refuse to de-serialize from old versions of the data. But if you want to you can define your own readObject()-function which can read back old data. This custom code can then check the serialVersionUID
in order to know which version the data is in and decide how to de-serialize it. This versioning technique is useful if you store serialized data which survives several versions of your code.
But storing serialized data for such a long time span is not very common. It is far more common to use the serialization mechanism to temporarily write data to for instance a cache or send it over the network to another program with the same version of the relevant parts of the codebase.
In this case you are not interested in maintaining backwards compatibility. You are only concerned with making sure that the code bases which are communicating indeed have the same versions of relevant classes. In order to facilitate such a check, you must maintain the serialVersionUID
just like before and not forget to update it when making changes to your classes.
If you do forget to update the field, you might end up with two different versions of a class with different structure but with the same serialVersionUID
. If this happens, the default mechanism (in.defaultReadObject()
) will not detect any difference, and try to de-serialize incompatible data. Now you might end up with a cryptic runtime error or silent failure (null fields). These types of errors might be hard to find.
So to help this usecase, the Java platform offers you a choice of not setting the serialVersionUID
manually. Instead, a hash of the class structure will be generated at compile-time and used as id. This mechanism will make sure that you never have different class structures with the same id, and so you will not get these hard-to-trace runtime serialization failures mentioned above.
But there is a backside to the auto-generated id strategy. Namely that the generated ids for the same class might differ between compilers (as mentioned by Jon Skeet above). So if you communicate serialized data between code compiled with different compilers, it is recommended to maintain the ids manually anyway.
And if you are backwards-compatible with your data like in the first use case mentioned, you also probably want to maintain the id yourself. This in order to get readable ids and have greater control over when and how they change.
Firefox does not support the MPEG H.264 (mp4) format at this time, due to a philosophical disagreement with the closed-source nature of the format.
To play videos in all browsers without using plugins, you will need to host multiple copies of each video, in different formats. You will also need to use an alternate form of the video
tag, as seen in the JSFiddle from @TimHayes above, reproduced below. Mozilla claims that only mp4 and WebM are necessary to ensure complete coverage of all major browsers, but you may wish to consult the Video Formats and Browser Support heading on W3C's HTML5 Video page to see which browser supports what formats.
Additionally, it's worth checking out the HTML5 Video page on Wikipedia for a basic comparison of the major file formats.
Below is the appropriate video
tag (you will need to re-encode your video in WebM or OGG formats as well as your existing mp4):
<video id="video" controls='controls'>
<source src="videos/clip.mp4" type="video/mp4"/>
<source src="videos/clip.webm" type="video/webm"/>
<source src="videos/clip.ogv" type="video/ogg"/>
Your browser doesn't seem to support the video tag.
</video>
Updated Nov. 8, 2013
Network infrastructure giant Cisco has announced plans to open-source an implementation of the H.264 codec, removing the licensing fees that have so far proved a barrier to use by Mozilla. Without getting too deep into the politics of it (see following link for that) this will allow Firefox to support H.264 starting in "early 2014". However, as noted in that link, this still comes with a caveat. The H.264 codec is merely for video, and in the MPEG-4 container it is most commonly paired with the closed-source AAC audio codec. Because of this, playback of H.264 video will work, but audio will depend on whether the end-user has the AAC codec already present on their machine.
The long and short of this is that progress is being made, but you still can't avoid using multiple encodings without using a plugin.
In acrhiecture - sometimes to support 6.0 and 7.0 , we exlude arm64
In architectures - > acrchitecture - select standard architecture arm64 armv7 armv7s. Just below in Valid acrchitecture make user arm64 armv7 armv7s is included. This worked for me.
No need to remember flags. Remember that you can always do:
subprocess.call(["chmod", "a-w", "file/path])
Not portable but easy to write and remember:
Refer man chmod
for additional options and more detailed explanation.
Two issues I can see here:
The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.
The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.
With quotes around the date:
mysql> CALL insertEvent('2012.01.01 12:12:12');
Funnily enough, adjusting the padding seems to do it.
.arrow {
border: solid rgb(2, 0, 0);
border-width: 0 3px 3px 0;
display: inline-block;
}
.first{
padding: 2vh;
}
.second{
padding: 4vh;
}
.left {
transform: rotate(135deg);
-webkit-transform: rotate(135deg);
}
_x000D_
<i class="arrow first left"></i>
<i class="arrow second left"></i>
_x000D_
Using ES6,
you can use forEach
to iterate over the Keys of an Object.
To get all the keys you can use Object.keys
which returns all the keys in an Object
Object.keys(obj).forEach(function(keyValue, index, map) {
console.log(keyValue);
});
Short hand of the above snippet would be, which only takes one parameter
Object.keys(obj).forEach(function(keyValue) {
console.log(keyValue);
});
No, this seems perfectly reasonable. There is a List<T>.AddRange()
method that basically does just this, but requires your collection to be a concrete List<T>
.
Alternatively you could use:
if ($('#navigation a').is(".active")) {
$(this).parent().addClass("active");
}
print("sorted counting values:-")
from collections import Counter
fname = open(filename)
fname = fname.read()
fsplit = fname.split()
user = Counter(fsplit)
for i,v in sorted(user.items()):
print((v,i))
new Buffer(number) // Old
Buffer.alloc(number) // New
new Buffer(string) // Old
Buffer.from(string) // New
new Buffer(string, encoding) // Old
Buffer.from(string, encoding) // New
new Buffer(...arguments) // Old
Buffer.from(...arguments) // New
Note that Buffer.alloc() is also faster on the current Node.js versions than new Buffer(size).fill(0), which is what you would otherwise need to ensure zero-filling.
String
is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.
If you want to manipulate a string, consider StringBuilder
or StringBuffer
in case you require thread safety.
I had the same problem and solved it completely by running VS Code as Administrator.
I used the above mentioned solutions (npm install -g @angular/cli@latest & npm install @angular/cli in my project), tried ng serve both in cmd and VS Code terminal but didn't work, while npm run ng serve could run in VS Code terminal, but I wasn't satisfied with that. After that I set the path in the environment variables exactly like this "C:\Users\TheUserName\AppData\Roaming\npm" and still wasn't able to run ng serve.
Then I ran VS Code as Administrator and it finally worked. It even recognized another command, gulp, which didn't recognize till then, even though I had it also correctly installed. Not sure why it had this behavior and I would like an explanation.
Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).
The examples you gave (int
, array, double
) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int
:
int x;
You can be sure it will only ever hold int
values.
If you declared a variable to be a List
, however, it is possible that the variable will hold sub-types of List
. Examples of these include ArrayList
, LinkedList
, etc.
If you did have a List
variable, and you needed to know if it was an ArrayList
, you could do the following:
List y;
...
if (y instanceof ArrayList) {
...its and ArrayList...
}
However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.
Selenium2Library has get_location():
import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()
If you don't have anything overflowing horizontally, you can also just use
overflow: auto;
and it will only show scrollbars when needed.
For linux/unix OS, you can use the shell syntax
const shell = require('child_process').execSync ;
const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;
shell(`mv ${currentPath} ${newPath}`);
That's it!
Unfortunately it's out of our hands whether the package writer bothers with a declaration file. What I tend to do is have a file such index.d.ts
that'll contain all the missing declaration files from various packages:
Index.ts:
declare module 'v-tooltip';
declare module 'parse5';
declare module 'emoji-mart-vue-fast';
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
Although currently there is no way to declare a method or property as private, ES6 modules are not in the global namespace. Therefore, anything that you declare in your module and do not export will not be available to any other part of your program, but will still be available to your module during run time. Thus, you have private properties and methods :)
Here is an example
(in test.js
file)
function tryMe1(a) {
console.log(a + 2);
}
var tryMe2 = 1234;
class myModule {
tryMe3(a) {
console.log(a + 100);
}
getTryMe1(a) {
tryMe1(a);
}
getTryMe2() {
return tryMe2;
}
}
// Exports just myModule class. Not anything outside of it.
export default myModule;
In another file
import MyModule from './test';
let bar = new MyModule();
tryMe1(1); // ReferenceError: tryMe1 is not defined
tryMe2; // ReferenceError: tryMe2 is not defined
bar.tryMe1(1); // TypeError: bar.tryMe1 is not a function
bar.tryMe2; // undefined
bar.tryMe3(1); // 101
bar.getTryMe1(1); // 3
bar.getTryMe2(); // 1234
Just a tip, in case you are having trouble with the replace function, you might have the datatype set to nchar (in which case it is a fixed length and it will not work).
This should do the job. It provides the client IP address (remote host).
Note that this code is running on the server side.
from mod_python import apache
req.get_remote_host(apache.REMOTE_NOLOOKUP)
xhr.file = file;
; the file object is not supposed to be attached this way.xhr.send(file)
doesn't send the file. You have to use the FormData
object to wrap the file into a multipart/form-data
post data object:
var formData = new FormData();
formData.append("thefile", file);
xhr.send(formData);
After that, the file can be access in $_FILES['thefile']
(if you are using PHP).
Remember, MDC and Mozilla Hack demos are your best friends.
EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.
Can you not use like this?
@Query("SELECT DISTINCT name FROM people p (nolock) WHERE p.name NOT IN (:myparam)")
List<String> findNonReferencedNames(@Param("myparam")List<String> names);
P.S. I write queries in SQL Server 2012 a lot and using nolock
in server is a good practice, you can ignore nolock
if a local db is used.
Seems like your db name is not being mapped correctly (after you've updated your question)
You could do a select on the tables inserting commas after each field to produce a csv, or use a GUI tool to return all the data and save it to a csv.
Use inputstream once don't use it multiple times and Do inputstream.close()
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.folderview_options, menu);
return (super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.locationListRefreshLocations) {
Cursor temp = helper.getEmployee(active_employeeId);
String[] matches = new String[1];
if (temp.moveToFirst()) {
matches[0] = helper.getEmployerID(temp);
}
temp.close();
startRosterReceiveBackgroundTask(matches);
} else if (item.getItemId()==R.id.locationListPrefs) {
startActivity(new Intent(this, PreferencesUnlockScreen.class));
return true;
}
return super.onOptionsItemSelected(item);
}
When you pass an object like this:
new SelectList(Model, "Code", "Name", 0)
you are saying: the Source (Model
) and Key ("Code"
) the Text ("Name"
) and the selected value 0
. You probably do not have a 0
value in your source for Code
property, so the HTML Helper will select the first element to pass the real selectedValue to this control.
You can try Query String Object plugin for jQuery.
yes, simply use colspan.
try this:-
select to_char(to_date('01/10/2017','dd/mm/yyyy'),'fmMonth fmDD,YYYY') from dual;
select to_char(sysdate,'fmMonth fmDD,YYYY') from dual;
__FUNCTION__
is non standard, __func__
exists in C99 / C++11. The others (__LINE__
and __FILE__
) are just fine.
It will always report the right file and line (and function if you choose to use __FUNCTION__
/__func__
). Optimization is a non-factor since it is a compile time macro expansion; it will never affect performance in any way.
Yes.
Field f = Test.class.getDeclaredField("str");
f.setAccessible(true);//Very important, this allows the setting to work.
String value = (String) f.get(object);
Then you use the field object to get the value on an instance of the class.
Note that get method is often confusing for people. You have the field, but you don't have an instance of the object. You have to pass that to the get
method
For instance you can use
update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'
You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.
Please try something like:
=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))
You seem to have three main possible scenarios:
ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.
I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.
This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.
This with =FIND which looks for a space (" "
) in C1
, starting with the eighth character within C1
counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.
Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.
So
=VALUE(LEFT(C1,FIND(" ",C1,8)))
returns 40671
in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.
If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:
=RIGHT(C2,4)
Takes the last four characters of C2, hence 2011
in this example.
=MID(C2,4,2)
Starting at the fourth character, takes the next two characters of C2, hence 05
in this example (representing May).
=LEFT(C2,2))
Takes the first two characters of C2, hence 08
in this example (representing the 8th day of the month).
Date is not a text function so does not need to be wrapped in =VALUE.
Taken together
=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2))
also returns 40671
in this example, but from different input from Case #1.
Is simple because already a date serial number, so just
=C2
is sufficient.
Put the above together to cover all three cases in a single formula:
=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))
as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH: