From the proxy_pass documentation:
A special case is using variables in the proxy_pass statement: The requested URL is not used and you are fully responsible to construct the target URL yourself.
Since you're using $1 in the target, nginx relies on you to tell it exactly what to pass. You can fix this in two ways. First, stripping the beginning of the uri with a proxy_pass is trivial:
location /service/ {
# Note the trailing slash on the proxy_pass.
# It tells nginx to replace /service/ with / when passing the request.
proxy_pass http://apache/;
}
Or if you want to use the regex location, just include the args:
location ~* ^/service/(.*) {
proxy_pass http://apache/$1$is_args$args;
}
You don't need to downgrade you can:
Either disable undefined symbol diagnostics in the settings -- "intelephense.diagnostics.undefinedSymbols": false .
Or use an ide helper that adds stubs for laravel facades. See https://github.com/barryvdh/laravel-ide-helper
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument('--disable-logging')
# Update your desired_capabilities dict withe extra options.
desired_capabilities.update(options.to_capabilities())
driver = webdriver.Remote(desired_capabilities=options.to_capabilities())
Both the desired_capabilities and options.to_capabilities() are dictionaries. You can use the dict.update() method to add the options to the main set.
For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services
From the above referenced site:
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.
Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.
Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.
You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.
Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx
If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx
If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx
If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx
If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx
Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx
Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx
I know question is already answered.
But let me add one point here. This is not only case of true or false. See below:
var val="Do";
Var c= (val == "Do" || val == "Done")
? 7
: 0
Here if val is Do or Done then c will be 7 else it will be zero. In this case c will be 7.
This is actually another perspective of this operator.
JSON.stringify
takes more optional arguments.
Try:
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, 4); // Indented 4 spaces
JSON.stringify({a:1,b:2,c:{d:1,e:[1,2]}}, null, "\t"); // Indented with tab
From:
How can I beautify JSON programmatically?
Should work in modern browsers, and it is included in json2.js if you need a fallback for browsers that don't support the JSON helper functions. For display purposes, put the output in a <pre>
tag to get newlines to show.
If I understand your question correctly:
for elem in doc.findall('timeSeries/values/value'):
print elem.get('dateTime'), elem.text
or if you prefer (and if there is only one occurrence of timeSeries/values
:
values = doc.find('timeSeries/values')
for value in values:
print value.get('dateTime'), elem.text
The findall()
method returns a list of all matching elements, whereas find()
returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values
element, in this case leading to the same result.
I don't see where the problem with not finding timeSeries
comes from however. Maybe you just forgot the getroot()
call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values
or //timeSeries/values
)
It is just called the eyedropper tool. There is no shortcut key for it that I'm aware of. The only way you can use it now is by clicking on the color picker box in styles sidebar and then clicking on the page as you have already been doing.
To execute easily a script file in the same folder (or subfolder of) as the caller you can use this:
# Get full path to the script:
$ScriptRoute = [System.IO.Path]::GetFullPath([System.IO.Path]::Combine($PSScriptRoot, "Scriptname.ps1"))
# Execute script at location:
&"$ScriptRoute"
You set the CSS to :
#elementID {
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
height: 200px;
}
It centers the image, but does not scale it.
In newer browsers you can use the background-size
property and do:
#elementID {
height: 200px;
width: 100%;
background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
background-size: 100% 100%;
}
Other than that, a regular image is one way to do it, but then it's not really a background image.
?
Clean and Simple -
$selectquery="SELECT id FROM tableName ORDER BY id DESC LIMIT 1";
$result = $mysqli->query($selectquery);
$row = $result->fetch_assoc();
echo $row['id'];
If you just need a number that's bigger than all others, you can use
float('inf')
in similar fashion, a number smaller than all others:
float('-inf')
This works in both python 2 and 3.
Yes You can compile and execute without main method By using static block. But after static block executed (printed) you will get an error saying no main method found.
And Latest INFO --> YOU cant Do this with JAVA 7 version. IT will not execute.
{
static
{
System.out.println("Hello World!");
System.exit(0); // prevents “main method not found” error
}
}
But this will not execute with JAVA 7 version.
Default migration generator does not handle default values (column modifiers are supported but do not include default
or null
), but you could create your own generator.
You can also manually update the migration file prior to running rake db:migrate
by adding the options to add_column
:
add_column :tweet, :retweets_count, :integer, :null => false, :default => 0
... and read Rails API
I found information about .bashrc and .bash_profile here to sum it up:
.bash_profile is executed when you login. Stuff you put in there might be your PATH and other important environment variables.
.bashrc is used for non login shells. I'm not sure what that means. I know that RedHat executes it everytime you start another shell (su to this user or simply calling bash again) You might want to put aliases in there but again I am not sure what that means. I simply ignore it myself.
.profile is the equivalent of .bash_profile for the root. I think the name is changed to let other shells (csh, sh, tcsh) use it as well. (you don't need one as a user)
There is also .bash_logout wich executes at, yeah good guess...logout. You might want to stop deamons or even make a little housekeeping . You can also add "clear" there if you want to clear the screen when you log out.
Also there is a complete follow up on each of the configurations files here
These are probably even distro.-dependant, not all distros choose to have each configuraton with them and some have even more. But when they have the same name, they usualy include the same content.
If you are using windows8:
command prompt
command prompt
and click Run as administrator
. Then execute the keytool command.This one worked for me:
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
The problem with datetime.utcnow()
and other such solutions is that they are slow.
More efficient solution may look like this one:
def _timestamp(prec=0):
t = time.time()
s = time.strftime("%H:%M:%S", time.localtime(t))
if prec > 0:
s += ("%.9f" % (t % 1,))[1:2+prec]
return s
Where prec
would be 3
in your case (milliseconds).
The function works up to 9 decimal places (please note number 9
in the 2nd formatting string).
If you'd like to round the fractional part, I'd suggest building "%.9f"
dynamically with desired number of decimal places.
The dword ptr
part is called a size directive. This page explains them, but it wasn't possible to direct-link to the correct section.
Basically, it means "the size of the target operand is 32 bits", so this will bitwise-AND the 32-bit value at the address computed by taking the contents of the ebp
register and subtracting four with 0.
Using Moshi:
When building your Retrofit Service add .asLenient() to your MoshiConverterFactory. You don't need a ScalarsConverter. It should look something like this:
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(ENDPOINT)
.addConverterFactory(MoshiConverterFactory.create().asLenient())
.build()
.create(UserService::class.java)
package newpckg;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class StrangeDate {
public static void main(String[] args) {
// string containing date in one format
// String strDate = "2012-05-20T09:00:00.000Z";
String strDate = "2012-05-20T09:00:00.000Z";
try {
// create SimpleDateFormat object with source string date format
SimpleDateFormat sdfSource = new SimpleDateFormat(
"yyyy-MM-dd'T'hh:mm:ss'.000Z'");
// parse the string into Date object
Date date = sdfSource.parse(strDate);
// create SimpleDateFormat object with desired date format
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd/MM/yyyy, ha");
// parse the date into another format
strDate = sdfDestination.format(date);
System.out
.println("Date is converted from yyyy-MM-dd'T'hh:mm:ss'.000Z' format to dd/MM/yyyy, ha");
System.out.println("Converted date is : " + strDate.toLowerCase());
} catch (ParseException pe) {
System.out.println("Parse Exception : " + pe);
}
}
}
Give it a try: http://convertwebpage.com — this is a web-application that can convert web-pages into images (jpg, png) or into pdf and has some options.
Have you tried JQuery? Vanilla javascript can be tough. Try using this:
$('.container-element').add('<div>Insert Div Content</div>');
.container-element
is a JQuery selector that marks the element with the class "container-element" (presumably the parent element in which you want to insert your divs). Then the add()
function inserts HTML into the container-element.
redirect 301 /contact.php /contact-us.php
There is no point using the redirectmatch rule and then have to write your links so they are exact match. If you don't include you don't have to exclude! Just use redirect without match and then use links normally
It happens when common column in both table are of different data type.
Example: In table1, you have date as string whereas in table2 you have date as datetime. so before merging,we need to change date to common data type.
These are the rules of the C++ language:
12
) is a "rvalue"int &ri = 12;
is ill-formedYou have to understand that these are C++ rules. They just are.
It is easy to invent a different language, say C++', with slightly different rules. In C++', it would be permitted to create a non-const reference with a rvalue. There is nothing inconsistent or impossible here.
But it would allow some risky code where the programmer might not get what he intended, and C++ designers rightly decided to avoid that risk.
you can do it so simple:
First: For Example in Models you have User.cs with this implementation
public class User
{
public string username { get; set; }
public string age { get; set; }
}
We are passing the empty model to user – This model would be filled with user’s data when he submits the form like this
public ActionResult Add()
{
var model = new User();
return View(model);
}
When you return the View by empty User as model, it maps with the structure of the form that you implemented. We have this on HTML side:
@model MyApp.Models.Student
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.username, htmlAttributes: new {
@class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.username, new {
htmlAttributes = new { @class = "form-
control" } })
@Html.ValidationMessageFor(model => model.userame, "",
new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.age, htmlAttributes: new { @class
= "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.age, new { htmlAttributes =
new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.age, "", new {
@class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default"
/>
</div>
</div>
</div>
}
So on button submit you will use it like this
[HttpPost]
public ActionResult Add(User user)
{
// now user.username has the value that user entered on form
}
The listed return type of the method is Task<string>
. You're trying to return a string
. They are not the same, nor is there an implicit conversion from string to Task<string>
, hence the error.
You're likely confusing this with an async
method in which the return value is automatically wrapped in a Task
by the compiler. Currently that method is not an async method. You almost certainly meant to do this:
private async Task<string> methodAsync()
{
await Task.Delay(10000);
return "Hello";
}
There are two key changes. First, the method is marked as async
, which means the return type is wrapped in a Task
, making the method compile. Next, we don't want to do a blocking wait. As a general rule, when using the await
model always avoid blocking waits when you can. Task.Delay
is a task that will be completed after the specified number of milliseconds. By await
-ing that task we are effectively performing a non-blocking wait for that time (in actuality the remainder of the method is a continuation of that task).
If you prefer a 4.0 way of doing it, without using await
, you can do this:
private Task<string> methodAsync()
{
return Task.Delay(10000)
.ContinueWith(t => "Hello");
}
The first version will compile down to something that is more or less like this, but it will have some extra boilerplate code in their for supporting error handling and other functionality of await
we aren't leveraging here.
If your Thread.Sleep(10000)
is really meant to just be a placeholder for some long running method, as opposed to just a way of waiting for a while, then you'll need to ensure that the work is done in another thread, instead of the current context. The easiest way of doing that is through Task.Run
:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
SomeLongRunningMethod();
return "Hello";
});
}
Or more likely:
private Task<string> methodAsync()
{
return Task.Run(()=>
{
return SomeLongRunningMethodThatReturnsAString();
});
}
For a single line of text (or a single character) you can use this technique:
It can be used when #box
has a non-fixed, relative height in %.
<div id="box"></div>
#box::before {
display: block;
content: "";
height: 50%;
}
#box::after {
vertical-align: top;
line-height: 0;
content: "TextContent";
}
See a live demo at JsBin (easier to edit CSS) or JsFiddle (easier to change height of result frame).
If you want to place inner text in HTML, not in CSS, then you need to wrap text content in additional inline element and edit #box::after
to match it. (And, of course, content:
property should be removed.)
For example,
<div id="box"><span>TextContent</span></div>
.
In this case, #box::after
should be replaced with #box span
.
For Internet Explorer 8 support you must replace ::
with :
.
you can't use dataSourceClassName approach in application.properties configurations as said by @Andy Wilkinson. if you want to have dataSourceClassName anyway you can use Java Config as:
@Configuration
@ComponentScan
class DataSourceConfig {
@Value("${spring.datasource.username}")
private String user;
@Value("${spring.datasource.password}")
private String password;
@Value("${spring.datasource.url}")
private String dataSourceUrl;
@Value("${spring.datasource.dataSourceClassName}")
private String dataSourceClassName;
@Value("${spring.datasource.poolName}")
private String poolName;
@Value("${spring.datasource.connectionTimeout}")
private int connectionTimeout;
@Value("${spring.datasource.maxLifetime}")
private int maxLifetime;
@Value("${spring.datasource.maximumPoolSize}")
private int maximumPoolSize;
@Value("${spring.datasource.minimumIdle}")
private int minimumIdle;
@Value("${spring.datasource.idleTimeout}")
private int idleTimeout;
@Bean
public DataSource primaryDataSource() {
Properties dsProps = new Properties();
dsProps.put("url", dataSourceUrl);
dsProps.put("user", user);
dsProps.put("password", password);
dsProps.put("prepStmtCacheSize",250);
dsProps.put("prepStmtCacheSqlLimit",2048);
dsProps.put("cachePrepStmts",Boolean.TRUE);
dsProps.put("useServerPrepStmts",Boolean.TRUE);
Properties configProps = new Properties();
configProps.put("dataSourceClassName", dataSourceClassName);
configProps.put("poolName",poolName);
configProps.put("maximumPoolSize",maximumPoolSize);
configProps.put("minimumIdle",minimumIdle);
configProps.put("minimumIdle",minimumIdle);
configProps.put("connectionTimeout", connectionTimeout);
configProps.put("idleTimeout", idleTimeout);
configProps.put("dataSourceProperties", dsProps);
HikariConfig hc = new HikariConfig(configProps);
HikariDataSource ds = new HikariDataSource(hc);
return ds;
}
}
reason you cannot use dataSourceClassName because it will throw and exception
Caused by: java.lang.IllegalStateException: both driverClassName and dataSourceClassName are specified, one or the other should be used.
which mean spring boot infers from spring.datasource.url property the Driver and at the same time setting the dataSourceClassName creates this exception. To make it right your application.properties should look something like this for HikariCP datasource:
# hikariCP
spring.jpa.databasePlatform=org.hibernate.dialect.MySQLDialect
spring.datasource.url=jdbc:mysql://localhost:3306/exampledb
spring.datasource.username=root
spring.datasource.password=
spring.datasource.poolName=SpringBootHikariCP
spring.datasource.maximumPoolSize=5
spring.datasource.minimumIdle=3
spring.datasource.maxLifetime=2000000
spring.datasource.connectionTimeout=30000
spring.datasource.idleTimeout=30000
spring.datasource.pool-prepared-statements=true
spring.datasource.max-open-prepared-statements=250
Note: Please check if there is any tomcat-jdbc.jar or commons-dbcp.jar in your classpath added most of the times by transitive dependency. If these are present in classpath Spring Boot will configure the Datasource using default connection pool which is tomcat. HikariCP will only be used to create the Datasource if there is no other provider in classpath. there is a fallback sequence from tomcat -> to HikariCP -> to Commons DBCP.
Activity
to a Fragment
Activity:
Bundle bundle = new Bundle();
String myMessage = "Stackoverflow is cool!";
bundle.putString("message", myMessage );
FragmentClass fragInfo = new FragmentClass();
fragInfo.setArguments(bundle);
transaction.replace(R.id.fragment_single, fragInfo);
transaction.commit();
Fragment:
Reading the value in fragment
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
String myValue = this.getArguments().getString("message");
...
...
...
}
But if you want to send values from Fragment to Activity, read the answer of jpardogo, you must need interfaces, more info: Communicating with other Fragments
If you can count on having a period of time where the table is in a stable state with no new inserts going on, this should do it (untested):
DECLARE
last_used NUMBER;
curr_seq NUMBER;
BEGIN
SELECT MAX(pk_val) INTO last_used FROM your_table;
LOOP
SELECT your_seq.NEXTVAL INTO curr_seq FROM dual;
IF curr_seq >= last_used THEN EXIT;
END IF;
END LOOP;
END;
This enables you to get the sequence back in sync with the table, without dropping/recreating/re-granting the sequence. It also uses no DDL, so no implicit commits are performed. Of course, you're going to have to hunt down and slap the folks who insist on not using the sequence to populate the column...
Motti is right about the order, but there are some other things to consider:
Compilers typically use a hidden flag variable to indicate if the local statics have already been initialized, and this flag is checked on every entry to the function. Obviously this is a small performance hit, but what's more of a concern is that this flag is not guaranteed to be thread-safe.
If you have a local static as above, and foo
is called from multiple threads, you may have race conditions causing plonk
to be initialized incorrectly or even multiple times. Also, in this case plonk
may get destructed by a different thread than the one which constructed it.
Despite what the standard says, I'd be very wary of the actual order of local static destruction, because it's possible that you may unwittingly rely on a static being still valid after it's been destructed, and this is really difficult to track down.
First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.
To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar()
method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.
If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:
I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.
JpaRepository
extends PagingAndSortingRepository
which in turn extends CrudRepository
.
Their main functions are:
CrudRepository
mainly provides CRUD functions.PagingAndSortingRepository
provides methods to do pagination and sorting records.JpaRepository
provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.Because of the inheritance mentioned above, JpaRepository
will have all the functions of CrudRepository
and PagingAndSortingRepository
. So if you don't need the repository to have the functions provided by JpaRepository
and PagingAndSortingRepository
, use CrudRepository
.
Also try aspnet_regiis -u
then aspnet_regiis -i
on below path
C:\Windows\Microsoft.NET\Framework\v4.0.30319
Now restart the IIS and check
Hope this will help !
Want zero warnings? Use it like this:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
Explanation: The default value of the extended
option has been deprecated, meaning you need to explicitly pass true or false value.
Recursion-based, pure pathlib
solution:
from pathlib import Path
def remove_path(path: Path):
if path.is_file() or path.is_symlink():
path.unlink()
return
for p in path.iterdir():
remove_path(p)
path.rmdir()
Supports Windows and symbolic links
You'd need to be careful as onBlur
has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).
There is, however, no way to use onFocusOut
in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.
Best example is here
thanks #define SIZE 10
void size(int arr[SIZE])
{
printf("size of array is:%d\n",sizeof(arr));
}
int main()
{
int arr[SIZE];
size(arr);
return 0;
}
Try this
We can update GTF answer to update timestamps easily
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=>date('Y-m-d H:i:s'),
'modified_at'=> date('Y-m-d H:i:s')
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=>date('Y-m-d H:i:s'),
'modified_at'=> date('Y-m-d H:i:s')
),
//...
);
Coder::insert($data);
Update: to simplify the date we can use carbon as @Pedro Moreira suggested
$now = Carbon::now('utc')->toDateTimeString();
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=> $now,
'modified_at'=> $now
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=> $now,
'modified_at'=> $now
),
//...
);
Coder::insert($data);
UPDATE2: for laravel 5 , use updated_at
instead of modified_at
$now = Carbon::now('utc')->toDateTimeString();
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=> $now,
'updated_at'=> $now
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=> $now,
'updated_at'=> $now
),
//...
);
Coder::insert($data);
allow_url_fopen
is generally set to On.
If it is not On, then you can try two things.
Create an .htaccess
file and keep it in root folder ( sometimes it may need to place it one step back folder of the root) and paste this code there.
php_value allow_url_fopen On
Create a php.ini
file (for update server php5.ini
) and keep it in root folder (sometimes it may need to place it one step back folder of the root) and paste the following code there:
allow_url_fopen = On;
I have personally tested the above solutions; they worked for me.
The remote
section also specifies fetch rules. You could add something like this into it to fetch all branches from the remote:
fetch = +refs/heads/*:refs/remotes/origin/*
(Or replace origin
with bitbucket
.)
Please read about it here: 10.5 Git Internals - The Refspec
CONVERT
takes the column name, not a string containing the column name; your current expression tries to convert the string A.my_NvarcharColumn
to an integer instead of the column content.
SELECT convert (int, N'A.my_NvarcharColumn') FROM A;
should instead be
SELECT convert (int, A.my_NvarcharColumn) FROM A;
Simple SQLfiddle here.
In Linux Mint, and most likely Ubuntu, you can try "nvidia-smi --loop=1"
Very easy. First put
io.sockets.on('connection', function (socket) {
console.log(socket);
You will see all fields of socket. then use CTRL+F and search the word address. Finally, when you find the field remoteAddress use dots to filter data. in my case it is
console.log(socket.conn.remoteAddress);
there is a simple way to do this: in the html file add:
<link rel="stylesheet" href="fonts/vermin_vibes.ttf" />
Note: you put the name of .ttf file you have. then go to to your css file and add:
h1 {
color: blue;
font-family: vermin vibes;
}
Note: you put the font family name of the font you have.
Note: do not write the font-family name as your font.ttf name example: if your font.ttf name is: "vermin_vibes.ttf" your font-family will be: "vermin vibes" font family doesn't contain special chars as "-,_"...etc it only can contain spaces.
cat | git log --author="authorName" > author_commits_details.txt
This gives your commits in text format.
As the plural in getElementsByName()
implies, does it always return list of elements that have this name. So when you have an input element with that name:
<input type="text" name="Tue">
And it is the first one with that name, you have to use document.getElementsByName('Tue')[0]
to get the first element of the list of elements with this name.
Beside that are properties case sensitive and the correct spelling of the value property is .value
.
The main reason is that classic C casts make no distinction between what we call static_cast<>()
, reinterpret_cast<>()
, const_cast<>()
, and dynamic_cast<>()
. These four things are completely different.
A static_cast<>()
is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A dynamic_cast<>()
is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference).
A reinterpret_cast<>()
(or a const_cast<>()
) on the other hand is always dangerous. You tell the compiler: "trust me: I know this doesn't look like a foo
(this looks as if it isn't mutable), but it is".
The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules.
Let's assume these:
class CDerivedClass : public CMyBase {...};
class CMyOtherStuff {...} ;
CMyBase *pSomething; // filled somewhere
Now, these two are compiled the same way:
CDerivedClass *pMyObject;
pMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked
pMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<>
// Safe; as long as we checked
// but harder to read
However, let's see this almost identical code:
CMyOtherStuff *pOther;
pOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert
pOther = (CMyOtherStuff*)(pSomething); // No compiler error.
// Same as reinterpret_cast<>
// and it's wrong!!!
As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved.
The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for "static_cast<" or "reinterpret_cast<".
pOther = reinterpret_cast<CMyOtherStuff*>(pSomething);
// No compiler error.
// but the presence of a reinterpret_cast<> is
// like a Siren with Red Flashing Lights in your code.
// The mere typing of it should cause you to feel VERY uncomfortable.
That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct.
Everyone is doing this programmily so I thought this answer would fit perfectly here. This code worked for my in the xml. Im NOT thinking about ratio yet, but still wanted to place this answer if it would help anyone.
android:adjustViewBounds="true"
Cheers..
Your function would work like this:
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
END
$$ LANGUAGE plpgsql;
Call:
SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count()
returns bigint
, but you had rowcount
defined as integer
, so you need an explicit cast ::int
to make this work
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.
Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)
The query itself seems rather odd, btw. But that's beside the point here.
You need to decode it to convert it to a string. Check the answer here about bytes literal in python3.
In [1]: b'I posted a new photo to Facebook'.decode('utf-8')
Out[1]: 'I posted a new photo to Facebook'
$?
is the exit status of a command, such that you can daisy-chain a series of commands.
Example
command1 && command2 && command3
command2
will run if command1's
$?
yields a success (0)
and command3
will execute if $?
of command2
will yield a success
If you want statically make columns not sortable. You can do this way
Some answers don't work with large numbers.
Convert integer to the hex representation, then convert it to bytes:
def int_to_bytes(number):
hrepr = hex(number).replace('0x', '')
if len(hrepr) % 2 == 1:
hrepr = '0' + hrepr
return bytes.fromhex(hrepr)
Result:
>>> int_to_bytes(2**256 - 1)
b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
It is time inefficient to compare each number, needlessly leading to a linear complexity. Having said that, this approach avoids any inequality checks:
import itertools
m, n = 5, 10
for i in itertools.chain(range(m), range(m + 1, n)):
print(i) # skips m = 5
As an aside, you woudn't want to use (*range(m), *range(m + 1, n))
even though it works because it will expand the iterables into a tuple and this is memory inefficient.
Credit: comment by njzk2, answer by Locke
Its possible using pseudo element (after).
I have added to the original code a
position:relativeand some margin.
#content{
width: 100px;
min-height: 100px;
margin: 20px auto;
border-style: ridge;
border-color: #567498;
border-spacing:10px;
position:relative;
background:#000;
}
#content:after {
content: '';
position: absolute;
top: -15px;
left: -15px;
right: -15px;
bottom: -15px;
border: red 2px solid;
}
I had this problem and I made a tool to export an HTML table to CSV file. The problem I had with FileSaver.js is that this tool grabs the table with html format, this is why some people can't open the file in excel or google. All you have to do is export the js file and then call the function. This is the github url https://github.com/snake404/tableToCSV if someone has the same problem.
select * from Reference where reference_dt = DATEADD(mm, 1, reference_dt)
view.isVisible = true
view.isInvisible = true
view.isGone = true
// For these to work, you need to use androidx and import:
import androidx.core.view.isVisible // or isInvisible/isGone
If you'd like them to be more consistent length, work for nullable views, and lower the chance of writing the wrong boolean, try using these custom extensions:
// Example
view.hide()
fun View?.show() {
if (this == null) return
if (!isVisible) isVisible = true
}
fun View?.hide() {
if (this == null) return
if (!isInvisible) isInvisible = true
}
fun View?.gone() {
if (this == null) return
if (!isGone) isGone = true
}
To make conditional visibility simple, also add these:
fun View?.show(visible: Boolean) {
if (visible) show() else gone()
}
fun View?.hide(hide: Boolean) {
if (hide) hide() else show()
}
fun View?.gone(gone: Boolean = true) {
if (gone) gone() else show()
}
From the C# language specification (PDF page 287 - or 300th page of the PDF):
Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier.
Actually, I do like mark instruction but little differently.
I've added C:\Program Files (x86)\GnuWin32\bin\
to the Path variable,
and try to run it with type awk using cmd.
Hope it works.
By combining the multicol package and enumitem package packages it is easy to define environments that are multi-column analogues of the enumerate and itemize environments:
\documentclass{article}
\usepackage{enumitem}
\usepackage{multicol}
\newlist{multienum}{enumerate}{1}
\setlist[multienum]{
label=\alph*),
before=\begin{multicols}{2},
after=\end{multicols}
}
\newlist{multiitem}{itemize}{1}
\setlist[multiitem]{
label=\textbullet,
before=\begin{multicols}{2},
after=\end{multicols}
}
\begin{document}
\textsf{Two column enumerate}
\begin{multienum}
\item item 1
\item item 2
\item item 3
\item item 4
\item item 5
\item item 6
\end{multienum}
\textsf{Two column itemize}
\begin{multiitem}
\item item 1
\item item 2
\item item 3
\item item 4
\item item 5
\item item 6
\end{multiitem}
\end{document}
The output is what you would hope for:
This question keeps coming up and I did not find a satisfying result yet, so here is what worked for me (based on a previous answer https://stackoverflow.com/a/52706362/1806760, which is not working):
My server is https://gitlab.dev
with a self-signed certificate.
First run git config --system --edit
(from an elevated command prompt, change --system
to --global
if you want to do it for just your user), then insert the following snippet after any previous [http]
sections:
[http "https://gitlab.dev"]
sslVerify = false
Then check if you did everything correctly:
> git config --type=bool --get-urlmatch http.sslVerify https://gitlab.dev
false
The cd
is done within the script's shell. When the script ends, that shell exits, and then you are left in the directory you were. "Source" the script, don't run it. Instead of:
./myscript.sh
do
. ./myscript.sh
(Notice the dot and space before the script name.)
I am late, hope it will help someone ....This is a known issue with IIS 8.0
The solution is to delete the 3.x module and handler from IIS manager. You could delete them at the application or site level if you want to keep them in applicationHost.config. But I wanted to delete them from applicationHost.config. do the following steps:
In IIS manager, click the machine name node. In “Features View”, double-click “Modules”. Find “ServiceModel” and remove it. Image 1 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’
Go back to the machine name node’s “Features View”, double-click “Handler Mappings”. Find “svc-Integrated” and remove it. Image 2 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’
npm run-script <custom_script_name>
or
npm run <custom_script_name>
In your example, you would want to run npm run-script script1
or npm run script1
.
See https://docs.npmjs.com/cli/run-script
Node also allows you to run custom scripts for certain lifecycle events, like after npm install
is run. These can be found here.
For example:
"scripts": {
"postinstall": "electron-rebuild",
},
This would run electron-rebuild
after a npm install
command.
SELECT cols
FROM table
WHERE cols IS NULL
What is the young generation?
The Young Generation is where all new objects are allocated and aged. When the young generation fills up, this causes a minor garbage collection. A young generation full of dead objects is collected very quickly. Some survived objects are aged and eventually move to the old generation.
What is the old generation?
The Old Generation is used to store long surviving objects. Typically, a threshold is set for young generation object and when that age is met, the object gets moved to the old generation. Eventually the old generation needs to be collected. This event is called a major garbage collection
What is the permanent generation?
The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application.
PermGen has been replaced with Metaspace since Java 8 release.
PermSize & MaxPermSize parameters will be ignored now
How does the three generations interact/relate to each other?
Image source & oracle technetwork tutorial article: http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/gc01/index.html
"The General Garbage Collection Process" in above article explains the interactions between them with many diagrams.
Have a look at summary diagram:
I needed to delete an Angular 6 directive whose spec file was erroneous. Even after deleting the offending files, removing all references to it and rebuilding the app, TS was still reporting the same error. What worked for me was restarting Visual Studio - this cleared the error and all traces of the old unwanted directive.
The following definition might be more efficient than the first solution proposed
def new_list_from_intervals(original_list, *intervals):
n = sum(j - i for i, j in intervals)
new_list = [None] * n
index = 0
for i, j in intervals :
for k in range(i, j) :
new_list[index] = original_list[k]
index += 1
return new_list
then you can use it like below
new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))
In kotlin you can use like this
fun changeDateFormats(currentFormat: String, dateString: String): String {
var result = ""
try {
val formatterOld = SimpleDateFormat(currentFormat, Locale.getDefault())
formatterOld.timeZone = TimeZone.getTimeZone("UTC")
var date: Date? = null
date = formatterOld.parse(dateString)
val dayFormate = SimpleDateFormat("d", Locale.getDefault())
var day = dayFormate.format(date)
val formatterNew = SimpleDateFormat("hh:mm a, d'" + getDayOfMonthSuffix(day.toInt()) + "' MMM yy", Locale.getDefault())
if (date != null) {
result = formatterNew.format(date)
}
} catch (e: ParseException) {
e.printStackTrace()
return dateString
}
return result
}
private fun getDayOfMonthSuffix(n: Int): String {
if (n in 11..13) {
return "th"
}
when (n % 10) {
1 -> return "st"
2 -> return "nd"
3 -> return "rd"
else -> return "th"
}
}
set like this
txt_chat_time_me.text = changeDateFormats("SERVER_DATE", "DATE")
Do as below using String#tr
:
"((String1))".tr('()', '')
# => "String1"
new JwtSecurityTokenHandler().ReadToken("")
will return a SecurityToken
new JwtSecurityTokenHandler().ReadJwtToken("")
will return a JwtSecurityToken
If you just change the method you are using you can avoid the cast in the above answer
You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.
If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)
In my case, I had to change the cell padding of an element that contained an input checkbox for a table that's being dynamically rendered with DataTables:
<td class="dt-center">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
After implementing the following line code within the initComplete function I was able to produce the correct padding, which fixed the rows from being displayed with an abnormally large height
$('tbody td:has(input.a)').css('padding', '0px');
Now, you can see that the correct styles are being applied to the parent element:
<td class=" dt-center" style="padding: 0px;">
<input class="a" name="constCheck" type="checkbox" checked="">
</td>
Essentially, this answer is an extension of @KP's answer, but the more collaboration of implementing this the better. In summation, I hope this helps someone else because it works! Lastly, thank you so much @KP for leading me in the right direction!
guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:
Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.
So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.
I solved my problem just follow this steps:
? Copy .aar package in app/libs.
? Add this in app/build.gradle file:
repositories {
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):
dependencies {
compile(name:'package_name', ext:'aar')
}
So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.
At its core, Git is a set of command line utility programs that are designed to execute on a Unix style command-line environment. Modern operating systems like Linux and macOS both include built-in Unix command line terminals. This makes Linux and macOS complementary operating systems when working with Git. Microsoft Windows instead uses Windows command prompt, a non-Unix terminal environment.
What is Git Bash?
Git Bash is an application for Microsoft Windows environments which provides an emulation layer for a Git command line experience. Bash is an acronym for Bourne Again Shell. A shell is a terminal application used to interface with an operating system through written commands. Bash is a popular default shell on Linux and macOS. Git Bash is a package that installs Bash, some common bash utilities, and Git on a Windows operating system.
First, make sure that the source page and the target page are both served through the file
URI scheme. You can't force an http
page to open a file
page (but it works the other way around).
Next, your script that calls window.open()
should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open()
won't work.
You can test this right here in this question page. Run these in Chrome's JavaScript console:
// Does nothing
window.open('http://google.com');
// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });
// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });
You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
</head>
<body>
<h5>Feel the presha</h5>
<h3>Come play my game, I'll test ya</h3>
<h1>Psycho- somatic- addict- insane!</h1>
</body>
</html>
Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.
This is over simplifying it, but Express.js is to Node.js what Ruby on Rails or Sinatra is to Ruby.
Express 3.x is a light-weight web application framework to help organize your web application into an MVC architecture on the server side. You can use a variety of choices for your templating language (like EJS, Jade, and Dust.js).
You can then use a database like MongoDB with Mongoose (for modeling) to provide a backend for your Node.js application. Express.js basically helps you manage everything, from routes, to handling requests and views.
Redis is a key/value store -- commonly used for sessions and caching in Node.js applications. You can do a lot more with it, but that's what I'm using it for. I use MongoDB for more complex relationships, like line-item <-> order <-> user relationships. There are modules (most notably connect-redis) that will work with Express.js. You will need to install the Redis database on your server.
Here is a link to the Express 3.x guide: https://expressjs.com/en/3x/api.html
here is a solution if you are not using jquery:
myArray = myArray.filter(function( obj ) {
return obj.id !== id;
});
[edit] The lovely chosen jQuery plugin has been bought to my attention, looks like a great alternative to me.
Or if you just want to use jQuery autocomplete, I've extended the combobox example to support defaults and remove the tooltips to give what I think is more expected behaviour. Try it out.
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var input,
that = this,
wasOpen = false,
select = this.element.hide(),
selected = select.children(":selected"),
defaultValue = selected.text() || "",
wrapper = this.wrapper = $("<span>")
.addClass("ui-combobox")
.insertAfter(select);
function removeIfInvalid(element) {
var value = $(element).val(),
matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(value) + "$", "i"),
valid = false;
select.children("option").each(function () {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
$(element).val(defaultValue);
select.val(defaultValue);
input.data("ui-autocomplete").term = "";
}
}
input = $("<input>")
.appendTo(wrapper)
.val(defaultValue)
.attr("title", "")
.addClass("ui-state-default ui-combobox-input")
.width(select.width())
.autocomplete({
delay: 0,
minLength: 0,
autoFocus: true,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function (event, ui) {
ui.item.option.selected = true;
that._trigger("selected", event, {
item: ui.item.option
});
},
change: function (event, ui) {
if (!ui.item) {
removeIfInvalid(this);
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
$("<a>")
.attr("tabIndex", -1)
.appendTo(wrapper)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-combobox-toggle")
.mousedown(function () {
wasOpen = input.autocomplete("widget").is(":visible");
})
.click(function () {
input.focus();
// close if already visible
if (wasOpen) {
return;
}
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
});
},
_destroy: function () {
this.wrapper.remove();
this.element.show();
}
});
})(jQuery);
I had this problem before, and the reason is very simple: Check your variables, if there were strings, so put it in quotes '$your_string_variable_here' ,, if it were numerical keep it without any quotes. for example, if I had these data: $name ( It will be string ) $phone_number ( It will be numerical ) So, it will be like that:
$query = "INSERT INTO users
(name
, phone
) VALUES ('$name', $phone)";
Just like that and it will be fixed ^_^
For further readers/searchers:
As Rene Pot points out on this topic,
By adding the attribute
readonly
(orreadonly="readonly"
) to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.
With this method, you can avoid popping up the "soft" Keyboard and still launch click events / fill the input by any on-screen keyboard.
This solution also works fine with date-time-pickers which generally already implement controls.
I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.
def remove_chars(line):
line7=line[7].translate(None,'abcd')
return line[:7]+[line7]+line[8:]
line= ['ad','da','sdf','asd',
'3424','342sfas','asdfaf','sdfa',
'afase']
print line[7]
line = remove_chars(line)
print line[7]
Open Outlook 2013 > File > Office account > About Outlook > click large "? About Outlook" button > read popup description
.then() is chainable and will wait for previous .then() to resolve.
.success() and .error() can be chained, but they will all fire at once (so not much point to that)
.success() and .error() are just nice for simple calls (easy makers):
$http.post('/getUser').success(function(user){
...
})
so you don't have to type this:
$http.post('getUser').then(function(response){
var user = response.data;
})
But generally i handler all errors with .catch():
$http.get(...)
.then(function(response){
// successHandler
// do some stuff
return $http.get('/somethingelse') // get more data
})
.then(anotherSuccessHandler)
.catch(errorHandler)
If you need to support <= IE8 then write your .catch() and .finally() like this (reserved methods in IE):
.then(successHandler)
['catch'](errorHandler)
Working Examples:
Here's something I wrote in more codey format to refresh my memory on how it all plays out with handling errors etc:
You should be able to simply do this:
Context context = new InitialContext();
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");
If you are looking it up from a remote destination you need to use the WL initial context factory like this:
Hashtable<String, String> h = new Hashtable<String, String>(7);
h.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, pURL); //For example "t3://127.0.0.1:7001"
h.put(Context.SECURITY_PRINCIPAL, pUsername);
h.put(Context.SECURITY_CREDENTIALS, pPassword);
InitialContext context = new InitialContext(h);
dataSource = (javax.sql.DataSource) context.lookup("jdbc/myDataSource");
If your server supports Short Tags, or you use PHP 5.4, you can use:
<?=date("Y")?>
It's not an insert if the record already exists in t1 (the user_id matches) unless you are happy to create duplicate user_id's.
You might want an update?
UPDATE t1
SET <t1.col_list> = (SELECT <t2.col_list>
FROM t2
WHERE t2.user_id = t1.user_id)
WHERE EXISTS
(SELECT 1
FROM t2
WHERE t1.user_id = t2.user_id);
Hope it helps...
I had a similar issue with Spring Data MongoDB: I had to add the package path to @EnableMongoRepositories
In browsers other than Internet Explorer, you can pass parameters to the function together after the delay:
var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);
So, you can do this:
var timeoutID = window.setTimeout(function (self) {
console.log(self);
}, 500, this);
This is better in terms of performance than a scope lookup (caching this
into a variable outside of the timeout / interval expression), and then creating a closure (by using $.proxy
or Function.prototype.bind
).
The code to make it work in IEs from Webreflection:
/*@cc_on
(function (modifierFn) {
// you have to invoke it as `window`'s property so, `window.setTimeout`
window.setTimeout = modifierFn(window.setTimeout);
window.setInterval = modifierFn(window.setInterval);
})(function (originalTimerFn) {
return function (callback, timeout){
var args = [].slice.call(arguments, 2);
return originalTimerFn(function () {
callback.apply(this, args)
}, timeout);
}
});
@*/
you can use update from...
something like:
update shipment set.... from shipment inner join ProfilerTest.dbo.BookingDetails on ...
I recommend to check event.metaKey as well. If that's set to true, the user might be doing something like cmd-A to select all the text in the field. You should allow that too.
C:\> wmic cpu get loadpercentage
LoadPercentage
0
Or
C:\> @for /f "skip=1" %p in ('wmic cpu get loadpercentage') do @echo %p%
4%
Another (simpler) Linux solution:
rm -r `find /path/to/foo -name .svn`
To answer the second part of the question:
If they can be virtual, what is an example of a scenario in which one would use such a function?
This is not an unreasonable thing to want to do. For instance, Java (where every method is virtual) has no problems with generic methods.
One example in C++ of wanting a virtual function template is a member function that accepts a generic iterator. Or a member function that accepts a generic function object.
The solution to this problem is to use type erasure with boost::any_range and boost::function, which will allow you to accept a generic iterator or functor without the need to make your function a template.
An alternate way is to construct a view which is then queried just like a table. In many database managers using a view can result in better performance.
CREATE VIEW xyz SELECT q.question, a.alternative
FROM tbl_question AS q, tbl_alternative AS a
WHERE q.categoryid = a.categoryid
AND q._id = a.questionid;
This is from memory so there may be some syntactic issues. http://www.sqlite.org/lang_createview.html
I mention this approach because then you can use SQLiteQueryBuilder with the view as you implied that it was preferred.
I prefer the way Golang does quote escaping for XML (and a few extras like newline escaping, and escaping some other characters), so I have ported its XML escape function to PHP below
function isInCharacterRange(int $r): bool {
return $r == 0x09 ||
$r == 0x0A ||
$r == 0x0D ||
$r >= 0x20 && $r <= 0xDF77 ||
$r >= 0xE000 && $r <= 0xFFFD ||
$r >= 0x10000 && $r <= 0x10FFFF;
}
function xml(string $s, bool $escapeNewline = true): string {
$w = '';
$Last = 0;
$l = strlen($s);
$i = 0;
while ($i < $l) {
$r = mb_substr(substr($s, $i), 0, 1);
$Width = strlen($r);
$i += $Width;
switch ($r) {
case '"':
$esc = '"';
break;
case "'":
$esc = ''';
break;
case '&':
$esc = '&';
break;
case '<':
$esc = '<';
break;
case '>':
$esc = '>';
break;
case "\t":
$esc = '	';
break;
case "\n":
if (!$escapeNewline) {
continue 2;
}
$esc = '
';
break;
case "\r":
$esc = '
';
break;
default:
if (!isInCharacterRange(mb_ord($r)) || (mb_ord($r) === 0xFFFD && $Width === 1)) {
$esc = "\u{FFFD}";
break;
}
continue 2;
}
$w .= substr($s, $Last, $i - $Last - $Width) . $esc;
$Last = $i;
}
$w .= substr($s, $Last);
return $w;
}
Note you'll need at least PHP7.2 because of the mb_ord
usage, or you'll have to swap it out for another polyfill, but these functions are working great for us!
For anyone curious, here is the relevant Go source https://golang.org/src/encoding/xml/xml.go?s=44219:44263#L1887
For me it was under:
/Users/{your username}/Library/Developer/Xcode/DerivedData...
and NOT in /Library/Developer/Xcode/DerivedData...
If you use log without base it uses e
.
From the comment
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
Therefor you have to use:
import math
print( math.log(1.5, 10))
I believe +%s
is seconds since epoch. It's timezone invariant.
An educational example from the stat documentation:
import os, sys
from stat import *
def walktree(top, callback):
'''recursively descend the directory tree rooted at top,
calling the callback function for each regular file'''
for f in os.listdir(top):
pathname = os.path.join(top, f)
mode = os.stat(pathname)[ST_MODE]
if S_ISDIR(mode):
# It's a directory, recurse into it
walktree(pathname, callback)
elif S_ISREG(mode):
# It's a file, call the callback function
callback(pathname)
else:
# Unknown file type, print a message
print 'Skipping %s' % pathname
def visitfile(file):
print 'visiting', file
if __name__ == '__main__':
walktree(sys.argv[1], visitfile)
I'd suggest OOWeb to act as an HTTP server and a templating engine like Velocity to generate HTML. I also second Esko's suggestion of Wicket. Both solutions are considerably simpler than the average setup.
You can use .replace
. For example:
>>> df = pd.DataFrame({'col2': {0: 'a', 1: 2, 2: np.nan}, 'col1': {0: 'w', 1: 1, 2: 2}})
>>> di = {1: "A", 2: "B"}
>>> df
col1 col2
0 w a
1 1 2
2 2 NaN
>>> df.replace({"col1": di})
col1 col2
0 w a
1 A 2
2 B NaN
or directly on the Series
, i.e. df["col1"].replace(di, inplace=True)
.
We can also add checks like this:
function parseData(data) {
if (!data) return {};
if (typeof data === 'object') return data;
if (typeof data === 'string') return JSON.parse(data);
return {};
}
If your skype is open, Quit skype and try,
or
Go to your xampp/wamp installed, search for httpd.conf. Open that file using textpad/notepad, search for Listen or 80 , update listen port to 8081 and save the file. Restart xampp/wamp, start the servers.
or
follow below steps in skype
The Code:
string myString = "Hello " + ((char)34) + " World." + ((char)34);
Output will be:
Hello "World."
I just did some tests of the four options that I know about.
Measure-Command {$(1..1000) | Out-Null}
TotalMilliseconds : 76.211
Measure-Command {[Void]$(1..1000)}
TotalMilliseconds : 0.217
Measure-Command {$(1..1000) > $null}
TotalMilliseconds : 0.2478
Measure-Command {$null = $(1..1000)}
TotalMilliseconds : 0.2122
## Control, times vary from 0.21 to 0.24
Measure-Command {$(1..1000)}
TotalMilliseconds : 0.2141
So I would suggest that you use anything but Out-Null
due to overhead. The next important thing, to me, would be readability. I kind of like redirecting to $null
and setting equal to $null
myself. I use to prefer casting to [Void]
, but that may not be as understandable when glancing at code or for new users.
I guess I slightly prefer redirecting output to $null
.
Do-Something > $null
Edit
After stej's comment again, I decided to do some more tests with pipelines to better isolate the overhead of trashing the output.
Here are some tests with a simple 1000 object pipeline.
## Control Pipeline
Measure-Command {$(1..1000) | ?{$_ -is [int]}}
TotalMilliseconds : 119.3823
## Out-Null
Measure-Command {$(1..1000) | ?{$_ -is [int]} | Out-Null}
TotalMilliseconds : 190.2193
## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}
TotalMilliseconds : 119.7923
In this case, Out-Null
has about a 60% overhead and > $null
has about a 0.3% overhead.
Addendum 2017-10-16: I originally overlooked another option with Out-Null
, the use of the -inputObject
parameter. Using this the overhead seems to disappear, however the syntax is different:
Out-Null -inputObject ($(1..1000) | ?{$_ -is [int]})
And now for some tests with a simple 100 object pipeline.
## Control Pipeline
Measure-Command {$(1..100) | ?{$_ -is [int]}}
TotalMilliseconds : 12.3566
## Out-Null
Measure-Command {$(1..100) | ?{$_ -is [int]} | Out-Null}
TotalMilliseconds : 19.7357
## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}
TotalMilliseconds : 12.8527
Here again Out-Null
has about a 60% overhead. While > $null
has an overhead of about 4%. The numbers here varied a bit from test to test (I ran each about 5 times and picked the middle ground). But I think it shows a clear reason to not use Out-Null
.
In case you don't have Linq, I solved it the following way:
private T[] GetArray<T>(IList<T> iList) where T: new()
{
var result = new T[iList.Count];
iList.CopyTo(result, 0);
return result;
}
Hope it helps
Or you might have something like this (redeclaring a variable):
var data = [];
var data =
r+
is used for reading, and writing mode. b
is for binary.
r+b
mode is open the binary file in read or write mode.
You can read more here.
Be careful, the solution proposed with $a = array_combine($a, $a);
will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384)
to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
You can do it using this class I just made. With this class you can use the Map
object like another dictionary(including json serialization) or with the dot notation. I hope help you:
class Map(dict):
"""
Example:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
"""
def __init__(self, *args, **kwargs):
super(Map, self).__init__(*args, **kwargs)
for arg in args:
if isinstance(arg, dict):
for k, v in arg.iteritems():
self[k] = v
if kwargs:
for k, v in kwargs.iteritems():
self[k] = v
def __getattr__(self, attr):
return self.get(attr)
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __setitem__(self, key, value):
super(Map, self).__setitem__(key, value)
self.__dict__.update({key: value})
def __delattr__(self, item):
self.__delitem__(item)
def __delitem__(self, key):
super(Map, self).__delitem__(key)
del self.__dict__[key]
Usage examples:
m = Map({'first_name': 'Eduardo'}, last_name='Pool', age=24, sports=['Soccer'])
# Add new key
m.new_key = 'Hello world!'
print m.new_key
print m['new_key']
# Update values
m.new_key = 'Yay!'
# Or
m['new_key'] = 'Yay!'
# Delete key
del m.new_key
# Or
del m['new_key']
For MySql WorkBench, Please use below :
update emp as a
inner join department b on a.department_id=b.id
set a.department_name=b.name
where a.emp_id in (10,11,12);
That is because there are different types of objects in Javascript!
For example
stringify(function (){})
-> [object Function]
stringify([])
-> [object Array]
stringify(/x/)
-> [object RegExp]
stringify(new Date)
-> [object Date]
...
stringify({})
-> [object Object]
the constructor function is called Object
(with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
When you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
If you want to see value inside "[Object objects]" use:
console.log(JSON.stringify(result))
You just need this:
$(".hidden").attr("placeholder", "Type here to search");
classList
is used for manipulating classes and not attributes.
Format, days, months and year:
var regex = /^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d$/;
Not with a regular statement, no.
What you can do is wrap the functionality in a PL/pgsql function (or another language, but PL/pgsql seems to be the most appropriate for this), and then just call that function. That means it'll still be a single statement to your app.
I'd recommend this article on CSS Tricks by Chris Coyier entitled Better Helvetica:
http://css-tricks.com/snippets/css/better-helvetica/
He basically recommends the following declaration for covering all the bases:
body {
font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-weight: 300;
}
I'd go for purchase-rest-service
. Reasons:
What is "pur chase rests ervice"? Long, concatenated words are hard to understand. I know, I'm German. "Donaudampfschifffahrtskapitänspatentausfüllungsassistentenausschreibungsstellenbewerbung."
"_" is harder to type than "-"
Use std::string::find
as follows:
if (s1.find(s2) != std::string::npos) {
std::cout << "found!" << '\n';
}
Note: "found!" will be printed if s2
is a substring of s1
, both s1
and s2
are of type std::string
.
Surrounding the path and the argument with spaces inside quotes as in your example should do. The command may need to handle the quotes when the parameters are passed to it, but it usually is not a big deal.
If you want the Oracle JDK and are willing not to use yum/rpm, see this answer here:
Downloading Java JDK on Linux via wget is shown license page instead
As per that post, you can automate the download of the tarball using curl and specifying a cookie header.
Then you can put the tarball contents in the right place and add java to your PATH, for example:
curl -v -j -k -L -H "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u45-b14/jdk-8u45-linux-x64.tar.gz > jdk.tar.gz
tar xzvf jdk.tar.gz
sudo mkdir /usr/local/java
sudo mv jdk1.8.0_45 /usr/local/java/
sudo ln -s /usr/local/java/jdk1.8.0_45 /usr/local/java/jdk
sudo vi /etc/profile.d/java.sh
export PATH="$PATH:/usr/local/java/jdk/bin"
export JAVA_HOME=/usr/local/java/jdk
source /etc/profile.d/java.sh
There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL
SQL> ed
Wrote file afiedt.buf
1 with x as (
2 select '1,2,3,a,b,c,d' str from dual
3 )
4 select regexp_substr(str,'[^,]+',1,level) element
5 from x
6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /
ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d
7 rows selected.
Or in PL/SQL
SQL> create type str_tbl is table of varchar2(100);
2 /
Type created.
SQL> create or replace function parse_list( p_list in varchar2 )
2 return str_tbl
3 pipelined
4 is
5 begin
6 for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
7 from dual
8 connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
9 loop
10 pipe row( x.element );
11 end loop
12 return;
13 end;
14
15 /
Function created.
SQL> select *
2 from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));
COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f
9 rows selected.
As of Laravel v7.X, the framework now comes with a minimal API wrapped around the Guzzle HTTP client. It provides an easy way to make get, post, put, patch, and delete requests using the HTTP Client:
use Illuminate\Support\Facades\Http;
$response = Http::get('http://test.com');
$response = Http::post('http://test.com');
$response = Http::put('http://test.com');
$response = Http::patch('http://test.com');
$response = Http::delete('http://test.com');
You can manage responses using the set of methods provided by the Illuminate\Http\Client\Response
instance returned.
$response->body() : string;
$response->json() : array;
$response->status() : int;
$response->ok() : bool;
$response->successful() : bool;
$response->serverError() : bool;
$response->clientError() : bool;
$response->header($header) : string;
$response->headers() : array;
Please note that you will, of course, need to install Guzzle like so:
composer require guzzlehttp/guzzle
There are a lot more helpful features built-in and you can find out more about these set of the feature here: https://laravel.com/docs/7.x/http-client
This is definitely now the easiest way to make external API calls within Laravel.
Set the width of the <td>
s to 50px
and then add your <td>
+ another fake <td>
table tr td:empty {_x000D_
width: 50px;_x000D_
}_x000D_
_x000D_
table tr td {_x000D_
padding-top: 10px;_x000D_
padding-bottom: 10px;_x000D_
}
_x000D_
<table>_x000D_
<tr>_x000D_
<td>First Column</td>_x000D_
<td></td>_x000D_
<td>Second Column</td>_x000D_
<td></td>_x000D_
<td>Third Column</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Code Explained:
The first CSS rule checks for empty td's and give them a width of 50px then the second rule give the padding of top and bottom to all the td's.
i just switched positions and worked for me (showing only mobile )
<style>_x000D_
.MobileContent {_x000D_
_x000D_
display: none;_x000D_
text-align:center;_x000D_
_x000D_
}_x000D_
_x000D_
@media screen and (max-width: 768px) {_x000D_
_x000D_
.MobileContent {_x000D_
_x000D_
display:block;_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
</style>_x000D_
<div class="MobileContent"> Something </div>
_x000D_
This Worked for me
In Web.config add below script
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
<remove name="WebDAVModule"/>
</modules>
<handlers accessPolicy="Read, Execute, Script">
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*."
verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
_x000D_
Also in RouteConfig.cs
Change
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
Hope it helps you or some one :)
string[] parts = myString.Split(" ");
string whatIWant = parts[0] + " "+ parts[1];
I wanted to add my experience on that. Indeed EF, when you add an object to the context, it changes the state of all the children and related entities to Added. Although there is a small exception in the rule here: if the children/related entities are being tracked by the same context, EF does understand that these entities exist and doesn't add them. The problem happens when for example, you load the children/related entities from some other context or a web ui etc and then yes, EF doesn't know anything about these entities and goes and adds all of them. To avoid that, just get the keys of the entities and find them (e.g. context.Students.FirstOrDefault(s => s.Name == "Alice"))
in the same context in which you want to do the addition.
PostgreSQL Forging Key DELETE, UPDATE CASCADE
CREATE TABLE apps_user(
user_id SERIAL PRIMARY KEY,
username character varying(30),
userpass character varying(50),
created_on DATE
);
CREATE TABLE apps_profile(
pro_id SERIAL PRIMARY KEY,
user_id INT4 REFERENCES apps_user(user_id) ON DELETE CASCADE ON UPDATE CASCADE,
firstname VARCHAR(30),
lastname VARCHAR(50),
email VARCHAR UNIQUE,
dob DATE
);
My favourite of the below is var_dump
, which when called as:
var_dump("%d", count);
produces output like:
patch.c:150:main(): count = 0
Credit to @"Jonathan Leffler". All are C89-happy:
Code
#define DEBUG 1
#include <stdarg.h>
#include <stdio.h>
void debug_vprintf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
}
/* Call as: (DOUBLE PARENTHESES ARE MANDATORY) */
/* var_debug(("outfd = %d, somefailed = %d\n", outfd, somefailed)); */
#define var_debug(x) do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): ", \
__FILE__, __LINE__, __func__); debug_vprintf x; }} while (0)
/* var_dump("%s" variable_name); */
#define var_dump(fmt, var) do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): ", \
__FILE__, __LINE__, __func__); debug_vprintf ("%s = " fmt, #var, var); }} while (0)
#define DEBUG_HERE do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): HERE\n", \
__FILE__, __LINE__, __func__); }} while (0)
//Runs function after x seconds
public static func runThisAfterDelay(seconds: Double, after: @escaping () -> Void) {
runThisAfterDelay(seconds: seconds, queue: DispatchQueue.main, after: after)
}
public static func runThisAfterDelay(seconds: Double, queue: DispatchQueue, after: @escaping () -> Void) {
let time = DispatchTime.now() + Double(Int64(seconds * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
queue.asyncAfter(deadline: time, execute: after)
}
//Use:-
runThisAfterDelay(seconds: x){
//write your code here
}
I have the solution to this problem enters (Start -> Run -> services.msc) are looking for the postgresql service once you localizas le das Properties---> login and you disable the account you have and what you leave as the local system account , save and restart the programs pgadmin3 and ready should operate.
Greeting from Colombia
Below i describe my method. I set event on input in input
, to call Masking() method, which will return an formatted string of that we insert in input
.
Html:
<input name="phone" pattern="+373 __ ___ ___" class="masked" required>
JQ: Here we set event on input:
$('.masked').on('input', function () {
var input = $(this);
input.val(Masking(input.val(), input.attr('pattern')));
});
JS: Function, which will format string by pattern;
function Masking (value, pattern) {
var out = '';
var space = ' ';
var any = '_';
for (var i = 0, j = 0; j < value.length; i++, j++) {
if (value[j] === pattern[i]) {
out += value[j];
}
else if(pattern[i] === any && value[j] !== space) {
out += value[j];
}
else if(pattern[i] === space && value[j] !== space) {
out += space;
j--;
}
else if(pattern[i] !== any && pattern[i] !== space) {
out += pattern[i];
j--;
}
}
return out;
}
While compiling in RHEL 6.2 (x86_64), I installed both 32bit and 64bit libstdc++-dev packages, but I had the "c++config.h no such file or directory" problem.
Resolution:
The directory /usr/include/c++/4.4.6/x86_64-redhat-linux
was missing.
I did the following:
cd /usr/include/c++/4.4.6/
mkdir x86_64-redhat-linux
cd x86_64-redhat-linux
ln -s ../i686-redhat-linux 32
I'm now able to compile 32bit binaries on a 64bit OS.
Are you looking for the SQL used to generate a table? For that, you can query the sqlite_master
table:
sqlite> CREATE TABLE foo (bar INT, quux TEXT);
sqlite> SELECT * FROM sqlite_master;
table|foo|foo|2|CREATE TABLE foo (bar INT, quux TEXT)
sqlite> SELECT sql FROM sqlite_master WHERE name = 'foo';
CREATE TABLE foo (bar INT, quux TEXT)
You could do this:
SELECT * FROM table WHERE cast(YOUR_INTEGER_VALUE as varchar) = 'string of numbers'
Null
refers to an absence of data. Null
is formally defined as a value that is unavailable, unassigned, unknown or inapplicable (OCA Oracle Database 12c, SQL Fundamentals I Exam Guide, p87).
So, you may not see records with columns containing null values when said columns are restricted using an "in" or "not in" clauses.
You could take the average buffer gets per execution during a period of activity of the instance:
SELECT username,
buffer_gets,
disk_reads,
executions,
buffer_get_per_exec,
parse_calls,
sorts,
rows_processed,
hit_ratio,
module,
sql_text
-- elapsed_time, cpu_time, user_io_wait_time, ,
FROM (SELECT sql_text,
b.username,
a.disk_reads,
a.buffer_gets,
trunc(a.buffer_gets / a.executions) buffer_get_per_exec,
a.parse_calls,
a.sorts,
a.executions,
a.rows_processed,
100 - ROUND (100 * a.disk_reads / a.buffer_gets, 2) hit_ratio,
module
-- cpu_time, elapsed_time, user_io_wait_time
FROM v$sqlarea a, dba_users b
WHERE a.parsing_user_id = b.user_id
AND b.username NOT IN ('SYS', 'SYSTEM', 'RMAN','SYSMAN')
AND a.buffer_gets > 10000
ORDER BY buffer_get_per_exec DESC)
WHERE ROWNUM <= 20
Instead of passing functions or querying it on the controller, I think what you need is relationships on models since these are related tables on your database.
If based on your structure, input_details and products are related you should put relationship definition on your models like this:
public class InputDetail(){
protected $table = "input_details";
....//other code
public function product(){
return $this->hasOne('App\Product');
}
}
then in your view you'll just have to say:
<p>{{ $input_details->product->name }}</p>
More simpler that way. It is also the best practice that controllers should only do business logic for the current resource. For more info on how to do this just go to the docs: https://laravel.com/docs/5.0/eloquent#relationships
The file permissions on my virtual environment directory and my project directory were not correct and, thus, would not allow me to install the proper packages. I upadated them by running:
sudo chown user:user -R [project folder]
sudo chown user:user -R [environment folder]
In the above your should use your own usernames in place of "user". The -R recurses through all subfolders and files.
Although you cannot use import
without running the code; there is quite a swift way in which you can input your variables; by using numpy.savez
, which stores variables as numpy arrays in a .npz file. Afterwards you can load the variables using numpy.load
.
See a full description in the scipy documentation
Please note this is only the case for variables and arrays of variable, and not for methods, etc.
Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.
Surely have a mutex-wrapped variable initialised to false
, that the thread sets to true
as the last thing it does before exiting. Is that atomic enough for your needs?
By default node package is nodejs, so use
$ nodejs -v
or
$ nodejs --version
You can make a link using
$ sudo ln -s /usr/bin/nodejs /usr/bin/node
then u can use
$ node --version
or
$ node -v
With the latest release of Bootstrap RC 3, changing the color of the icons is as simple as adding a class with the color you want and adding it to the span.
Default black color:
<h1>Password Changed <span class="glyphicon glyphicon-ok"></span></h1>
would become
<h1>Password Changed <span class="glyphicon glyphicon-ok icon-success"></span></h1>
CSS
.icon-success {
color: #5CB85C;
}
I think this is what you want:
/grand/parent/child[@id="#grand"]
It only seems to because that is what it is printing out. But actually, you shouldn't write the logic this way. This is equivalent:
insert into errortable (dateupdated, table1id)
values (sysdate, 1083);
It seems silly to convert the system date to a string just to convert it back to a date.
If you want to see the full date, then you can do:
select TO_CHAR(dateupdated, 'YYYY-MM-DD HH24:MI:SS'), table1id
from errortable;
Are you getting errors, or just not sure where to start?
%pylab inline
import pandas as pd
import matplotlib.pyplot as plt
df2 = df.groupby(['Name', 'Abuse/NFF'])['Name'].count().unstack('Abuse/NFF').fillna(0)
df2[['abuse','nff']].plot(kind='bar', stacked=True)
I know this is old, but I ran into the same issue. I'm on a Mac/Ubuntu and switch back and forth. What I have found is that just sending a simple interrupt signal to the main R process does exactly what you're looking for. I've ran scripts that went on for as long as 24 hours and the signal interrupt works very well. You should be able to run kill in terminal:
$ kill -2 pid
You can find the pid by running
$ps aux | grep exec/R
Not sure about Windows since I'm not ever on there, but I can't imagine there's not an option to do this as well in Command Prompt/Task Manager
Hope this helps!
Another working solution for IE specific styling is
<html data-useragent="Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)">
And then your selector
html[data-useragent*='MSIE 10.0'] body .my-class{
margin-left: -0.4em;
}
The Value of num will be some garbage value from the main memory(RAM). its better if you initialize the variable just after creating.
If you don't want to create a custom Toolbar
, you can do like this
public class GalleryActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
...
getSupportActionBar().setTitle("Select Image");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
In you AndroidManifest.xml
<activity
android:name=".GalleryActivity"
android:theme="@style/Theme.AppCompat.Light">
</activity>
you can also put this android:theme="@style/Theme.AppCompat.Light"
to <aplication>
tag, for apply to all activities
Likely quite simple but best way is to edit manually the file .classpath at the root of your project folder with something like
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
<attribute name="org.eclipse.jst.component.dependency" value="/WEB-INF/lib"/>
</attributes>
</classpathentry>
when you want to have jar in your WEB-IN/lib folder (case for a web app)
If the language isn't a problem (any sandboxed scripted one) then there's LUA for .NET. The Silverlight version of the .NET framework is also sandboxed afaik.
process.env is a reference to your environment, so you have to set the variable there.
To set an environment variable in Windows:
SET NODE_ENV=development
on OS X or Linux:
export NODE_ENV=development
Simple way to differentiate UTF-8 and UTF-16 is to identify commonalities between them.
Other than sharing same unicode number for given character, each one is their own format.
UTF-8 try to represent, every unicode number given to character with one byte(If it is ASCII), else 2 two bytes, else 4 bytes and so on...
UTF-16 try to represent, every unicode number given to character with two byte to start with. If two bytes are not sufficient, then uses 4 bytes. IF that is also not sufficient, then uses 6 bytes.
Theoretically, UTF-16 is more space efficient, but in practical UTF-8 is more space efficient as most of the characters(98% of data) for processing are ASCII and UTF-8 try to represent them with single byte and UTF-16 try to represent them with 2 bytes.
Also, UTF-8 is superset of ASCII encoding. So every app that expects ASCII data would also accepted by UTF-8 processor. This is not true for UTF-16. UTF-16 could not understand ASCII, and this is big hurdle for UTF-16 adoption.
Another point to note is, all UNICODE as of now could be fit in 4 bytes of UTF-8 maximum(Considering all languages of world). This is same as UTF-16 and no real saving in space compared to UTF-8 ( https://stackoverflow.com/a/8505038/3343801 )
So, people use UTF-8 where ever possible.
Not true for the OP, but this error can be caused by using single quotation marks ('
) instead of double ("
) for strings.
The JSON spec requires double quotation marks for strings.
E.g:
JSON.parse(`{"myparam": 'myString'}`)
gives the error, whereas
JSON.parse(`{"myparam": "myString"}`)
does not. Note the quotation marks around myString
.
For copying data from source to destination:
use <DestinationDatabase>
select * into <DestinationTable> from <SourceDataBase>.dbo.<SourceTable>
If you're using Python 3.3 or above, I'd recommend the built-in get_terminal_size()
as already recommended. However if you are stuck with an older version and want a simple, cross-platform way of doing this, you could use asciimatics. This package supports versions of Python back to 2.7 and uses similar options to those suggested above to get the current terminal/console size.
Simply construct your Screen
class and use the dimensions
property to get the height and width. This has been proven to work on Linux, OSX and Windows.
Oh - and full disclosure here: I am the author, so please feel free to open a new issue if you have any problems getting this to work.
As to the CSS suggestion:
#myCanvas {
width: 100%;
height: 100%;
}
By the standard, CSS does not size the canvas coordinate system, it scales the content. In Chrome, the CSS mentioned will scale the canvas up or down to fit the browser's layout. In the typical case where the coordinate system is smaller than the browser's dimensions in pixels, this effectively lowers the resolution of your drawing. It most likely results in non-proportional drawing as well.
For multiple lines
xposition = [0.3, 0.4, 0.45]
for xc in xposition:
plt.axvline(x=xc, color='k', linestyle='--')
The only thing about using telnet to test postfix, or other SMTP, is that you have to know the commands and syntax. Instead, just use swaks :)
thufir@dur:~$
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 4 messages
> 1 [email protected] 15/553 test Mon, 30 Dec 2013 10:15:12 -0800
2 [email protected] 15/581 test Mon, 30 Dec 2013 10:15:55 -0800
3 [email protected] 15/581 test Mon, 30 Dec 2013 10:29:57 -0800
4 [email protected] 15/581 test Mon, 30 Dec 2013 11:54:16 -0800
? q
Held 4 messages in /home/thufir/Maildir
thufir@dur:~$
thufir@dur:~$ swaks --to [email protected]
=== Trying dur.bounceme.net:25...
=== Connected to dur.bounceme.net.
<- 220 dur.bounceme.net ESMTP Postfix (Ubuntu)
-> EHLO dur.bounceme.net
<- 250-dur.bounceme.net
<- 250-PIPELINING
<- 250-SIZE 10240000
<- 250-VRFY
<- 250-ETRN
<- 250-STARTTLS
<- 250-ENHANCEDSTATUSCODES
<- 250-8BITMIME
<- 250 DSN
-> MAIL FROM:<[email protected]>
<- 250 2.1.0 Ok
-> RCPT TO:<[email protected]>
<- 250 2.1.5 Ok
-> DATA
<- 354 End data with <CR><LF>.<CR><LF>
-> Date: Mon, 30 Dec 2013 14:33:17 -0800
-> To: [email protected]
-> From: [email protected]
-> Subject: test Mon, 30 Dec 2013 14:33:17 -0800
-> X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
->
-> This is a test mailing
->
-> .
<- 250 2.0.0 Ok: queued as 52D162C3EFF
-> QUIT
<- 221 2.0.0 Bye
=== Connection closed with remote host.
thufir@dur:~$
thufir@dur:~$ mail -f Maildir
"/home/thufir/Maildir": 5 messages 1 new
1 [email protected] 15/553 test Mon, 30 Dec 2013 10:15:12 -0800
2 [email protected] 15/581 test Mon, 30 Dec 2013 10:15:55 -0800
3 [email protected] 15/581 test Mon, 30 Dec 2013 10:29:57 -0800
4 [email protected] 15/581 test Mon, 30 Dec 2013 11:54:16 -0800
>N 5 [email protected] 15/581 test Mon, 30 Dec 2013 14:33:17 -0800
? 5
Return-Path: <[email protected]>
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from dur.bounceme.net (localhost [127.0.0.1])
by dur.bounceme.net (Postfix) with ESMTP id 52D162C3EFF
for <[email protected]>; Mon, 30 Dec 2013 14:33:17 -0800 (PST)
Date: Mon, 30 Dec 2013 14:33:17 -0800
To: [email protected]
From: [email protected]
Subject: test Mon, 30 Dec 2013 14:33:17 -0800
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Message-Id: <[email protected]>
This is a test mailing
New mail has arrived.
? q
Held 5 messages in /home/thufir/Maildir
thufir@dur:~$
It's just one easy command.
I faced the same problem but When I changed the skin of AVD device to HVGA, it worked.
I use the following snippet to view all the rows in a table. Use a query to find all the rows. The returned objects are the class instances. They can be used to view/edit the values as required:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine, Sequence
from sqlalchemy import String, Integer, Float, Boolean, Column
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class MyTable(Base):
__tablename__ = 'MyTable'
id = Column(Integer, Sequence('user_id_seq'), primary_key=True)
some_col = Column(String(500))
def __init__(self, some_col):
self.some_col = some_col
engine = create_engine('sqlite:///sqllight.db', echo=True)
Session = sessionmaker(bind=engine)
session = Session()
for class_instance in session.query(MyTable).all():
print(vars(class_instance))
session.close()
There's also xmlstarlet (which is available for Windows as well).
Go the Project's Properties -> Linker-> System -> SubSystem
, then set it to Console(/S)
.
Just read this great .Net DI container comparison blog by Philip Mat.
He does some thorough performance comparison tests on;
He recommends Autofac as it is small, fast, and easy to use ... I agree. It appears that Unity and Ninject are the slowest in his tests.
According to Microsoft
(DLL) Dynamic link libraries are files that contain data, code, or resources needed for the running of applications. These are files that are created by the windows ecosystem and can be shared between two or more applications.
When a program or software runs on Windows, much of how the application works depends on the DLL files of the program. For instance, if a particular application had several modules, then how each module interacts with each other is determined by the Windows DLL files.
If you want detailed explanation, check these useful resources
Try setting the system default encoding as utf-8
at the start of the script, so that all strings are encoded using that.
Example -
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
The above should set the default encoding as utf-8
.
You can use Google Chrome Extension: JSONView
All formatted json result will be displayed directly on the browser.
require_once('db/connect.php');
//rand(1000000 , 9999999);
$products_query = "SELECT id FROM products";
$products_result = mysqli_query($conn, $products_query);
$products_row = mysqli_fetch_array($products_result);
$ids_array = [];
do
{
array_push($ids_array, $products_row['id']);
}
while($products_row = mysqli_fetch_array($products_result));
/*
echo '<pre>';
print_r($ids_array);
echo '</pre>';
*/
$row_counter = count($ids_array);
for ($i=0; $i < $row_counter; $i++)
{
$current_row = $ids_array[$i];
$rand = rand(1000000 , 9999999);
mysqli_query($conn , "UPDATE products SET code='$rand' WHERE id='$current_row'");
}
this fails:
DECLARE @vPortalUID NVARCHAR(32)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS uniqueidentifier)
PRINT @nPortalUID
this works
DECLARE @vPortalUID NVARCHAR(36)
SET @vPortalUID='2A66057D-F4E5-4E2B-B2F1-38C51A96D385'
DECLARE @nPortalUID AS UNIQUEIDENTIFIER
SET @nPortalUID = CAST(@vPortalUID AS UNIQUEIDENTIFIER)
PRINT @nPortalUID
the difference is NVARCHAR(36)
, your input parameter is too small!
updated based on Xbello
comment:
string = my_string.rstrip('\r\n')
read more here
Make sure that the "Filter" input is left blank and nothing is written intentionally or by mistake. That was it in my case :P
Prior to C++11, there was no portable way to do this.
A portable way is to use Boost or Ace library.
There is ACE_OS::sleep();
in ACE.
Most of these answers are essentially the same. Mine is also, but this is the form I like
boolean completed = false;
Throwable lastException = null;
for (int tryCount=0; tryCount < config.MAX_SOME_OPERATION_RETRIES; tryCount++)
{
try {
completed = some_operation();
break;
}
catch (UnlikelyException e) {
lastException = e;
fix_the_problem();
}
}
if (!completed) {
reportError(lastException);
}
Would have left this as a comment but I need more rep, anyways I just wanted to mention to Nicholas Peterson that perhaps passing the second argument to the Redirect call to tell it to end the response would have worked. Not the most graceful way to handle this but it does in fact work.
So
filterContext.RequestContext.HttpContext.Response.Redirect("/Login", true);
instead of
filterContext.RequestContext.HttpContext.Response.Redirect("/Login);
So you'd have this in your controller:
protected override void OnAuthorization(AuthorizationContext filterContext)
{
if(!User.IsInRole("Admin")
{
base.OnAuthorization(filterContext);
filterContext.RequestContext.HttpContext.Response.Redirect("/Login", true);
}
}
Found a solution that works for me looking here (see the third comment on the first answer). This code looks for a valid twitter client and uses it to post the tweet. Note: It does not give you an Intent with the various Twitter clients and allow you to choose.
Share using twitter:
Intent shareIntent = findTwitterClient();
shareIntent.putExtra(Intent.EXTRA_TEXT, "test");
startActivity(Intent.createChooser(shareIntent, "Share"));
Calling this method:
public Intent findTwitterClient() {
final String[] twitterApps = {
// package // name - nb installs (thousands)
"com.twitter.android", // official - 10 000
"com.twidroid", // twidroid - 5 000
"com.handmark.tweetcaster", // Tweecaster - 5 000
"com.thedeck.android" }; // TweetDeck - 5 000 };
Intent tweetIntent = new Intent();
tweetIntent.setType("text/plain");
final PackageManager packageManager = getPackageManager();
List<ResolveInfo> list = packageManager.queryIntentActivities(
tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (int i = 0; i < twitterApps.length; i++) {
for (ResolveInfo resolveInfo : list) {
String p = resolveInfo.activityInfo.packageName;
if (p != null && p.startsWith(twitterApps[i])) {
tweetIntent.setPackage(p);
return tweetIntent;
}
}
}
return null;
}
Facebook will be similar using "com.facebook.katana", although you still can't set the message text (deprecated July 2011).
Code source: Intent to open twitter client on Android
When I needed to create similar dots in input[password] I use a custom font in base64 (with 2 glyphs see above 25CF and 2022)
SCSS styles
@font-face {
font-family: 'pass';
font-style: normal;
font-weight: 400;
src: url(data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAAATsAA8AAAAAB2QAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABWAAAABwAAAAcg9+z70dERUYAAAF0AAAAHAAAAB4AJwANT1MvMgAAAZAAAAA/AAAAYH7AkBhjbWFwAAAB0AAAAFkAAAFqZowMx2N2dCAAAAIsAAAABAAAAAQAIgKIZ2FzcAAAAjAAAAAIAAAACAAAABBnbHlmAAACOAAAALkAAAE0MwNYJ2hlYWQAAAL0AAAAMAAAADYPA2KgaGhlYQAAAyQAAAAeAAAAJAU+ATJobXR4AAADRAAAABwAAAAcCPoA6mxvY2EAAANgAAAAEAAAABAA5gFMbWF4cAAAA3AAAAAaAAAAIAAKAE9uYW1lAAADjAAAARYAAAIgB4hZ03Bvc3QAAASkAAAAPgAAAE5Ojr8ld2ViZgAABOQAAAAGAAAABuK7WtIAAAABAAAAANXulPUAAAAA1viLwQAAAADW+JM4eNpjYGRgYOABYjEgZmJgBEI2IGYB8xgAA+AANXjaY2BifMg4gYGVgYVBAwOeYEAFjMgcp8yiFAYHBl7VP8wx/94wpDDHMIoo2DP8B8kx2TLHACkFBkYA8/IL3QB42mNgYGBmgGAZBkYGEEgB8hjBfBYGDyDNx8DBwMTABmTxMigoKKmeV/3z/z9YJTKf8f/X/4/vP7pldosLag4SYATqhgkyMgEJJnQFECcMOGChndEAfOwRuAAAAAAiAogAAQAB//8AD3jaY2BiUGJgYDRiWsXAzMDOoLeRkUHfZhM7C8Nbo41srHdsNjEzAZkMG5lBwqwg4U3sbIx/bDYxgsSNBRUF1Y0FlZUYBd6dOcO06m+YElMa0DiGJIZUxjuM9xjkGRhU2djZlJXU1UDQ1MTcDASNjcTFQFBUBGjYEkkVMJCU4gcCKRTeHCk+fn4+KSllsJiUJEhMUgrMUQbZk8bgz/iA8SRR9qzAY087FjEYD2QPDDAzMFgyAwC39TCRAAAAeNpjYGRgYADid/fqneL5bb4yyLMwgMC1H90HIfRkCxDN+IBpFZDiYGAC8QBbSwuceNpjYGRgYI7594aBgcmOAQgYHzAwMqACdgBbWQN0AAABdgAiAAAAAAAAAAABFAAAAj4AYgI+AGYB9AAAAAAAKgAqACoAKgBeAJIAmnjaY2BkYGBgZ1BgYGIAAUYGBNADEQAFQQBaAAB42o2PwUrDQBCGvzVV9GAQDx485exBY1CU3PQgVgIFI9prlVqDwcZNC/oSPoKP4HNUfQLfxYN/NytCe5GwO9/88+/MBAh5I8C0VoAtnYYNa8oaXpAn9RxIP/XcIqLreZENnjwvyfPieVVdXj2H7DHxPJH/2/M7sVn3/MGyOfb8SWjOGv4K2DRdctpkmtqhos+D6ISh4kiUUXDj1Fr3Bc/Oc0vPqec6A8aUyu1cdTaPZvyXyqz6Fm5axC7bxHOv/r/dnbSRXCk7+mpVrOqVtFqdp3NKxaHUgeod9cm40rtrzfrt2OyQa8fppCO9tk7d1x0rpiQcuDuRkjjtkHt16ctbuf/radZY52/PnEcphXpZOcofiEZNcQAAeNpjYGIAg///GBgZsAF2BgZGJkZmBmaGdkYWRla29JzKggxD9tK8TAMDAxc2D0MLU2NjENfI1M0ZACUXCrsAAAABWtLiugAA) format('woff');
}
input.password {
font-family: 'pass', 'Roboto', Helvetica, Arial, sans-serif ;
font-size: 18px;
&::-webkit-input-placeholder {
transform: scale(0.77);
transform-origin: 0 50%;
}
&::-moz-placeholder {
font-size: 14px;
opacity: 1;
}
&:-ms-input-placeholder {
font-size: 14px;
font-family: 'Roboto', Helvetica, Arial, sans-serif;
}
After that, I got identical display input[password]
If you explicitly setPreferredSize(new Dimension(X, Y));
then it is better to use:
setLocation(dim.width/2-this.getPreferredSize().width/2, dim.height/2-this.getPreferredSize().height/2);
You can use as below,
Select X.a, X.b, Y.c from (
Select X.a as a, sum (b) as sum_b from name_table X
group by X.a)X
left join from name_table Y on Y.a = X.a
Example;
CREATE TABLE #products (
product_name VARCHAR(MAX),
code varchar(3),
list_price [numeric](8, 2) NOT NULL
);
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
INSERT INTO #products VALUES ('Dinding', 'ADE', 2000)
INSERT INTO #products VALUES ('Kaca', 'AKB', 2000)
INSERT INTO #products VALUES ('paku', 'ACE', 2000)
--SELECT * FROM #products
SELECT distinct x.code, x.SUM_PRICE, product_name FROM (SELECT code, SUM(list_price) as SUM_PRICE From #products
group by code)x
left join #products y on y.code=x.code
DROP TABLE #products
@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.
For that we have provide one setter method for myobj and set the myobj value with mocked object.
class MyClass {
MyInterface myObj;
public void abc() {
myObj.myMethodToBeVerified (new String("a"), new String("b"));
}
public void setMyObj(MyInterface obj)
{
this.myObj=obj;
}
}
In our Test class, we have to write below code
class MyClassTest {
MyClass myClass = new MyClass();
@Mock
MyInterface myInterface;
@test
testAbc() {
myclass.setMyObj(myInterface); //it is good to have in @before method
myClass.abc();
verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
}
}
select email, count(*) as c FROM orders GROUP BY email
Very simple code example:
If (object1 instanceof Class1) {
// do something
} else if (object1 instanceof Class2) {
// do something different
}
Be careful here. In the example above, if Class1 is Object, the first comparison will always be true. So, just like with exceptions, hierarchical order matters!
chmod +x foo.sh
#!/bin/sh
or some such.sudo pwd
f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
result.append(x.split(' ')[1])
f.close()
You can do the same using a list comprehension
print([x.split(' ')[1] for x in open(file).readlines()])
Docs on split()
string.split(s[, sep[, maxsplit]])
Return a list of the words of the string
s
. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string.
So, you can omit the space I used and do just x.split()
but this will also remove tabs and newlines, be aware of that.
As a quick-dirty-smart-simple workaround:
For UILabels that don't have much lines you can instead use stackViews.
Spacing
of the StackView to your desired amountBe sure to stack them vertically. This solution also works for custom fonts.
I use an interface and create an anonymous instance of it like so:
AppEntryPoint.java
public interface AppEntryPoint
{
public void entryMethod();
}
Main.java
public class Main
{
public static AppEntryPoint entryPoint;
public static void main(String[] args)
{
entryPoint = new AppEntryPoint()
{
//You now have an environment to run your app from
@Override
public void entryMethod()
{
//Do something...
System.out.println("Hello World!");
}
}
entryPoint.entryMethod();
}
public static AppEntryPoint getApplicationEntryPoint()
{
return entryPoint;
}
}
Not as elegant as creating an instance of that class and calling its own method, but accomplishes the same thing, essentially. Just another way to do it.
// Collect this information on every request
$aip = $_SERVER['REMOTE_ADDR'];
$bip = $_SERVER['HTTP_X_FORWARDED_FOR'];
$agent = $_SERVER['HTTP_USER_AGENT'];
session_start();
// Do this each time the user successfully logs in.
$_SESSION['ident'] = hash("sha256", $aip . $bip . $agent);
// Do this every time the client makes a request to the server, after authenticating
$ident = hash("sha256", $aip . $bip . $agent);
if ($ident != $_SESSION['ident'])
{
end_session();
header("Location: login.php");
// add some fancy pants GET/POST var headers for login.php, that lets you
// know in the login page to notify the user of why they're being challenged
// for login again, etc.
}
What this does is capture 'contextual' information about the user's session, pieces of information which should not change during the life of a single session. A user isn't going to be at a computer in the US and in China at the same time, right? So if the IP address changes suddenly within the same session that strongly implies a session hijacking attempt, so you secure the session by ending the session and forcing the user to re-authenticate. This thwarts the hack attempt, the attacker is also forced to login instead of gaining access to the session. Notify the user of the attempt (ajax it up a bit), and vola, Slightly annoyed+informed user and their session/information is protected.
We throw in User Agent and X-FORWARDED-FOR to do our best to capture uniqueness of a session for systems behind proxies/networks. You may be able to use more information then that, feel free to be creative.
It's not 100%, but it's pretty damn effective.
There's more you can do to protect sessions, expire them, when a user leaves a website and comes back force them to login again maybe. You can detect a user leaving and coming back by capturing a blank HTTP_REFERER (domain was typed in the URL bar), or check if the value in the HTTP_REFERER equals your domain or not (the user clicked an external/crafted link to get to your site).
Expire sessions, don't let them remain valid indefinitely.
Don't rely on cookies, they can be stolen, it's one of the vectors of attack for session hijacking.
If you want the object_name prefixed to any ID you should call form helpers on the form object:
- form_for(@message) do |f|
= f.label :email
This also makes sure any submitted data is stored in memory should there be any validation errors etc.
If you can't call the form helper method on the form object, for example if you're using a tag helper (radio_button_tag etc.) you can interpolate the name using:
= radio_button_tag "#{f.object_name}[email]", @message.email
In this case you'd need to specify the value manually to preserve any submissions.
The simplest explanation I can think of is that monads are a way of composing functions with embelished results (aka Kleisli composition). An "embelished" function has the signature a -> (b, smth)
where a
and b
are types (think Int
, Bool
) that might be different from each other, but not necessarily - and smth
is the "context" or the "embelishment".
This type of functions can also be written a -> m b
where m
is equivalent to the "embelishment" smth
. So these are functions that return values in context (think functions that log their actions, where smth
is the logging message; or functions that perform input\output and their results depends on the result of the IO action).
A monad is an interface ("typeclass") that makes the implementer tell it how to compose such functions. The implementer needs to define a composition function (a -> m b) -> (b -> m c) -> (a -> m c)
for any type m
that wants to implement the interface (this is the Kleisli composition).
So, if we say that we have a tuple type (Int, String)
representing results of computations on Int
s that also log their actions, with (_, String)
being the "embelishment" - the log of the action - and two functions increment :: Int -> (Int, String)
and twoTimes :: Int -> (Int, String)
we want to obtain a function incrementThenDouble :: Int -> (Int, String)
which is the composition of the two functions that also takes into account the logs.
On the given example, a monad implementation of the two functions applies to integer value 2 incrementThenDouble 2
(which is equal to twoTimes (increment 2)
) would return (6, " Adding 1. Doubling 3.")
for intermediary results increment 2
equal to (3, " Adding 1.")
and twoTimes 3
equal to (6, " Doubling 3.")
From this Kleisli composition function one can derive the usual monadic functions.
select @@version
Sample Output
Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64) Mar 29 2009 10:11:52 Copyright (c) 1988-2008 Microsoft Corporation Developer Edition (64-bit) on Windows NT 6.1 (Build 7600: )
If you just want to get the edition, you can use:
select serverproperty('Edition')
To use in an automated script, you can get the edition ID, which is an integer:
select serverproperty('EditionID')