Necromancing.
It looks you have just as good a schema to work with as me...
Here is how to do it correctly:
In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID
-- First, chech if the table exists...
IF 0 < (
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
-- Check for NULL values in the primary-key column
IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
BEGIN
ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL
-- No, don't drop, FK references might already exist...
-- Drop PK if exists
-- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name
--DECLARE @pkDropCommand nvarchar(1000)
--SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
--WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
--AND TABLE_SCHEMA = 'dbo'
--AND TABLE_NAME = 'T_SYS_Language_Forms'
----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
--))
---- PRINT @pkDropCommand
--EXECUTE(@pkDropCommand)
-- Instead do
-- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';
-- Check if they keys are unique (it is very possible they might not be)
IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
BEGIN
-- If no Primary key for this table
IF 0 =
(
SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE CONSTRAINT_TYPE = 'PRIMARY KEY'
AND TABLE_SCHEMA = 'dbo'
AND TABLE_NAME = 'T_SYS_Language_Forms'
-- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms'
)
ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
;
-- Adding foreign key
IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms')
ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID);
END -- End uniqueness check
ELSE
PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...'
END -- End NULL check
ELSE
PRINT 'FSCK, need to figure out how to update NULL value(s)...'
END
According with the HTTP/1.1 standard, the shared IP hosted site can be accessed by a GET request with the IP as URL and a header of the host.
Here there are two examples(wget and curl):
$ wget --header 'Host:somerandomservice.com' http://67.225.235.59
$ curl --header 'Host:somerandomservice.com' http://67.225.235.59
Resources:
https://en.wikipedia.org/wiki/Shared_web_hosting_service
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.23
When i use relative path "dir/file.php" with in the header() function in works for me. I think that the session is not saved for some reason when you redirect using the full url...
//Does retain the session info for some reason
header("Location: dir");
//Does not retain the session for some reason
header("Location: https://mywebz.com/dir")
The simplest approach would be to make use of the to:object
within link
as mentioned in documentation:
https://reactrouter.com/web/api/Link/to-object
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true, id: 1 }
}}
/>
We can retrieve above params (state) as below:
this.props.location.state // { fromDashboard: true ,id: 1 }
This could work if the PHP script generates a form for each entry with hidden fields and the href uses JavaScript to post the form.
You can use this free service by adding a link which creates pdf from any url (e.g. http://www.phys.org):
The System.DateTime
class has a property called Now
, which:
Gets a
DateTime
object that is set to the current date and time on this computer, expressed as the local time.
You can set the Text
property of your label to the current time like this (where myLabel
is the name of your label):
myLabel.Text = DateTime.Now.ToString();
There is a very fundamental difference between the two. In case of Singleton design pattern, only one instance of a class will be created per classLoader while that is not the case with Spring singleton as in the later one shared bean instance for the given id per IoC container is created.
For example, if I have a class with the name "SpringTest" and my XML file looks something like this :-
<bean id="test1" class="com.SpringTest" scope="singleton">
--some properties here
</bean>
<bean id="test2" class="com.SpringTest" scope="singleton">
--some properties here
</bean>
So now in the main class if you will check the reference of the above two it will return false as according to Spring documentation:-
When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container
So as in our case, the classes are the same but the id's that we have provided are different hence resulting in two different instances being created.
To clarify for anyone who is looking for what is the difference between the 3 on a simpler level. You can expose your service with minimal ClusterIp (within k8s cluster) or larger exposure with NodePort (within cluster external to k8s cluster) or LoadBalancer (external world or whatever you defined in your LB).
ClusterIp exposure < NodePort exposure < LoadBalancer exposure
ip/name:port
ip/name:port
If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:
PARAMETERS SomeParam Text(10);
SELECT Field FROM Table
WHERE OtherField=SomeParam
You can also say:
CREATE PROCEDURE ProcedureName
(Parameter1 datatype, Parameter2 datatype) AS
SQLStatement
From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs
Note that the procedure contains only one statement.
new
will initialise the default values of the struct and correctly links the references in it to itself.
E.g.
struct test_s {
int some_strange_name = 1;
int &easy = some_strange_name;
}
So new struct test_s
will return an initialised structure with a working reference, while the malloc'ed version has no default values and the intern references aren't initialised.
You should use python Explicit Conversion Flag PEP-3101
'My name is {0!s:10} {1}'.format('Dunkin', 'Donuts')
'My name is Dunkin Donuts'
or
'My name is %-10s %s' % ('Dunkin', 'Donuts')
'My name is Dunkin Donuts'
After looking for an answer for this question I found a brilliant explanation with an example that I would like to share with you.
You can watch a video that demonstrate the differences HERE
In this example we have this given code:
public interface IEmployeeRepository
{
IEnumerable<Employee> GetAllEmployees();
Employee Add(Employee employee);
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MockEmployeeRepository : IEmployeeRepository
{
private List<Employee> _employeeList;
public MockEmployeeRepository()
{
_employeeList = new List<Employee>()
{
new Employee() { Id = 1, Name = "Mary" },
new Employee() { Id = 2, Name = "John" },
new Employee() { Id = 3, Name = "Sam" },
};
}
public Employee Add(Employee employee)
{
employee.Id = _employeeList.Max(e => e.Id) + 1;
_employeeList.Add(employee);
return employee;
}
public IEnumerable<Employee> GetAllEmployees()
{
return _employeeList;
}
}
HomeController
public class HomeController : Controller
{
private IEmployeeRepository _employeeRepository;
public HomeController(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
[HttpGet]
public ViewResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Employee employee)
{
if (ModelState.IsValid)
{
Employee newEmployee = _employeeRepository.Add(employee);
}
return View();
}
}
Create View
@model Employee
@inject IEmployeeRepository empRepository
<form asp-controller="home" asp-action="create" method="post">
<div>
<label asp-for="Name"></label>
<div>
<input asp-for="Name">
</div>
</div>
<div>
<button type="submit">Create</button>
</div>
<div>
Total Employees Count = @empRepository.GetAllEmployees().Count().ToString()
</div>
</form>
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IEmployeeRepository, MockEmployeeRepository>();
}
Copy-paste this code and press on the create button in the view and switch between
AddSingleton
, AddScoped
and AddTransient
you will get each time a different result that will might help you understand this.
AddSingleton() - As the name implies, AddSingleton() method creates a Singleton service. A Singleton service is created when it is first requested. This same instance is then used by all the subsequent requests. So in general, a Singleton service is created only one time per application and that single instance is used throughout the application life time.
AddTransient() - This method creates a Transient service. A new instance of a Transient service is created each time it is requested.
AddScoped() - This method creates a Scoped service. A new instance of a Scoped service is created once per request within the scope. For example, in a web application it creates 1 instance per each http request but uses the same instance in the other calls within that same web request.
I got this error after change a loop in my program, let`s see:
for ...
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:
for ...
x_batch = []
y_batch = []
for ...
x_batch.append(one_hot(int_word, vocab_size))
y_batch.append(one_hot(int_nb, vocab_size, value))
...
...
if ...
x_batch = np.asarray(x_batch)
y_batch = np.asarray(y_batch)
...
Then, check if you are using np.asarray() or something like that.
Based on the code here: http://cplusplus.happycodings.com/algorithms/code17.html
// Merge Sort
#include <iostream>
using namespace std;
int a[50];
void merge(int,int,int);
void merge_sort(int low,int high)
{
int mid;
if(low<high)
{
mid = low + (high-low)/2; //This avoids overflow when low, high are too large
merge_sort(low,mid);
merge_sort(mid+1,high);
merge(low,mid,high);
}
}
void merge(int low,int mid,int high)
{
int h,i,j,b[50],k;
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
int main()
{
int num,i;
cout<<"*******************************************************************
*************"<<endl;
cout<<" MERGE SORT PROGRAM
"<<endl;
cout<<"*******************************************************************
*************"<<endl;
cout<<endl<<endl;
cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort [THEN
PRESS
ENTER]:"<<endl;
cin>>num;
cout<<endl;
cout<<"Now, Please Enter the ( "<< num <<" ) numbers (ELEMENTS) [THEN
PRESS ENTER]:"<<endl;
for(i=1;i<=num;i++)
{
cin>>a[i] ;
}
merge_sort(1,num);
cout<<endl;
cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl;
cout<<endl<<endl;
for(i=1;i<=num;i++)
cout<<a[i]<<" ";
cout<<endl<<endl<<endl<<endl;
return 1;
}
You can use Ruby's Net::HTTP
class:
require 'net/http'
url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts res.body
You can also use the following to delete the remote branch
git push --delete origin serverfix
Which does the same thing as
git push origin :serverfix
but it may be easier to remember.
Here is a situation where you can divide by zero. The business rule is that to calculate inventory turns, you take cost of goods sold for a period, annualize it. After you have the annualized number, you divide by the average inventory for the period.
I'm looking at calculating the number of inventory turns that occur in a three month period. I have calculated that I have Cost of Goods sold during the three month period of $1,000. The annual rate of sales is $4,000 ($1,000/3)*12. The beginning inventory is 0. The ending inventory is 0. My average inventory is now 0. I have sales of $4000 per year, and no inventory. This yields an infinite number of turns. This means that all my inventory is being converted and purchased by customers.
This is a business rule of how to calculate inventory turns.
Change the database.php file from
$db['default']['dbdriver'] = 'mysql';
to
$db['default']['dbdriver'] = 'mysqli';
At least in .NET 4.5+ you can also do:
var uri = new System.Uri("C:\\foo", UriKind.Absolute);
If your current line wraps around the visible screen onto the next line, you can use g$ to get to the end of the screen line.
Run following command in git bash that works fine for me
git config --global http.sslverify "false"
For example:
sqlplus -s admin/password << EOF
whenever sqlerror exit sql.sqlcode;
set echo off
set heading off
@pl_script_1.sql
@pl_script_2.sql
exit;
EOF
Another alternative is to use any web hosting with webdav support. You will need some space for this somewhere of course but it is straightforward to set up and a good alternative to running a full blown nexus server.
add this to your build section
<extensions>
<extension>
<artifactId>wagon-webdav-jackrabbit</artifactId>
<groupId>org.apache.maven.wagon</groupId>
<version>2.2</version>
</extension>
</extensions>
Add something like this to your distributionManagement section
<repository>
<id>release.repo</id>
<url>dav:http://repo.jillesvangurp.com/releases/</url>
</repository>
Finally make sure to setup the repository access in your settings.xml
add this to your servers section
<server>
<id>release.repo</id>
<username>xxxx</username>
<password>xxxx</password>
</server>
and a definition to your repositories section
<repository>
<id>release.repo</id>
<url>http://repo.jillesvangurp.com/releases</url>
<releases>
<enabled>true</enabled>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
Finally, if you have any standard php hosting, you can use something like sabredav to add webdav capabilities.
Advantages: you have your own maven repository Downsides: you don't have any of the management capabilities in nexus; you need some webdav setup somewhere
Try on this way
function timenow(){
var now= new Date(),
ampm= 'am',
h= now.getHours(),
m= now.getMinutes(),
s= now.getSeconds();
if(h>= 12){
if(h>12) h -= 12;
ampm= 'pm';
}
if(m<10) m= '0'+m;
if(s<10) s= '0'+s;
return now.toLocaleDateString()+ ' ' + h + ':' + m + ':' + s + ' ' + ampm;
}
toLocaleDateString()
is a function to change the date time format like toLocaleDateString("en-us")
If you want to move the mouse, use this:
import pyautogui
pyautogui.moveTo(x,y)
If you want to click, use this:
import pyautogui
pyautogui.click(x,y)
If you don't have pyautogui
installed, you must have python attached to CMD. Go to CMD and write: pip install pyautogui
This will install pyautogui
for Python 2.x.
For Python 3.x, you will probably have to use pip3 install pyautogui
or python3 -m pip install pyautogui
.
You could use
options(warn=-1)
But note that turning off warning messages globally might not be a good idea.
To turn warnings back on, use
options(warn=0)
(or whatever your default is for warn
, see this answer)
I did
msgbox "TEXT HERE",3,"TITLE HERE"
If Yes=true then
(result)
else
msgbox "Closing..."
For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,
as a reference of available options see sprintf
#include <stdio.h>
int main ()
{
unsigned long lval = 123;
char buffer [50];
sprintf (buffer, "%lu" , lval );
}
You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(
If you don't wrap the text node in a <span>
like @Jacob suggests, you could instead give the surrounding element padding
as opposed to margin
:
<p id="theParagraph">The text node!</p>
p#theParagraph
{
border: 1px solid red;
padding-bottom: 10px;
}
The problem that you are facing is : TypeError : str returned non-string (type NoneType)
Here you have to understand the str function's working: the str fucntion,although is mostly used to print values but actually is designed to return a string,not to print one. In your class str function is calling the print directly while it is returning nothing ,that explains your error output.Since our formatted string is built, and since our function returns nothing, the None value is used. This was the explaination for your error
You can solve this problem by using the return in str function like: *simply returnig the string value instead of printing it
class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)
def __str__(self):
return self.summary
but if the value you are returning in not of string type then you can do like this to return string value from your str function
*typeconverting the value to string that your str function returns
class Summary(models.Model):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
summary = models.TextField(max_length=600)
def __str__(self):
return str(self.summary)
`
In your second statement
import {FriendCard} from './../pages/FriendCard'
you are telling typescript to import the FriendCard class from the file './pages/FriendCard'
Your FriendCard file is exporting a variable and that variable is referencing the anonymous function.
You have two options here. If you want to do this in a typed way you can refactor your module to be typed (option 1) or you can import the anonymous function and add a d.ts file. See https://github.com/Microsoft/TypeScript/issues/3019 for more details. about why you need to add the file.
Refactor the Friend card js file to be typed.
export class FriendCard {
webElement: any;
menuButton: any;
serialNumber: any;
constructor(card) {
this.webElement = card;
this.menuButton;
this.serialNumber;
}
getAsWebElement = function () {
return this.webElement;
};
clickMenuButton = function () {
this.menuButton.click();
};
setSerialNumber = function (numberOfElements) {
this.serialNumber = numberOfElements + 1;
this.menuButton = element(by.xpath('.//*[@id=\'mCSB_2_container\']/li[' + serialNumber + ']/ng-include/div/div[2]/i'));
};
deleteFriend = function () {
element(by.css('[ng-click="deleteFriend(person);"]')).click();
element(by.css('[ng-click="confirm()"]')).click();
}
};
You can import the anonymous function
import * as FriendCard from module("./FriendCardJs");
There are a few options for a d.ts file definition. This answer seems to be the most complete: How do you produce a .d.ts "typings" definition file from an existing JavaScript library?
On your onCreate
method add:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
While defining in the AndroidManifest.xml
the parent activity (the activity that will be called once the back button in the action bar is pressed):
In your <activity>
definition on the Manifest, add the line:
android:parentActivityName="com.example.activities.MyParentActivity"
Reasons to prefer Service Locator over Inversion of Control (IoC) are:
Service Locator is much, much easier for other people to following in your code. IoC is 'magic' but maintenance programmers must understand your convoluted Spring configurations and all the myriad of locations to figure out how you wired your objects.
IoC is terrible for debugging configuration problems. In certain classes of applications the application will not start when misconfigured and you may not get a chance to step through what is going on with a debugger.
IoC is primarily XML based (Annotations improve things but there is still a lot of XML out there). That means developers can't work on your program unless they know all the magic tags defined by Spring. It is not good enough to know Java anymore. This hinders less experience programmers (ie. it is actually poor design to use a more complicated solution when a simpler solution, such as Service Locator, will fulfill the same requirements). Plus, support for diagnosing XML problems is far weaker than support for Java problems.
Dependency injection is more suited to larger programs. Most of the time the additional complexity is not worth it.
Often Spring is used in case you "might want to change the implementation later". There are other ways of achieving this without the complexity of Spring IoC.
For web applications (Java EE WARs) the Spring context is effectively bound at compile time (unless you want operators to grub around the context in the exploded war). You can make Spring use property files, but with servlets property files will need to be at a pre-determined location, which means you can't deploy multiple servlets of the same time on the same box. You can use Spring with JNDI to change properties at servlet startup time, but if you are using JNDI for administrator-modifiable parameters the need for Spring itself lessens (since JNDI is effectively a Service Locator).
With Spring you can lose program Control if Spring is dispatching to your methods. This is convenient and works for many types of applications, but not all. You may need to control program flow when you need to create tasks (threads etc) during initialization or need modifiable resources that Spring didn't know about when the content was bound to your WAR.
Spring is very good for transaction management and has some advantages. It is just that IoC can be over-engineering in many situations and introduce unwarranted complexity for maintainers. Do not automatically use IoC without thinking of ways of not using it first.
I had similar issue when connecting to RDS Oracle even when client and server were both set to TLSv1.2 the certs was right and java was 1.8.0_141 So Finally I had to apply patch at Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files
After applying the patch the issue went away and connection went fine.
To use support libraries starting from version 26.0.0 you need to add Google's Maven repository to your project's build.gradle file as described here: https://developer.android.com/topic/libraries/support-library/setup.html
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
For Android Studio 3.0.0 and above:
allprojects {
repositories {
jcenter()
google()
}
}
TortoiseGit has matured and I recommend it especially if you have used TortoiseSVN.
In entity relationship modeling, solid lines represent strong relationships and dashed lines represent weak relationships.
Part of the problem here is that the strings usually used to represent timezones are not actually unique. "EST" only means "America/New_York" to people in North America. This is a limitation in the C time API, and the Python solution is… to add full tz features in some future version any day now, if anyone is willing to write the PEP.
You can format and parse a timezone as an offset, but that loses daylight savings/summer time information (e.g., you can't distinguish "America/Phoenix" from "America/Los_Angeles" in the summer). You can format a timezone as a 3-letter abbreviation, but you can't parse it back from that.
If you want something that's fuzzy and ambiguous but usually what you want, you need a third-party library like dateutil
.
If you want something that's actually unambiguous, just append the actual tz name to the local datetime string yourself, and split it back off on the other end:
d = datetime.datetime.now(pytz.timezone("America/New_York"))
dtz_string = d.strftime(fmt) + ' ' + "America/New_York"
d_string, tz_string = dtz_string.rsplit(' ', 1)
d2 = datetime.datetime.strptime(d_string, fmt)
tz2 = pytz.timezone(tz_string)
print dtz_string
print d2.strftime(fmt) + ' ' + tz_string
Or… halfway between those two, you're already using the pytz
library, which can parse (according to some arbitrary but well-defined disambiguation rules) formats like "EST". So, if you really want to, you can leave the %Z
in on the formatting side, then pull it off and parse it with pytz.timezone()
before passing the rest to strptime
.
You can also use this also
def n3bu1A(n):
o=""
key = {
'a':'n', 'b':'o', 'c':'p', 'd':'q', 'e':'r', 'f':'s', 'g':'t', 'h':'u',
'i':'v', 'j':'w', 'k':'x', 'l':'y', 'm':'z', 'n':'a', 'o':'b', 'p':'c',
'q':'d', 'r':'e', 's':'f', 't':'g', 'u':'h', 'v':'i', 'w':'j', 'x':'k',
'y':'l', 'z':'m', 'A':'N', 'B':'O', 'C':'P', 'D':'Q', 'E':'R', 'F':'S',
'G':'T', 'H':'U', 'I':'V', 'J':'W', 'K':'X', 'L':'Y', 'M':'Z', 'N':'A',
'O':'B', 'P':'C', 'Q':'D', 'R':'E', 'S':'F', 'T':'G', 'U':'H', 'V':'I',
'W':'J', 'X':'K', 'Y':'L', 'Z':'M'}
for x in n:
v = x in key.keys()
if v == True:
o += (key[x])
else:
o += x
return o
Yes = n3bu1A("N zhpu fvzcyre jnl gb fnl Guvf vf zl Zragbe!!")
print(Yes)
If you're not too bothered about the width of the padding, this solution will actually keep the padding in percentages too..
textarea
{
border:1px solid #999999;
width:98%;
margin:5px 0;
padding:1%;
}
Not perfect, but you'll get some padding and the width adds up to 100% so its all good
I personally like using setdefault()
my_dict = {}
my_dict.setdefault(some_key, 0)
my_dict[some_key] += 1
The simplest answer is:
On whichever method you declare @Transactional
the boundary of transaction starts and boundary ends when method completes.
If you are using JPA call then all commits are with in this transaction boundary.
Lets say you are saving entity1, entity2 and entity3. Now while saving entity3 an exception occur, then as enitiy1 and entity2 comes in same transaction so entity1 and entity2 will be rollback with entity3.
Transaction :
- entity1.save
- entity2.save
- entity3.save
Any exception will result in rollback of all JPA transactions with DB.Internally JPA transaction are used by Spring.
WebSockets is protocol that relies on TCP streamed connection. Although WebSockets is Message based protocol.
If you want to implement your own protocol then I recommend to use latest and stable specification (for 18/04/12) RFC 6455. This specification contains all necessary information regarding handshake and framing. As well most of description on scenarios of behaving from browser side as well as from server side. It is highly recommended to follow what recommendations tells regarding server side during implementing of your code.
In few words, I would describe working with WebSockets like this:
Create server Socket (System.Net.Sockets) bind it to specific port, and keep listening with asynchronous accepting of connections. Something like that:
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8080)); serverSocket.Listen(128); serverSocket.BeginAccept(null, 0, OnAccept, null);
You should have accepting function "OnAccept" that will implement handshake. In future it has to be in another thread if system is meant to handle huge amount of connections per second.
private void OnAccept(IAsyncResult result) { try { Socket client = null; if (serverSocket != null && serverSocket.IsBound) { client = serverSocket.EndAccept(result); } if (client != null) { /* Handshaking and managing ClientSocket */ } } catch(SocketException exception) { } finally { if (serverSocket != null && serverSocket.IsBound) { serverSocket.BeginAccept(null, 0, OnAccept, null); } } }
After connection established, you have to do handshake. Based on specification 1.3 Opening Handshake, after connection established you will receive basic HTTP request with some information. Example:
GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13
This example is based on version of protocol 13. Bear in mind that older versions have some differences but mostly latest versions are cross-compatible. Different browsers may send you some additional data. For example Browser and OS details, cache and others.
Based on provided handshake details, you have to generate answer lines, they are mostly same, but will contain Accpet-Key, that is based on provided Sec-WebSocket-Key. In specification 1.3 it is described clearly how to generate response key. Here is my function I've been using for V13:
static private string guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; private string AcceptKey(ref string key) { string longKey = key + guid; SHA1 sha1 = SHA1CryptoServiceProvider.Create(); byte[] hashBytes = sha1.ComputeHash(System.Text.Encoding.ASCII.GetBytes(longKey)); return Convert.ToBase64String(hashBytes); }
Handshake answer looks like that:
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
But accept key have to be the generated one based on provided key from client and method AcceptKey I provided before. As well, make sure after last character of accept key you put two new lines "\r\n\r\n".
Implementing own WebSockets protocol definitely have some benefits and great experience you get as well as control over protocol it self. But you have to spend some time doing it, and make sure that implementation is highly reliable.
In same time you might have a look in ready to use solutions that google (again) have enough.
If you are using a RemoteWebDriver, you can cast WebElement into RemoteWebElement. You can then call getCoordinates() on that object to get the coordinates.
WebElement el = driver.findElementById("elementId");
Coordinates c = ((RemoteWebElement)el).getCoordinates();
driver.getMouse().mouseMove(c);
I made a function to get a vector of queries and do a transaction, maybe someone will find out it useful:
function transaction ($con, $Q){
mysqli_query($con, "START TRANSACTION");
for ($i = 0; $i < count ($Q); $i++){
if (!mysqli_query ($con, $Q[$i])){
echo 'Error! Info: <' . mysqli_error ($con) . '> Query: <' . $Q[$i] . '>';
break;
}
}
if ($i == count ($Q)){
mysqli_query($con, "COMMIT");
return 1;
}
else {
mysqli_query($con, "ROLLBACK");
return 0;
}
}
k old post but no one use list expression to answer :P
list =[ ['a','b'], ['a','c'], ['b','d'] ]
Search = 'c'
# return if it find in either item 0 or item 1
print [x for x,y in list if x == Search or y == Search]
# return if it find in item 1
print [x for x,y in list if y == Search]
You can try this:
<form action="/home">_x000D_
_x000D_
<input type="submit" value="cancel">_x000D_
_x000D_
<input type="submit" value="login" formaction="/login">_x000D_
<input type="submit" value="signup" formaction="/signup">_x000D_
_x000D_
</form>
_x000D_
You have to use HorizontalContentAlignment="Center" and! Width="Auto".
I actually has this problem once with a path issue referring another project :
I had this in my default.properties:
android.library.reference.1=..\\MyProject_Core\\
Which I fixed like this:
android.library.reference.1=../MyProject_Core/
My colleague created the above with Windows but only the version below worked on my Mac.
Please use the following
ddlCity.Items.Clear();
You need to use quote marks.
font-family: "Comic Sans MS", cursive, sans-serif;
Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.
**EDITED for Swift 4.2:
As @Koen commented, swift 4.2 allows:
guard let self = self else {
return // Could not get a strong reference for self :`(
}
// Now self is a strong reference
self.doSomething()
P.S.: Since I am having some up-votes, I would like to recommend the reading about escaping closures.
EDITED: As @tim-vermeulen has commented, Chris Lattner said on Fri Jan 22 19:51:29 CST 2016, this trick should not be used on self, so please don't use it. Check the non escaping closures info and the capture list answer from @gbk.**
For those who use [weak self] in capture list, note that self could be nil, so the first thing I do is check that with a guard statement
guard let `self` = self else {
return
}
self.doSomething()
If you are wondering what the quote marks are around self
is a pro trick to use self inside the closure without needing to change the name to this, weakSelf or whatever.
This should work based on your example "2011-29-01 12:00 am"
DateTime dt;
DateTime.TryParseExact(dateTime,
"yyyy-dd-MM hh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
A little anecdote to illustrate the use of array_key_exists
.
// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
'office-door' => unlockOffice(),
'home-key' => unlockSmallApartment(),
'wifes-mercedes' => unusedKeyAfterDivorce(),
'safety-deposit-box' => uselessKeyForEmptyBox(),
'rusto-old-car' => unlockOldBarrel(),
);
// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
print('Its on the chain.');
}
The best way is to use source generation, so that you could use
if (hash(str) == HASH("some string") ..
in your main source, and an pre-build step would convert the HASH(const char*)
expression to an integer value.
You can find a few examples here:
// Fill the DataSet. DataSet ds = new DataSet(); ds.Locale = CultureInfo.InvariantCulture; FillDataSet(ds); DataTable contacts = ds.Tables["Contact"]; DataTable orders = ds.Tables["SalesOrderHeader"]; var query = contacts.AsEnumerable().Join(orders.AsEnumerable(), order => order.Field<Int32>("ContactID"), contact => contact.Field<Int32>("ContactID"), (contact, order) => new { ContactID = contact.Field<Int32>("ContactID"), SalesOrderID = order.Field<Int32>("SalesOrderID"), FirstName = contact.Field<string>("FirstName"), Lastname = contact.Field<string>("Lastname"), TotalDue = order.Field<decimal>("TotalDue") }); foreach (var contact_order in query) { Console.WriteLine("ContactID: {0} " + "SalesOrderID: {1} " + "FirstName: {2} " + "Lastname: {3} " + "TotalDue: {4}", contact_order.ContactID, contact_order.SalesOrderID, contact_order.FirstName, contact_order.Lastname, contact_order.TotalDue); }
Or just google for 'linq join method syntax'.
You could try:
hadoop fs -put /path/in/linux /hdfs/path
or even
hadoop fs -copyFromLocal /path/in/linux /hdfs/path
By default both put
and copyFromLocal
would upload directories recursively to HDFS.
If you want a generic error you can setup all $.ajax()
(which $.get()
uses underneath) requests jQuery makes to display an error using $.ajaxSetup()
, for example:
$.ajaxSetup({
error: function(xhr, status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
Just run this once before making any AJAX calls (no changes to your current code, just stick this before somewhere). This sets the error
option to default to the handler/function above, if you made a full $.ajax()
call and specified the error
handler then what you had would override the above.
This is the main difference between use git reset --hard and git reset --soft:
--soft
Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.
--hard
Resets the index and working tree. Any changes to tracked files in the working tree since are discarded.
Sure:
public HttpResponseMessage Post()
{
// ... do the job
// now redirect
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("http://www.abcmvc.com");
return response;
}
I had the same problem and a simple solution that I found was:
List<Object[]> results = query.getResultList();
for (Object[] result: results) {
SomeClass something = (SomeClass)result[1];
something.doSomething;
}
I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.
Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.
@RestController
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {
@Value("${name}")//not necessary
private String name;//not necessary
private static String NAME_STATIC;
@Value("${name}")
public void setNameStatic(String name){
PropertyController.NAME_STATIC = name;
}
}
The previous answers will only work if you know the exact value you are searching for - the question states that only a partial value is known.
Array.FindIndex(authors, author => author.Contains("xyz"));
This will return the index of the first item containing "xyz".
Using command prompt in windows you can use below command to get class files.
wsimport "complete file path of your .wsdl file"
example : wsimport C:\Users\schemas\com\myprofile\myprofile2019.wsdl
if you want to generate source code you should be using below commnad.
wsimport -keep -s src "complete file path of your .wsdl file"
example : wsimport -keep -s src C:\Users\schemas\com\myprofile\myprofile2019.wsdl
Note : Here "-s" means source directory and "src" is name of folder that should be created before executing this command. Wsimport is a tool which is bundled along with JAVA SE, no seperate download is required.
Just a quick addition, because I tackled the same issue today:
With Go 1.13 it is possible to use the new isZero()
method:
if reflect.ValueOf(session).IsZero() {
// do stuff...
}
I didn't test this regarding performance, but I guess that this should be faster, than comparing via reflect.DeepEqual()
.
You can make your enum implement Parcelable which is quite easy for enums:
public enum MyEnum implements Parcelable {
VALUE;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(final Parcel dest, final int flags) {
dest.writeInt(ordinal());
}
public static final Creator<MyEnum> CREATOR = new Creator<MyEnum>() {
@Override
public MyEnum createFromParcel(final Parcel source) {
return MyEnum.values()[source.readInt()];
}
@Override
public MyEnum[] newArray(final int size) {
return new MyEnum[size];
}
};
}
You can then use Intent.putExtra(String, Parcelable).
UPDATE: Please note wreckgar's comment that enum.values()
allocates a new array at each call.
UPDATE: Android Studio features a live template ParcelableEnum
that implements this solution. (On Windows, use Ctrl+J)
public class Toggle {
public static String toggle(String s) {
char[] ch = s.toCharArray();
for (int i = 0; i < s.length(); i++) {
char charat = ch[i];
if (Character.isUpperCase(charat)) {
charat = Character.toLowerCase(charat);
} else
charat = Character.toUpperCase(charat);
System.out.print(charat);
}
return s;
}
public static void main(String[] args) {
toggle("DivYa");
}
}
There is a growing number of Open Source and commercial solutions for pure JavaScript charting that do not require Flash. In this response I will only present Open Source options.
There are 2 main classes of JavaScript solutions for graphics that do not require Flash:
There are pros and cons of both approaches but for a charting library I would recommend the later because it is well integrated with DOM, allowing to manipulate charts elements with the DOM, and most importantly setting DOM events. By contrast Canvas charting libraries must reinvent the DOM wheel to manage events. So unless you intend to build static graphs with no event handling, SVG/VML solutions should be better.
For SVG/VML solutions there are many options, including:
Raphael is a very active, well maintained, and mature, open-source graphic library with very good cross-browser support including IE 6 to 8, Firefox, Opera, Safari, Chrome, and Konqueror. Raphael does not depend on any JavaScript framework and therefore can be used with Prototype, jQuery, Dojo, Mootools, etc...
There are a number of charting libraries based on Raphael, including (but not limited to):
Disclosure: I am the developer of one of the Ico forks on github.
Another solution to this old question is the new container string array
, introduced in Matlab 2016b. From what I read in the official Matlab docs, this container resembles a cell-array and most of the array-related functions should work out of the box. For your case, new solution would be:
a=repmat('Some text', 10, 1);
This solution resembles a Rich C's solution applied to string array.
If you want to use for <input>
it will not work, for <input>
or text area you need to use Javascript
<script language="javascript" type="text/javascript">
function capitaliseName()
{
var str = document.getElementById("name").value;
document.getElementById("name").value = str.charAt(0).toUpperCase() + str.slice(1);
}
</script>
<textarea name="NAME" id="name" onkeydown = "capitaliseName()"></textarea>
that is supposed to work well for <input>
or <textarea>
String secStore = System.getenv("SECONDARY_STORAGE");
File externalsdpath = new File(secStore);
This will get the path of external sd secondary storage.
SELECT DATEADD(day,-30,date) AS before30d
FROM...
But it is strongly recommended to keep date in datetime column, not varchar.
I had a similar problem. My laptop ran out of battery during a git operation. Boo.
I didn't have any backups. (N.B. Ubuntu One is not a backup solution for git; it will helpfully overwrite your sane repository with your corrupted one.)
To the git wizards, if this was a bad way to fix it, please leave a comment. It did, however, work for me... at least temporarily.
Step 1: Make a backup of .git (in fact I do this in between every step that changes something, but with a new copy-to name, e.g. .git-old-1, .git-old-2, etc.):
cp -a .git .git-old
Step 2: Run git fsck --full
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
error: object file .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e is empty
fatal: loose object 8b61d0135d3195966b443f6c73fb68466264c68e (stored in .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e) is corrupt
Step 3: Remove the empty file. I figured what the heck; its blank anyway.
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ rm .git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e
rm: remove write-protected regular empty file `.git/objects/8b/61d0135d3195966b443f6c73fb68466264c68e'? y
Step 3: Run git fsck
again. Continue deleting the empty files. You can also cd
into the .git
directory and run find . -type f -empty -delete -print
to remove all empty files. Eventually git started telling me it was actually doing something with the object directories:
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: object file .git/objects/e0/cbccee33aea970f4887194047141f79a363636 is empty
fatal: loose object e0cbccee33aea970f4887194047141f79a363636 (stored in .git/objects/e0/cbccee33aea970f4887194047141f79a363636) is corrupt
Step 4: After deleting all of the empty files, I eventually came to git fsck
actually running:
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: HEAD: invalid sha1 pointer af9fc0c5939eee40f6be2ed66381d74ec2be895f
error: refs/heads/master does not point to a valid object!
error: refs/heads/master.u1conflict does not point to a valid object!
error: 0e31469d372551bb2f51a186fa32795e39f94d5c: invalid sha1 pointer in cache-tree
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
missing blob 8b61d0135d3195966b443f6c73fb68466264c68e
missing blob e89896b1282fbae6cf046bf21b62dd275aaa32f4
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a
missing blob caab8e3d18f2b8c8947f79af7885cdeeeae192fd
missing blob e4cf65ddf80338d50ecd4abcf1caf1de3127c229
Step 5: Try git reflog
. Fail because my HEAD is broken.
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git reflog
fatal: bad object HEAD
Step 6: Google. Find this. Manually get the last two lines of the reflog:
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ tail -n 2 .git/logs/refs/heads/master
f2d4c4868ec7719317a8fce9dc18c4f2e00ede04 9f0abf890b113a287e10d56b66dbab66adc1662d Nathan VanHoudnos <[email protected]> 1347306977 -0400 commit: up to p. 24, including correcting spelling of my name
9f0abf890b113a287e10d56b66dbab66adc1662d af9fc0c5939eee40f6be2ed66381d74ec2be895f Nathan VanHoudnos <[email protected]> 1347358589 -0400 commit: fixed up to page 28
Step 7: Note that from Step 6 we learned that the HEAD is currently pointing to the very last commit. So let's try to just look at the parent commit:
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git show 9f0abf890b113a287e10d56b66dbab66adc1662d
commit 9f0abf890b113a287e10d56b66dbab66adc1662d
Author: Nathan VanHoudnos <nathanvan@XXXXXX>
Date: Mon Sep 10 15:56:17 2012 -0400
up to p. 24, including correcting spelling of my name
diff --git a/tex/MCMC-in-IRT.tex b/tex/MCMC-in-IRT.tex
index 86e67a1..b860686 100644
--- a/tex/MCMC-in-IRT.tex
+++ b/tex/MCMC-in-IRT.tex
It worked!
Step 8: So now we need to point HEAD to 9f0abf890b113a287e10d56b66dbab66adc1662d.
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git update-ref HEAD 9f0abf890b113a287e10d56b66dbab66adc1662d
Which didn't complain.
Step 9: See what fsck says:
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: refs/heads/master.u1conflict does not point to a valid object!
error: 0e31469d372551bb2f51a186fa32795e39f94d5c: invalid sha1 pointer in cache-tree
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
missing blob 8b61d0135d3195966b443f6c73fb68466264c68e
missing blob e89896b1282fbae6cf046bf21b62dd275aaa32f4
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a
missing blob caab8e3d18f2b8c8947f79af7885cdeeeae192fd
missing blob e4cf65ddf80338d50ecd4abcf1caf1de3127c229
Step 10: The invalid sha1 pointer in cache-tree seemed like it was from a (now outdated) index file (source). So I killed it and reset the repo.
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ rm .git/index
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git reset
Unstaged changes after reset:
M tex/MCMC-in-IRT.tex
M tex/recipe-example/build-example-plots.R
M tex/recipe-example/build-failure-plots.R
Step 11: Looking at the fsck again...
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git fsck --full
Checking object directories: 100% (256/256), done.
error: refs/heads/master.u1conflict does not point to a valid object!
dangling blob 03511c9868b5dbac4ef1343956776ac508c7c2a2
dangling blob dd09f7f1f033632b7ef90876d6802f5b5fede79a
The dangling blobs are not errors. I'm not concerned with master.u1conflict, and now that it is working I don't want to touch it anymore!
Step 12: Catching up with my local edits:
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git status
# On branch master
# Changes not staged for commit:
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified: tex/MCMC-in-IRT.tex
# modified: tex/recipe-example/build-example-plots.R
# modified: tex/recipe-example/build-failure-plots.R
#
< ... snip ... >
no changes added to commit (use "git add" and/or "git commit -a")
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git commit -a -m "recovering from the git fiasco"
[master 7922876] recovering from the git fiasco
3 files changed, 12 insertions(+), 94 deletions(-)
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git add tex/sept2012_code/example-code-testing.R
nathanvan@nathanvan-N61Jq:~/workspace/mcmc-chapter$ git commit -a -m "adding in the example code"
[master 385c023] adding in the example code
1 file changed, 331 insertions(+)
create mode 100644 tex/sept2012_code/example-code-testing.R
So hopefully that can be of some use to people in the future. I'm glad it worked.
To sure, you should use function to check is null and empty as below:
string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}
It is indeed a key conflict. When concatenating arrays, duplicate keys are not overwritten.
Instead you must use array_merge()
$array = array_merge(array('Item 1'), array('Item 2'));
for me, it is a wrong error feedback.
there was config error in webpack.config.js
,
delete the file and start over solved my issue
If you're using Windows 10, it is built into the Linux subsystem feature. Just launch a Bash prompt (press the Windows key, then type bash
and choose "Bash on Ubuntu on Windows"), cd
to the directory you want to make and type make
.
FWIW, the Windows drives are found in /mnt
, e.g. C:\
drive is /mnt/c
in Bash.
If Bash isn't available from your start menu, here are instructions for turning on that Windows feature (64-bit Windows only):
Fill the screen with 6,435 z's $str = [System.Linq.Enumerable]::Repeat([string]::new("z", 143), 45)
$str
Java
8 now supports default methods, which are similar to C#
's extension methods.
To send to both remote with one command, you can create a alias for it:
git config alias.pushall '!git push origin devel && git push github devel'
With this, when you use the command git pushall
, it will update both repositories.
I had a problem when connecting my android phone, I couldn't charge my phone because the power switch on and then off ... PowerTop let me find this setting and was useful to fix the issue ( auto value was causing issue):
echo 'on' | sudo tee /sys/bus/usb/devices/1-1/power/control
just run this command from command prompt and it will launch chrome instance with CORS disabled:
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
for get week number in jalai calendar you can use this:
$weeknumber = date("W"); //number week in year
$dayweek = date("w"); //number day in week
if ($dayweek == "6")
{
$weeknumberint = (int)$weeknumber;
$date2int++;
$weeknumber = (string)$date2int;
}
echo $date2;
result:
15
week number change in saturday
You are sure you are linking to the same file and then editing that same file?
On some browser, you can use CTRL F5 to force a refresh (on the PC). On the Mac, it is Cmd Shift R
Firebug also has a net tab with "Disable Browser Cache".
But I want to give a warning here: even if you can hard refresh, how do you know your customers are getting the latest version? So you need to check, rather than just making sure you and your program manager can do a hard refresh and just go home and take the paycheck next month. If you want to do a job that change the world for the better, or leave the world a little bit better than you found it, you need to investigate more to make sure it works for your customers too (or else, sometimes the customer may call tech support, and tech support may read the script of "clear out the cookies and it will work", which is what happens to me sometimes). Some methods down at the bottom of this post can ensure the customers get the latest version.
If you are using Chrome and the DevTools is open, you can click and hold the Refresh icon in front of the address bar, and a box will pop up, and you can choose to "Hard Reload" or even "Empty Cache and Hard Reload":
If you use the Google Chrome debugger, it is the same, you can go to the Network section and make sure the "Disable cache (while DevTools is open)" is checked, in the Settings of the debugger panel.
Also, when you link the JavaScript file, use
<script src="my-js-file.js?v=1"></script>
or v=2
, and so forth, when you definitely want to refresh the file. Or you can go to the console and do a Date.now()
and get a timestamp, such as 1491313943549
, and use
<script src="my-js-file.js?t=1491313943549"></script>
Some building tools will do that automatically for you, or can be configured to do that, making it something like:
<script src="main.742a4952.js"></script>
which essentially will bust the cache.
Note that when you use the v=2
or t=1491313943549
, or main.742a4952.js
, you also have the advantage that for your users, they definitely will get the newer version as well.
I am using rails 6 and Model.all(:order 'columnName DESC') is not working. I have found the correct answer in OrderInRails
This is very simple.
@variable=Model.order('columnName DESC')
A contract is: If two objects are equal then they should have the same hashcode and if two objects are not equal then they may or may not have same hash code.
Try using your object as key in HashMap (edited after comment from joachim-sauer), and you will start facing trouble. A contract is a guideline, not something forced upon you.
List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();
It might help who is looking for the same solution.
select * from tablename ORDER BY ABS(column_name)
Simply put:
SELECT *
FROM TABLE_NAME
WHERE
dob > '1/21/2012'
Where 1/21/2012 is the date and you want all data, including that date.
SELECT *
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'
Use a between if you're selecting time between two dates
In my case it was an old version of the DLL in C:\WINDOWS\Microsoft.NET\Framework\~\Temporary ASP.NET Files\ directory. You can either delete or replace the old version, or you can remove and add back the reference to the DLL in your project. Basically, either way will create a new pointer to the temporary ASP.NET Files.
This is more complicated if you have a nested MasterPage. You need to first find the content control that contains the nested MasterPage, and then find the control on your nested MasterPage from that.
Crucial bit: Master.Master.
See here: http://forums.asp.net/t/1059255.aspx?Nested+master+pages+and+Master+FindControl
Example:
'Find the content control
Dim ct As ContentPlaceHolder = Me.Master.Master.FindControl("cphMain")
'now find controls inside that content
Dim lbtnSave As LinkButton = ct.FindControl("lbtnSave")
For Mars (Eclipse 4.5) and WTP 3.7 use this link. http://download.eclipse.org/webtools/repository/mars/
In my opinion, the most understandable algorithm for detecting cycle in a directed graph is the graph-coloring-algorithm.
Basically, the graph coloring algorithm walks the graph in a DFS manner (Depth First Search, which means that it explores a path completely before exploring another path). When it finds a back edge, it marks the graph as containing a loop.
For an in depth explanation of the graph coloring algorithm, please read this article: http://www.geeksforgeeks.org/detect-cycle-direct-graph-using-colors/
Also, I provide an implementation of graph coloring in JavaScript https://github.com/dexcodeinc/graph_algorithm.js/blob/master/graph_algorithm.js
This formula works for me:
// Converts CR TimeDate format to AssignDate for WeightedAverageDate calculation.
Date( Year({DWN00500.BUDDT}), Month({DWN00500.BUDDT}), Day({DWN00500.BUDDT}) ) - CDate(1899, 12, 30)
I think you want Any
:
if (myList.Any(str => str.Contains("Mdd LH")))
It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll
) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)
With TypeScript generics you can do something like this.
class Person {
constructor (public Name : string, public Age: number) {}
}
var list = new Array<Person>();
list.push(new Person("Baby", 1));
list.push(new Person("Toddler", 2));
list.push(new Person("Teen", 14));
list.push(new Person("Adult", 25));
var oldest_person = list.reduce( (a, b) => a.Age > b.Age ? a : b );
alert(oldest_person.Name);
It's simple, use $.getJSON()
function and in your URL just include
callback=?
as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/
Similarly to @brucexin I needed to get OS-level thread identifier (which != thread.get_ident()
) and use something like below not to depend on particular numbers and being amd64-only:
---- 8< ---- (xos.pyx)
"""module xos complements standard module os"""
cdef extern from "<sys/syscall.h>":
long syscall(long number, ...)
const int SYS_gettid
# gettid returns current OS thread identifier.
def gettid():
return syscall(SYS_gettid)
and
---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos
...
print 'my tid: %d' % xos.gettid()
this depends on Cython though.
I find this the most elegant way:
function isInteger(n) {
return n === (n^0);
}
It cares also to return false in case of a non-numeric value.
Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:
window.parent.$("#serverMsg")
There is no performance difference.
A const_iterator
is an iterator that points to const value (like a const T*
pointer); dereferencing it returns a reference to a constant value (const T&
) and prevents modification of the referenced value: it enforces const
-correctness.
When you have a const reference to the container, you can only get a const_iterator
.
Edited: I mentionned “The const_iterator
returns constant pointers” which is not accurate, thanks to Brandon for pointing it out.
Edit: For COW objects, getting a non-const iterator (or dereferencing it) will probably trigger the copy. (Some obsolete and now disallowed implementations of std::string
use COW.)
A little late, but if any of you have been going crazy trying to use inline SVG as a background, the escaping suggestions above do not quite work. For one, it does not work in IE, and depending on the content of your SVG the technique will cause trouble in other browsers, like FF.
If you base64 encode the svg (not the entire url, just the svg tag and its contents! ) it works in all browsers. Here is the same jsfiddle example in base64: http://jsfiddle.net/vPA9z/3/
The CSS now looks like this:
body { background-image:
url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHdpZHRoPScxMCcgaGVpZ2h0PScxMCc+PGxpbmVhckdyYWRpZW50IGlkPSdncmFkaWVudCc+PHN0b3Agb2Zmc2V0PScxMCUnIHN0b3AtY29sb3I9JyNGMDAnLz48c3RvcCBvZmZzZXQ9JzkwJScgc3RvcC1jb2xvcj0nI2ZjYycvPiA8L2xpbmVhckdyYWRpZW50PjxyZWN0IGZpbGw9J3VybCgjZ3JhZGllbnQpJyB4PScwJyB5PScwJyB3aWR0aD0nMTAwJScgaGVpZ2h0PScxMDAlJy8+PC9zdmc+");
Remember to remove any URL escaping before converting to base64. In other words, the above example showed color='#fcc' converted to color='%23fcc', you should go back to #.
The reason why base64 works better is that it eliminates all the issues with single and double quotes and url escaping
If you are using JS, you can use window.btoa()
to produce your base64 svg; and if it doesn't work (it might complain about invalid characters in the string), you can simply use https://www.base64encode.org/.
Example to set a div background:
var mySVG = "<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><linearGradient id='gradient'><stop offset='10%' stop-color='#F00'/><stop offset='90%' stop-color='#fcc'/> </linearGradient><rect fill='url(#gradient)' x='0' y='0' width='100%' height='100%'/></svg>";_x000D_
var mySVG64 = window.btoa(mySVG);_x000D_
document.getElementById('myDiv').style.backgroundImage = "url('data:image/svg+xml;base64," + mySVG64 + "')";
_x000D_
html, body, #myDiv {_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
margin: 0;_x000D_
}
_x000D_
<div id="myDiv"></div>
_x000D_
With JS you can generate SVGs on the fly, even changing its parameters.
One of the better articles on using SVG is here : http://dbushell.com/2013/02/04/a-primer-to-front-end-svg-hacking/
Hope this helps
Mike
Destroy the datepicker's instance when you don't want it and create new instance whenever necessary.
I know this is ugly but only this seems to be working...
$("#ddlSearchType").change(function () {
if ($(this).val() == "Required Date" || $(this).val() == "Submitted Date") {
$("#txtSearch").datepicker();
}
else {
$("#txtSearch").datepicker("destroy");
}
});
Although the above answers all work, What you originally tried to do was the correct way, however you just have the syntax backwards (switch "$size" and "$gt")..
Correct:
db.collection.find({items: {$gt: {$size: 1}}})
Incorrect:
db.collection.find({items: {$size: {$gt: 1}}})
You can bypass the security concerns, and create a much politer application by simply checking if the Word process is running, and asking the user to close it, then click a 'Continue' button in your app. This is the approach taken by many installers.
private bool isWordRunning()
{
return System.Diagnostics.Process.GetProcessesByName("winword").Length > 0;
}
Of course, you can only do this if your app has a GUI
Hadley has been developing a package called forcats
. This package makes the task so much easier. You can exploit fct_infreq()
when you want to change the order of x-axis by the frequency of a factor. In the case of the mtcars
example in this post, you want to reorder levels of cyl
by the frequency of each level. The level which appears most frequently stays on the left side. All you need is the fct_infreq()
.
library(ggplot2)
library(forcats)
ggplot(mtcars, aes(fct_infreq(factor(cyl)))) +
geom_bar() +
labs(x = "cyl")
If you wanna go the other way around, you can use fct_rev()
along with fct_infreq()
.
ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) +
geom_bar() +
labs(x = "cyl")
/** Count max number of nonempty cells in sheet rows */
private int getColumnsCount(XSSFSheet xssfSheet) {
int result = 0;
Iterator<Row> rowIterator = xssfSheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
List<Cell> cells = new ArrayList<>();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cells.add(cellIterator.next());
}
for (int i = cells.size(); i >= 0; i--) {
Cell cell = cells.get(i-1);
if (cell.toString().trim().isEmpty()) {
cells.remove(i-1);
} else {
result = cells.size() > result ? cells.size() : result;
break;
}
}
}
return result;
}
Using Bootstrap 3's grid system:
<div class="container">
<div class="row">
<div class="col-xs-4">Menu</div>
<div class="col-xs-8">
<div class="row">
<div class="col-md-4 col-md-push-8">Right Content</div>
<div class="col-md-8 col-md-pull-4">Content</div>
</div>
</div>
</div>
</div>
Working example: http://bootply.com/93614
First, we set two columns that will stay in place no matter the screen resolution (col-xs-*
).
Next, we divide the larger, right hand column in to two columns that will collapse on top of each other on tablet sized devices and lower (col-md-*
).
Finally, we shift the display order using the matching class (col-md-[push|pull]-*
). You push the first column over by the amount of the second, and pull the second by the amount of the first.
Don't know for sure, but it sounds like it is still submitting. I quick solution would be to change your (guessing at your code here):
<input type="submit" value="Submit" onclick="checkform()">
to a button:
<input type="button" value="Submit" onclick="checkform()">
That way your form still gets submitted (from the else part of your checkform()) and it shouldn't be reloading the page.
There are other, perhaps better, ways of handling it but this works in the mean time.
Try the following
function findById(source, id) {
for (var i = 0; i < source.length; i++) {
if (source[i].id === id) {
return source[i];
}
}
throw "Couldn't find object with id: " + id;
}
In Android Studio 2, just right click on app and select New > Activity > ... to create desired activity type.
Python indexing starts at 0 (rather than 1), so your assignment "r[1,:] = r0" defines the second (i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.
You could try to use ng-class
.
Here is my simple example:
http://plnkr.co/edit/wS3QkQ5dvHNdc6Lb8ZSF?p=preview
<div ng-repeat="object in objects">
<span ng-class="{'disabled': object.status}" ng-click="disableIt(object)">
{{object.value}}
</span>
</div>
The status is a custom attribute of object, you could name it whatever you want.
The disabled
in ng-class
is a CSS class name, the object.status
should be true
or false
You could change every object's status in function disableIt
.
In your Controller, you could do this:
$scope.disableIt = function(obj) {
obj.status = !obj.status
}
If you don't know how many columns you are going to have, the declaration
table-layout: fixed
along with not setting any column widths, would imply that browsers divide the total width evenly - no matter what.
That can also be the problem with this approach, if you use this, you should also consider how overflow is to be handled.
I know this thread is old, but since a Google search brought me here, it will also do to other people who may find this useful.
Microsoft recenly launched Visual Studio Online, which is free for projects with up to 5 users:
http://www.visualstudio.com/en-us/products/visual-studio-online-overview-vs.aspx
I have been using it for a while, and it integrates completely with Visual Studio 2013. It claims integration with other IDEs too. Apart from TFS, Git can also be used with it.
I know this thread is old, but since a Google search brought me here
The silly mistake I had done was keeping mysql.py
in same dir. Try renaming mysql.py
to another name so python
don't consider that as module.
In your ipython_config.py
file, search for the following lines
# c.InteractiveShellApp.matplotlib = None
and
# c.InteractiveShellApp.pylab = None
and uncomment them. Then, change None
to the backend that you're using (I use 'qt4'
) and save the file. Restart IPython, and matplotlib and pylab should be loaded - you can use the dir()
command to verify which modules are in the global namespace.
Suppose we have a dictionary like this
Dictionary<int,string> dict = new Dictionary<int, string>();
dict.Add(1, "Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");
We can initialize it as follow.
Dictionary<int, string> dict = new Dictionary<int, string>
{
{ 1, "Mohan" },
{ 2, "Kishor" },
{ 3, "Pankaj" },
{ 4, "Jeetu" }
};
Here is a self-contained example, with easily manipulated test data.
With this example, if you have a name with more than three parts, then all the "extra" stuff will get put in the LAST_NAME field. An exception is made for specific strings that are identified as "titles", such as "DR", "MRS", and "MR".
If the middle name is missing, then you just get FIRST_NAME and LAST_NAME (MIDDLE_NAME will be NULL).
You could smash it into a giant nested blob of SUBSTRINGs, but readability is hard enough as it is when you do this in SQL.
Edit-- Handle the following special cases:
1 - The NAME field is NULL
2 - The NAME field contains leading / trailing spaces
3 - The NAME field has > 1 consecutive space within the name
4 - The NAME field contains ONLY the first name
5 - Include the original full name in the final output as a separate column, for readability
6 - Handle a specific list of prefixes as a separate "title" column
SELECT
FIRST_NAME.ORIGINAL_INPUT_DATA
,FIRST_NAME.TITLE
,FIRST_NAME.FIRST_NAME
,CASE WHEN 0 = CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)
THEN NULL --no more spaces? assume rest is the last name
ELSE SUBSTRING(
FIRST_NAME.REST_OF_NAME
,1
,CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)-1
)
END AS MIDDLE_NAME
,SUBSTRING(
FIRST_NAME.REST_OF_NAME
,1 + CHARINDEX(' ',FIRST_NAME.REST_OF_NAME)
,LEN(FIRST_NAME.REST_OF_NAME)
) AS LAST_NAME
FROM
(
SELECT
TITLE.TITLE
,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME)
THEN TITLE.REST_OF_NAME --No space? return the whole thing
ELSE SUBSTRING(
TITLE.REST_OF_NAME
,1
,CHARINDEX(' ',TITLE.REST_OF_NAME)-1
)
END AS FIRST_NAME
,CASE WHEN 0 = CHARINDEX(' ',TITLE.REST_OF_NAME)
THEN NULL --no spaces @ all? then 1st name is all we have
ELSE SUBSTRING(
TITLE.REST_OF_NAME
,CHARINDEX(' ',TITLE.REST_OF_NAME)+1
,LEN(TITLE.REST_OF_NAME)
)
END AS REST_OF_NAME
,TITLE.ORIGINAL_INPUT_DATA
FROM
(
SELECT
--if the first three characters are in this list,
--then pull it as a "title". otherwise return NULL for title.
CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,1,3)))
ELSE NULL
END AS TITLE
--if you change the list, don't forget to change it here, too.
--so much for the DRY prinicple...
,CASE WHEN SUBSTRING(TEST_DATA.FULL_NAME,1,3) IN ('MR ','MS ','DR ','MRS')
THEN LTRIM(RTRIM(SUBSTRING(TEST_DATA.FULL_NAME,4,LEN(TEST_DATA.FULL_NAME))))
ELSE LTRIM(RTRIM(TEST_DATA.FULL_NAME))
END AS REST_OF_NAME
,TEST_DATA.ORIGINAL_INPUT_DATA
FROM
(
SELECT
--trim leading & trailing spaces before trying to process
--disallow extra spaces *within* the name
REPLACE(REPLACE(LTRIM(RTRIM(FULL_NAME)),' ',' '),' ',' ') AS FULL_NAME
,FULL_NAME AS ORIGINAL_INPUT_DATA
FROM
(
--if you use this, then replace the following
--block with your actual table
SELECT 'GEORGE W BUSH' AS FULL_NAME
UNION SELECT 'SUSAN B ANTHONY' AS FULL_NAME
UNION SELECT 'ALEXANDER HAMILTON' AS FULL_NAME
UNION SELECT 'OSAMA BIN LADEN JR' AS FULL_NAME
UNION SELECT 'MARTIN J VAN BUREN SENIOR III' AS FULL_NAME
UNION SELECT 'TOMMY' AS FULL_NAME
UNION SELECT 'BILLY' AS FULL_NAME
UNION SELECT NULL AS FULL_NAME
UNION SELECT ' ' AS FULL_NAME
UNION SELECT ' JOHN JACOB SMITH' AS FULL_NAME
UNION SELECT ' DR SANJAY GUPTA' AS FULL_NAME
UNION SELECT 'DR JOHN S HOPKINS' AS FULL_NAME
UNION SELECT ' MRS SUSAN ADAMS' AS FULL_NAME
UNION SELECT ' MS AUGUSTA ADA KING ' AS FULL_NAME
) RAW_DATA
) TEST_DATA
) TITLE
) FIRST_NAME
Another solution is described also here in case some of the other scripts does not work in your case.
In the end, both do the same thing. There are some differences in code: Web Services doesn't add a Root namespace of project, but Service Reference adds service classes to the namespace of the project. The ServiceSoapClient
class gets a different naming, which is not important. In working with TFS I'd rather use Service Reference because it works better with source control. Both work with SOAP protocols.
I find it better to use the Service Reference because it is new and will thus be better maintained.
NOTE: Only mac users!
curl -ksO https://gist.githubusercontent.com/nicerobot/2697848/raw/uninstall-node.sh
chmod +x ./uninstall-node.sh
./uninstall-node.sh
rm uninstall-node.sh
Or you could check out this website: How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)
if this doesn't work, you need to remove node via control panel or any other method. As long as it gets removed.
If you use nvm
, you can use:
nvm install node
You can already check if it works, then you don't need to take the following steps with: npm -v
and then node -v
if you have nvm
installed:
command -v nvm
sudo npm uninstall npm -g
Or, if that fails, get the npm source code, and do:
sudo make uninstall
If you have nvm
installed, then use: nvm uninstall npm
npm install -g grunt
Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.
And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.
The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.
In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.
Java, unlike languages like C and C++, treats boolean
as a completely separate data type which has 2 distinct values: true and false. The values 1 and 0 are of type int and are not implicitly convertible to boolean
.
For that I have written the following code in the "ActionPeformed(...)" method of the "Start" button
You need that code to be in the actionPerformed(...)
of the ActionListener
registered with the Start button, not for the Start button itself.
You can add a simple ActionListener
like this:
JButton startButton = new JButton("Start");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
startButton.setEnabled(false);
stopButton.setEnabled(true);
}
}
);
note that your startButton above will need to be final
in the above example if you want to create the anonymous listener in local scope.
Thank you for posting this issue.
One resolution: open the package in XML form through windows explorer, locate the GUID for the connection manager that cant be found. In my case, it was a bonked EventHandler connection that was corrupted. This same connection manager was used in the control flow but somehow was not corrupted there, so it was not obvious to the user via the UI. Since the XML pointed to an event handler connection manager, I opened the event handler tab in the UI and it immediately displayed the wonderful RED X on the source and targets that were referencing the corrupted connection manager ID. I repointed it to the correct manager, rebuilt the pkg and saved. Good to go.
The key was opening the pkg in XML format and locating the GUID in the code to see where it was failing. If I was not able to find a valid reference to it in the UI, I was going to either rename the XML connection to another known GUID within the XML and then go into the UI and repoint it again, or delete it altogether.
Good luck.
Downloading a file requires you to read it, either way you will have to go through the file in some way. Instead of line by line, you can just read it by bytes from the stream:
BufferedInputStream in = new BufferedInputStream(new URL("http://www.website.com/information.asp").openStream())
byte data[] = new byte[1024];
int count;
while((count = in.read(data,0,1024)) != -1)
{
out.write(data, 0, count);
}
Add a unique id to all your instances, i.e.
public interface Idable {
int id();
}
public class IdGenerator {
private static int id = 0;
public static synchronized int generate() { return id++; }
}
public abstract class AbstractSomething implements Idable {
private int id;
public AbstractSomething () {
this.id = IdGenerator.generate();
}
public int id() { return id; }
}
Extend from AbstractSomething and query this property. Will be safe inside a single vm (assuming no game playing with classloaders to get around statics).
I would like to give one additional answer, while the other ones will suffice in most cases.
I wanted to write a string over multiple lines, but its contents needed to be single-line.
sql=" \
SELECT c1, c2 \
from Table1, ${TABLE2} \
where ... \
"
I am sorry if this if a bit off-topic (I did not need this for SQL). However, this post comes up among the first results when searching for multi-line shell variables and an additional answer seemed appropriate.
What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).
The javaw command is identical to java, except that javaw has no associated console window. Use javaw when you do not want a command prompt window to be displayed. The javaw launcher displays a window with error information if it fails.
And javaws is for Java web start applications, applets, or something like that, I would suspect.
try this:
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=YOUR SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
UNION
SELECT * FROM OPENROWSET('SQLNCLI', 'Server=ANOTHER SERVER;Trusted_Connection=yes;','SELECT * FROM Table1') AS a
I am willing to bet some of my reputation that there is no such thing.
Partially because if you are worried about cross-platform SQL compatibility, your best bet in turn is to abstract your database code with some API or ORM tool that handles these things for you, and is well supported, so will deal with newer database versions as they come out.
Exact kind of API available to you will be dependent on your programming language/platform. For example, PHP has Pear:DB and others, I personally have found quite nice Python's ORM features implemented in Django framework. I presume there should be some of these things available on other platforms as well.
Use:
$.ajax({
url: 'feed/4', type: 'POST', data: "_METHOD=PUT&accessToken=63ce0fde", success: function(data) {
console.log(data);
}
});
Always remember to use _METHOD=PUT
.
You need to adjust three (or four) properties:
fetch.message.max.bytes
- this will determine the largest size of a message that can be fetched by the consumer.replica.fetch.max.bytes
- this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).message.max.bytes
- this is the largest size of the message that can be received by the broker from a producer.max.message.bytes
- this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes
.)I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.
I had the same issue on Mac OS X (installed with homebrew), and the .npmrc is not the only place node stored config variables. There is a glocal npmrc config file in /usr/local/etc that you have to edit using this command:
sudo nano npmrc
Remove the ca=
line, or whatever the config setting was that broke your install, save that file, and try npm again, and you should see it working.
Here’s the JavaScript equivalent:
var i = null;
var j = i || 10; //j is now 10
Note that the logical operator ||
does not return a boolean value but the first value that can be converted to true.
Additionally use an array of objects instead of one single object:
var options = {
filters: [
{
name: 'firstName',
value: 'abc'
}
]
};
var filter = options.filters[0] || ''; // is {name:'firstName', value:'abc'}
var filter2 = options.filters[1] || ''; // is ''
That can be accessed by index.
Some minor improvements
->previous answers weren't showing all results
->possible to filter on column name by setting the column name variable
DECLARE @columnname nvarchar(150)
SET @columnname=''
DECLARE @SQL varchar(max)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select
'''+d.name+'.''+sh.name+''.''+o.name COLLATE SQL_Latin1_General_CP1_CI_AS as name,c.name COLLATE SQL_Latin1_General_CP1_CI_AS as columnname,c.column_id
from '+d.name+'.sys.columns c
inner join '+d.name+'.sys.objects o on c.object_id=o.object_id
INNER JOIN '+d.name+'.sys.schemas sh on o.schema_id=sh.schema_id
where c.name like ''%'+@columnname+'%'' and sh.name<>''sys''
'
FROM sys.databases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)
The existing explanations aren't really complete without the actual rule from the Standard, found in 6.7:
The zero-initialization of all block-scope variables with static storage duration or thread storage duration is performed before any other initialization takes place. Constant initialization of a block-scope entity with static storage duration, if applicable, is performed before its block is first entered. An implementation is permitted to perform early initialization of other block-scope variables with static or thread storage duration under the same conditions that an implementation is permitted to statically initialize a variable with static or thread storage duration in namespace scope. Otherwise such a variable is initialized the first time control passes through its declaration; such a variable is considered initialized upon the completion of its initialization. If the initialization exits by throwing an exception, the initialization is not complete, so it will be tried again the next time control enters the declaration. If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization. If control re-enters the declaration recursively while the variable is being initialized, the behavior is undefined.
import * as express from "express";
This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.
In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.
for background worker i think you should try this technique it will help to call as many as pages you like all pages will run at once independently without waiting for each page response as asynchronous.
form_action_page.php
<?php
post_async("http://localhost/projectname/testpage.php", "Keywordname=testValue");
//post_async("http://localhost/projectname/testpage.php", "Keywordname=testValue2");
//post_async("http://localhost/projectname/otherpage.php", "Keywordname=anyValue");
//call as many as pages you like all pages will run at once //independently without waiting for each page response as asynchronous.
//your form db insertion or other code goes here do what ever you want //above code will work as background job this line will direct hit before //above lines response
?>
<?php
/*
* Executes a PHP page asynchronously so the current page does not have to wait for it to finish running.
*
*/
function post_async($url,$params)
{
$post_string = $params;
$parts=parse_url($url);
$fp = fsockopen($parts['host'],
isset($parts['port'])?$parts['port']:80,
$errno, $errstr, 30);
$out = "GET ".$parts['path']."?$post_string"." HTTP/1.1\r\n";//you can use POST instead of GET if you like
$out.= "Host: ".$parts['host']."\r\n";
$out.= "Content-Type: application/x-www-form-urlencoded\r\n";
$out.= "Content-Length: ".strlen($post_string)."\r\n";
$out.= "Connection: Close\r\n\r\n";
fwrite($fp, $out);
fclose($fp);
}
?>
testpage.php
<?
echo $_REQUEST["Keywordname"];//case1 Output > testValue
//here do your background operations it will not halt main page
?>
PS:if you want to send url parameters as loop then follow this answer :https://stackoverflow.com/a/41225209/6295712
use
console.log(variable)
and if you using google chrome open Console by using Ctrl+Shift+j
Goto >> Console
I had a similir problem, but in my case, I put a row in the leading of the ListView, and it was consuming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recommend to check if the problem is a larger widget than its container can have.
Expanded(child:MyListView())
When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.
However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.
Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.
If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.
To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.
As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html
I use this :
1-Declare a temp table variable in the script your building:
DECLARE @ShiftPeriodList TABLE(id INT NOT NULL);
2-Allocate to temp table:
IF (SOME CONDITION)
BEGIN
INSERT INTO @ShiftPeriodList SELECT ShiftId FROM [hr].[tbl_WorkShift]
END
IF (SOME CONDITION2)
BEGIN
INSERT INTO @ShiftPeriodList
SELECT ws.ShiftId
FROM [hr].[tbl_WorkShift] ws
WHERE ws.WorkShift = 'Weekend(VSD)' OR ws.WorkShift = 'Weekend(SDL)'
END
3-Reference the table when you need it in a WHERE statement :
INSERT INTO SomeTable WHERE ShiftPeriod IN (SELECT * FROM @ShiftPeriodList)
Use following query to print REPAIR
SQL statments for all tables inside a database:
select concat('REPAIR TABLE ', table_name, ';') from information_schema.tables
where table_schema='mydatabase';
After that copy all the queries and execute it on mydatabase
.
Note: replace mydatabase
with desired DB name
What happens here is the particular package is not available in the cache. Resetting will help solve the problem.
Goto terminal and build the project again
./gradlew build
This should download all the missing packages again
Try the -fno-stack-protector
flag.
You can use the onsubmit function.
If you return false the form won't get submitted. Read up about it here.
$('#myform').submit(function() {
// your code here
});
You can use CSS selectors.
Depending on how you get that td, you can either give it an id:
<td id='cell'>c</td>
and then use:
$("#cell").text("text");
Or traverse to the third cell of the first row of table_header, etc.
This will do it:
my_hash.each_with_object({}) { |(key, value), hash| hash[key] = value.upcase }
As opposed to inject
the advantage is that you are in no need to return the hash again inside the block.
<label for="fileEdit">
<i class="fa fa-cloud-upload">
</i>
<input id="fileEdit" class="hidden" type="file" name="addImg" ng-file-change="onImageChange( $files )" ng-multiple="false" accept="{{ contentType }}"/>
</label>
For example you can use this : label with hidden input (icon is present).
System.exit();
causes the Java VM to terminate completely.
JFrame.dispose();
causes the JFrame
window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.
The one you choose really depends on your situation. If you want to terminate everything in the current Java VM, you should use System.exit()
and everything will be cleaned up. If you only want to destroy the current window, with the side effect that it will close the Java VM if this is the only window, then use JFrame.dispose()
.
Another solution:
^[1-9]\d*$
\d
equivalent to [0-9]
If you want a list of strings containing your string:
var newList = myList.Where(x => x.Contains(myString)).ToList();
Another option is to use Linq FirstOrDefault
var element = myList.Where(x => x.Contains(myString)).FirstOrDefault();
Keep in mind that Contains
method is case sensitive.
Under Settings => Media, there's an option for 'Full URL-path for files'. If you set this to the default media directory path '/wp-content/uploads' instead of blank, it will insert relative paths e.g. '/wp-content/uploads/2020/06/document.pdf'.
I'm not sure if it makes all links relative, e.g. to posts, but at least it handles media, which probably is what most people are worried about.
As @Egon mentioned above, there is no real folder management in BLOB storage.
You can achieve some features of a file system using '/' in the file name, but this has many limitations (for example, what happen if you need to rename a "folder"?).
As a general rule, I would keep my files as flat as possible in a container, and have my application manage whatever structure I want to expose to the end users (for example manage a nested folder structure in my database, have a record for each file, referencing the BLOB using container-name and file-name).
In bash
, you should be able to do:
kill $(ps aux | grep '[p]ython csp_build.py' | awk '{print $2}')
Details on its workings are as follows:
ps
gives you the list of all the processes.grep
filters that based on your search string, [p]
is a trick to stop you picking up the actual grep
process itself.awk
just gives you the second field of each line, which is the PID.$(x)
construct means to execute x
then take its output and put it on the command line. The output of that ps
pipeline inside that construct above is the list of process IDs so you end up with a command like kill 1234 1122 7654
.Here's a transcript showing it in action:
pax> sleep 3600 &
[1] 2225
pax> sleep 3600 &
[2] 2226
pax> sleep 3600 &
[3] 2227
pax> sleep 3600 &
[4] 2228
pax> sleep 3600 &
[5] 2229
pax> kill $(ps aux | grep '[s]leep' | awk '{print $2}')
[5]+ Terminated sleep 3600
[1] Terminated sleep 3600
[2] Terminated sleep 3600
[3]- Terminated sleep 3600
[4]+ Terminated sleep 3600
and you can see it terminating all the sleepers.
Explaining the grep '[p]ython csp_build.py'
bit in a bit more detail:
When you do sleep 3600 &
followed by ps -ef | grep sleep
, you tend to get two processes with sleep
in it, the sleep 3600
and the grep sleep
(because they both have sleep
in them, that's not rocket science).
However, ps -ef | grep '[s]leep'
won't create a process with sleep
in it, it instead creates grep '[s]leep'
and here's the tricky bit: the grep
doesn't find it because it's looking for the regular expression "any character from the character class [s]
(which is s
) followed by leep
.
In other words, it's looking for sleep
but the grep process is grep '[s]leep'
which doesn't have sleep
in it.
When I was shown this (by someone here on SO), I immediately started using it because
| grep -v grep
; andAccording to my interpretation of the implementation of unicode-escape
and the unicode repr
in the CPython 2.6.5 source, yes; the only difference between repr(unicode_string)
and unicode_string.encode('unicode-escape')
is the inclusion of wrapping quotes and escaping whichever quote was used.
They are both driven by the same function, unicodeescape_string
. This function takes a parameter whose sole function is to toggle the addition of the wrapping quotes and escaping of that quote.
While the cursor: none
CSS solution is definitely a solid and easy workaround, if your actual goal is to remove the default cursor while your web application is being used, or implement your own interpretation of raw mouse movement (for FPS games, for example), you might want to consider using the Pointer Lock API instead.
You can use requestPointerLock on an element to remove the cursor, and redirect all mousemove
events to that element (which you may or may not handle):
document.body.requestPointerLock();
To release the lock, you can use exitPointerLock:
document.exitPointerLock();
No cursor, for real
This is a very powerful API call. It not only renders your cursor invisible, but it actually removes your operating system's native cursor. You won't be able to select text, or do anything with your mouse (except listening to some mouse events in your code) until the pointer lock is released (either by using exitPointerLock
or pressing ESC in some browsers).
That is, you cannot leave the window with your cursor for it to show again, as there is no cursor.
Restrictions
As mentioned above, this is a very powerful API call, and is thus only allowed to be made in response to some direct user-interaction on the web, such as a click; for example:
document.addEventListener("click", function () {
document.body.requestPointerLock();
});
Also, requestPointerLock
won't work from a sandboxed iframe
unless the allow-pointer-lock
permission is set.
User-notifications
Some browsers will prompt the user for a confirmation before the lock is engaged, some will simply display a message. This means pointer lock might not activate right away after the call. However, the actual activation of pointer locking can be listened to by listening to the pointerchange
event on the element on which requestPointerLock
was called:
document.body.addEventListener("pointerlockchange", function () {
if (document.pointerLockElement === document.body) {
// Pointer is now locked to <body>.
}
});
Most browsers will only display the message once, but Firefox will occasionally spam the message on every single call. AFAIK, this can only be worked around by user-settings, see Disable pointer-lock notification in Firefox.
Listening to raw mouse movement
The Pointer Lock API not only removes the mouse, but instead redirects raw mouse movement data to the element requestPointerLock
was called on. This can be listened to simply by using the mousemove
event, then accessing the movementX
and movementY
properties on the event object:
document.body.addEventListener("mousemove", function (e) {
console.log("Moved by " + e.movementX + ", " + e.movementY);
});
Anyone using composer dependencies, you might want to consider this library: https://github.com/ramsey/uuid
It doesn't get any easier than this:
Uuid::uuid4();
The following command line is from Christian Garbin's blog
g++ -g -O -Wa,-aslh horton_ex2_05.cpp >list.txt
I ran G++ from a DOS window on Win-XP, against a routine that contains an implicit cast
c:\gpp_code>g++ -g -O -Wa,-aslh horton_ex2_05.cpp >list.txt
horton_ex2_05.cpp: In function `int main()':
horton_ex2_05.cpp:92: warning: assignment to `int' from `double'
The output is asssembled generated code iterspersed with the original C++ code (the C++ code is shown as comments in the generated asm stream)
16:horton_ex2_05.cpp **** using std::setw;
17:horton_ex2_05.cpp ****
18:horton_ex2_05.cpp **** void disp_Time_Line (void);
19:horton_ex2_05.cpp ****
20:horton_ex2_05.cpp **** int main(void)
21:horton_ex2_05.cpp **** {
164 %ebp
165 subl $128,%esp
?GAS LISTING C:\DOCUME~1\CRAIGM~1\LOCALS~1\Temp\ccx52rCc.s
166 0128 55 call ___main
167 0129 89E5 .stabn 68,0,21,LM2-_main
168 012b 81EC8000 LM2:
168 0000
169 0131 E8000000 LBB2:
169 00
170 .stabn 68,0,25,LM3-_main
171 LM3:
172 movl $0,-16(%ebp)
I believe I have a valid use case for using typeid(), the same way it is valid to use sizeof(). For a template function, I need to special case the code based on the template variable, so that I offer maximum functionality and flexibility.
It is much more compact and maintainable than using polymorphism, to create one instance of the function for each type supported. Even in that case I might use this trick to write the body of the function only once:
Note that because the code uses templates, the switch statement below should resolve statically into only one code block, optimizing away all the false cases, AFAIK.
Consider this example, where we may need to handle a conversion if T is one type vs another. I use it for class specialization to access hardware where the hardware will use either myClassA or myClassB type. On a mismatch, I need to spend time converting the data.
switch ((typeid(T)) {
case typeid(myClassA):
// handle that case
break;
case typeid(myClassB):
// handle that case
break;
case typeid(uint32_t):
// handle that case
break;
default:
// handle that case
}
Jenkins has a link to their REST API in the bottom right of each page. This link appears on every page of Jenkins and points you to an API output for the exact page you are browsing. That should provide some understanding into how to build the API URls.
You can additionally use some wrapper, like I do, in Python, using http://jenkinsapi.readthedocs.io/en/latest/
Here is their website: https://wiki.jenkins-ci.org/display/JENKINS/Remote+access+API
See the query below (assumed @dt1 >= @dt2);
Declare @dt1 datetime = '2013-7-3'
Declare @dt2 datetime = '2013-5-2'
select abs(DATEDIFF(DD, @dt2, @dt1)) Days,
case when @dt1 >= @dt2
then case when DAY(@dt2)<=DAY(@dt1)
then Convert(varchar, DATEDIFF(MONTH, @dt2, @dt1)) + CONVERT(varchar, ' Month(s) ') + Convert(varchar, DAY(@dt1)-DAY(@dt2)) + CONVERT(varchar, 'Day(s).')
else Convert(varchar, DATEDIFF(MONTH, @dt2, @dt1)-1) + CONVERT(varchar, ' Month(s) ') + convert(varchar, abs(DATEDIFF(DD, @dt1, DateAdd(Month, -1, @dt1))) - (DAY(@dt2)-DAY(@dt1))) + CONVERT(varchar, 'Day(s).')
end
else 'See asumption: @dt1 must be >= @dt2'
end In_Months_Days
Returns:
Days | In_Months_Days
62 | 2 Month(s) 1Day(s).
I tried multiple solutions, but his is the only one that actually worked for me in all the browsers
let newTab = window.open();
newTab.location.href = url;
You can use the glob() function to do this.
Here is some documentation on it: http://php.net/manual/en/function.glob.php
You can use an iterator.
typedef std::map<std::string, std::map<std::string, std::string>>::iterator it_type;
for(it_type iterator = m.begin(); iterator != m.end(); iterator++) {
// iterator->first = key
// iterator->second = value
// Repeat if you also want to iterate through the second map.
}
You need to multiply your Model matrix. Because that is where model position, scaling and rotation should be (that's why it's called the model matrix).
All you need to do is (see here)
Model = glm::rotate(Model, angle_in_radians, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
Note that to convert from degrees to radians, use
glm::radians(degrees)
That takes the Model matrix and applies rotation on top of all the operations that are already in there. The other functions translate and scale do the same. That way it's possible to combine many transformations in a single matrix.
note: earlier versions accepted angles in degrees. This is deprecated since 0.9.6
Model = glm::rotate(Model, angle_in_degrees, glm::vec3(x, y, z)); // where x, y, z is axis of rotation (e.g. 0 1 0)
1 - (change)
is bound to the HTML onchange event. The documentation about HTML onchange says the following :
Execute a JavaScript when a user changes the selected option of a
<select>
element
Source : https://www.w3schools.com/jsref/event_onchange.asp
2 - As stated before, (ngModelChange)
is bound to the model variable binded to your input.
So, my interpretation is :
(change)
triggers when the user changes the input(ngModelChange)
triggers when the model changes, whether it's consecutive to a user action or notsegmentation fault arrives when you access memory which is not declared by the program. You can do this through pointers i.e through memory addresses. Or this may also be due to stackoverflow for eg:
void rec_func() {int q = 5; rec_func();}
int main() {rec_func();}
This call will keep on consuming stack memory until it's completely filled and thus finally stackoverflow happens. Note: it might not be visible in some competitive questions as it leads to timeouterror first but for those in which timeout doesn't happens its a hard time figuring out sigsemv.
I don't know but i use this method:
public static Boolean isInRange(this Decimal dec, Decimal min, Decimal max, bool includesMin = true, bool includesMax = true ) {
return (includesMin ? (dec >= min) : (dec > min)) && (includesMax ? (dec <= max) : (dec < max));
}
And this is the way I can use it:
[TestMethod]
public void IsIntoTheRange()
{
decimal dec = 54;
Boolean result = false;
result = dec.isInRange(50, 60); //result = True
Assert.IsTrue(result);
result = dec.isInRange(55, 60); //result = False
Assert.IsFalse(result);
result = dec.isInRange(54, 60); //result = True
Assert.IsTrue(result);
result = dec.isInRange(54, 60, false); //result = False
Assert.IsFalse(result);
result = dec.isInRange(32, 54, false, false);//result = False
Assert.IsFalse(result);
result = dec.isInRange(32, 54, false);//result = True
Assert.IsTrue(result);
}
I tried ng remove component Comp_Name also ng distroy component but it is not yet supported by angular so the best option for now is to manually remove it from the folder structure.
MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.
The conventional operators
are available for DateTime
since .NET Framework 1.1. Also, addition and subtraction of DateTime
objects are also possible using conventional operators +
and -
.
One example from MSDN:
Equality:System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);
// areEqual gets false.
bool areEqual = april19 == otherDate;
otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;
Other operators can be used likewise.
Here is the list all operators available for DateTime
.
For the query to be legal in SQL92, the name column must be omitted from the select list or named in the GROUP BY clause.
SQL99 and later permits such nonaggregates per optional feature T301 if they are functionally dependent on GROUP BY columns: If such a relationship exists between name and custid, the query is legal. This would be the case, for example, were custid a primary key of customers.
MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them.
via MySQL :: MySQL 5.7 Reference Manual :: 12.19.3 MySQL Handling of GROUP BY
You can solve it by changing the sql mode with this command:
SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
and ... remember to reconnect the database!!!
Looking at the JDK, innermost constructor for Calendar.getInstance()
has this:
public GregorianCalendar(TimeZone zone, Locale aLocale) {
super(zone, aLocale);
gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
setTimeInMillis(System.currentTimeMillis());
}
so it already automatically does what you suggest. Date's default constructor holds this:
public Date() {
this(System.currentTimeMillis());
}
So there really isn't need to get system time specifically unless you want to do some math with it before creating your Calendar/Date object with it. Also I do have to recommend joda-time to use as replacement for Java's own calendar/date classes if your purpose is to work with date calculations a lot.
In order for you to modify test1
while inside a function you will need to do define test1
as a global variable, for example:
test1 = 0
def testFunc():
global test1
test1 += 1
testFunc()
However, if you only need to read the global variable you can print it without using the keyword global
, like so:
test1 = 0
def testFunc():
print test1
testFunc()
But whenever you need to modify a global variable you must use the keyword global
.
CSRF can be enforced at the view level, which can't be disabled globally.
In some cases this is a pain, but um, "it's for security". Gotta retain those AAA ratings.
https://docs.djangoproject.com/en/dev/ref/csrf/#contrib-and-reusable-apps
Check if your scripts name doesn't contain $SERVICE. If it does, it will be shown in ps results, causing script to always think that service is running. You can grep it against current filename like this:
#!/bin/sh
SERVICE=$1
if ps ax | grep -v grep | grep -v $0 | grep $SERVICE > /dev/null
then
echo "$SERVICE service running, everything is fine"
else
echo "$SERVICE is not running"
fi
Its boils down to this: math.h
is from C
and was created over 10 years ago. In math.h, due to its primitive nature, the abs()
function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs()
.
When C++ was created it took math.h
and made it cmath
. cmath
is essentially math.h but improved for C++. It improved things like having to distinguish between fabs()
and abs, and just made abs()
for both doubles and integer types.
In summary either:
Use math.h and use abs()
for integers, fabs()
for doubles
or
use cmath and just have abs for everything (easier and recommended)
Hope this helps anyone who is having the same problem!
ko.cleanNode($("#modalPartialView")[0]);
ko.applyBindings(vm, $("#modalPartialView")[0]);
works for me, but as others note, the cleanNode
is internal ko
function, so there is probably a better way.
You should indeed start with the Mandelbrot set, and understand what it really is.
The idea behind it is relatively simple. You start with a function of complex variable
f(z) = z2 + C
where z is a complex variable and C is a complex constant. Now you iterate it starting from z = 0, i.e. you compute z1 = f(0), z2 = f(z1), z3 = f(z2) and so on. The set of those constants C for which the sequence z1, z2, z3, ... is bounded, i.e. it does not go to infinity, is the Mandelbrot set (the black set in the figure on the Wikipedia page).
In practice, to draw the Mandelbrot set you should:
The astounding fact about fractals is how we can obtain a tremendously complex set (in particular, the frontier of the Mandelbrot set) from easy and apparently innocuous requirements.
Enjoy!
Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).
You can do this:
<img src="src/to/your/img.jpg" id="yourImgId"/>
document.getElementById("yourImgId").style.height = "heightpx";
The same you can do with the width.
document.getElementById("address_box").value =
(title + "\n" + address + "\n" + address2 + "\n" + address3 + "\n" + address4);
I think of it this way, encapsulation is hiding the way something gets done. This can be one or many actions.
Abstraction is related to "why" I am encapsulating it the first place.
I am basically telling the client "You don't need to know much about how I process the payment and calculate shipping, etc. I just want you to tell me you want to 'Checkout' and I will take care of the details for you."
This way I have encapsulated the details by generalizing (abstracting) into the Checkout request.
I really think that abstracting and encapsulation go together.
Just create Footer Wrapper View using constructor UIView(frame:_)
then if you are using xib file for FooterView, create view from xib and add as subView to wrapper view. then assign wrapper to tableView.tableFooterView = fixWrapper
.
let fixWrapper = UIView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 54)) // dont remove
let footer = UIView.viewFromNib("YourViewXibFileName") as! YourViewClassName
fixWrapper.addSubview(footer)
tableView.tableFooterView = fixWrapper
tableFootterCostView = footer
It works perfectly for me! the point is to create footer view with constructor (frame:_)
. Even though you create UIView() and assign frame property it may not work.
Take a look at the Cursor.Position
Property. It should get you started.
private void MoveCursor()
{
// Set the Current cursor, move the cursor's Position,
// and set its clipping rectangle to the form.
this.Cursor = new Cursor(Cursor.Current.Handle);
Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
Cursor.Clip = new Rectangle(this.Location, this.Size);
}
Here's what I ended up with. It's a listing of all properties and methods, and I listed all parameters for each method. I didn't succeed on getting all of the values.
foreach(System.Reflection.AssemblyName an in System.Reflection.Assembly.GetExecutingAssembly().GetReferencedAssemblies()){
System.Reflection.Assembly asm = System.Reflection.Assembly.Load(an.ToString());
foreach(Type type in asm.GetTypes()){
//PROPERTIES
foreach (System.Reflection.PropertyInfo property in type.GetProperties()){
if (property.CanRead){
Response.Write("<br>" + an.ToString() + "." + type.ToString() + "." + property.Name);
}
}
//METHODS
var methods = type.GetMethods();
foreach (System.Reflection.MethodInfo method in methods){
Response.Write("<br><b>" + an.ToString() + "." + type.ToString() + "." + method.Name + "</b>");
foreach (System.Reflection.ParameterInfo param in method.GetParameters())
{
Response.Write("<br><i>Param=" + param.Name.ToString());
Response.Write("<br> Type=" + param.ParameterType.ToString());
Response.Write("<br> Position=" + param.Position.ToString());
Response.Write("<br> Optional=" + param.IsOptional.ToString() + "</i>");
}
}
}
}
To call a function inside a same controller in any laravel version follow as bellow
$role = $this->sendRequest('parameter');
// sendRequest is a public function
Update 1 November 2012
My original answer applies specifically to jQuery 1.6. My advice remains the same but jQuery 1.6.1 changed things slightly: in the face of the predicted pile of broken websites, the jQuery team reverted attr()
to something close to (but not exactly the same as) its old behaviour for Boolean attributes. John Resig also blogged about it. I can see the difficulty they were in but still disagree with his recommendation to prefer attr()
.
Original answer
If you've only ever used jQuery and not the DOM directly, this could be a confusing change, although it is definitely an improvement conceptually. Not so good for the bazillions of sites using jQuery that will break as a result of this change though.
I'll summarize the main issues:
prop()
rather than attr()
.prop()
does what attr()
used to do. Replacing calls to attr()
with prop()
in your code will generally work.checked
property is a Boolean, the style
property is an object with individual properties for each style, the size
property is a number.value
and checked
: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input (reflected in the defaultValue
/ defaultChecked
property).If you're a jQuery developer and are confused by this whole business about properties and attributes, you need to take a step back and learn a little about it, since jQuery is no longer trying so hard to shield you from this stuff. For the authoritative but somewhat dry word on the subject, there's the specs: DOM4, HTML DOM, DOM Level 2, DOM Level 3. Mozilla's DOM documentation is valid for most modern browsers and is easier to read than the specs, so you may find their DOM reference helpful. There's a section on element properties.
As an example of how properties are simpler to deal with than attributes, consider a checkbox that is initially checked. Here are two possible pieces of valid HTML to do this:
<input id="cb" type="checkbox" checked>
<input id="cb" type="checkbox" checked="checked">
So, how do you find out if the checkbox is checked with jQuery? Look on Stack Overflow and you'll commonly find the following suggestions:
if ( $("#cb").attr("checked") === true ) {...}
if ( $("#cb").attr("checked") == "checked" ) {...}
if ( $("#cb").is(":checked") ) {...}
This is actually the simplest thing in the world to do with the checked
Boolean property, which has existed and worked flawlessly in every major scriptable browser since 1995:
if (document.getElementById("cb").checked) {...}
The property also makes checking or unchecking the checkbox trivial:
document.getElementById("cb").checked = false
In jQuery 1.6, this unambiguously becomes
$("#cb").prop("checked", false)
The idea of using the checked
attribute for scripting a checkbox is unhelpful and unnecessary. The property is what you need.
checked
attribute1
is a literal. name = value
is an assignment. 1 = value
is an assignment to a literal, which makes no sense. Why would you want 1
to mean something other than 1
?
The following code helps me to setup communication between two siblings. The setup is done in their parent during render() and componentDidMount() calls. It is based on https://reactjs.org/docs/refs-and-the-dom.html Hope it helps.
class App extends React.Component<IAppProps, IAppState> {
private _navigationPanel: NavigationPanel;
private _mapPanel: MapPanel;
constructor() {
super();
this.state = {};
}
// `componentDidMount()` is called by ReactJS after `render()`
componentDidMount() {
// Pass _mapPanel to _navigationPanel
// It will allow _navigationPanel to call _mapPanel directly
this._navigationPanel.setMapPanel(this._mapPanel);
}
render() {
return (
<div id="appDiv" style={divStyle}>
// `ref=` helps to get reference to a child during rendering
<NavigationPanel ref={(child) => { this._navigationPanel = child; }} />
<MapPanel ref={(child) => { this._mapPanel = child; }} />
</div>
);
}
}
Five ways, 4 for bash and 1 addition for zsh:
type foobar &> /dev/null
hash foobar &> /dev/null
command -v foobar &> /dev/null
which foobar &> /dev/null
(( $+commands[foobar] ))
(zsh only)You can put any of them to your if
clause. According to my tests (https://www.topbug.net/blog/2016/10/11/speed-test-check-the-existence-of-a-command-in-bash-and-zsh/), the 1st and 3rd method are recommended in bash and the 5th method is recommended in zsh in terms of speed.
brew cask install caskroom/versions/java8
I had the same need and was looking for recommendation or standard references and came across this thread. My current blacklist of characters that should be avoided in file and directory names are:
$CharactersInvalidForFileName = {
"pound" -> "#",
"left angle bracket" -> "<",
"dollar sign" -> "$",
"plus sign" -> "+",
"percent" -> "%",
"right angle bracket" -> ">",
"exclamation point" -> "!",
"backtick" -> "`",
"ampersand" -> "&",
"asterisk" -> "*",
"single quotes" -> "“",
"pipe" -> "|",
"left bracket" -> "{",
"question mark" -> "?",
"double quotes" -> "”",
"equal sign" -> "=",
"right bracket" -> "}",
"forward slash" -> "/",
"colon" -> ":",
"back slash" -> "\\",
"lank spaces" -> "b",
"at sign" -> "@"
};