maybe this error came because this version
of Sql Server is not installed
connectionString="Data Source=(LocalDB)\v12.0;....
and you don't have to install it
the fastest fix is to change it to any installed version you have
in my case I change it from v12.0
to MSSQLLocalDB
Try this
getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath()
First, check whether the table exists or not. Accordingly, create table if doesn't exist.
var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";
using (SqlCommand command = new SqlCommand(commandStr, con))
command.ExecuteNonQuery();
Read the message:
Only one
<configSections>
element allowed per config file and if present must be the first child of the root<configuration>
element.
Move the configSections element to the top - just above where system.data is currently.
You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?
this.Controls.Add(dataGridView1);
By the way the code is a bit confused
String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql = "SELECT Clients FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
conn.Open();
DataSet ds = new DataSet();
DataGridView dataGridView1 = new DataGridView();
using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
{
adapter.Fill(ds);
dataGridView1.DataSource = ds;
// Of course, before addint the datagrid to the hosting form you need to
// set position, location and other useful properties.
// Why don't you create the DataGrid with the designer and use that instance instead?
this.Controls.Add(dataGridView1);
}
}
EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as
SELECT field_names_list FROM _tablename_
so the correct syntax to use for retrieving all the clients data is
string sql = "SELECT * FROM Clients";
where the *
means -> all the fields present in the table
Ran into this issue. Caused in my case by deleting the .mdf while iispexress was still running and therefor still using the DB. Right click on iisexpress in system tray and click exit THEN delete the MDF to prevent this error from actually occurring.
To fix this error simply within VS right click the App-Data folder add new item > SQL Server Database. Name: [use the database name provided by the update-database error] Click Add.
if (reader.HasRows)
{
while (reader.Read())
{
comboBox1.Items.Add(reader.GetString(0));
}
}
reader.Close();
MySqlDataReader reader1 = cmd1.ExecuteReader();
if (reader1.HasRows)
{
while (reader1.Read())
{
listBox1.Items.Add(reader1.GetString(0));
}
}
reader1.Close();
I have not tested , but what the main idea is: put semicolon on each query.
SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = @"
update table
set somecol = somevalue;
insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;
try
{
connection.Open();
}
finally
{
command.Dispose();
connection.Dispose();
}
Update: you can follow Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too
Application Private Data files are stored within <internal_storage>/data/data/<package>
Files being stored in the internal storage can be accessed with openFileOutput() and openFileInput()
When those files are created as MODE_PRIVATE it is not possible to see/access them within another application such as a FileManager.
To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).
Then I register a pre- or post-build event in Visual Studio...
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"
For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).
I had what appeared to be the same permissions issue on the web.config
file.
However, my problem was caused by IIS failing to load the config file because it contained URL rewrite rules and I hadn't installed the IIS URL rewrite module on the new server.
Solution: Install the rewrite module.
Hope that saves somebody a few hours.
For anyone who came here trying find out how to set connection string dinamicaly, and got trouble with the solutions above (like "Format of the initialization string does not conform to specification starting at index 0.") when setting up the connection string in the constructor. This is how to fix it:
public static string ConnectionString
{
get {
if (ConfigurationManager.AppSettings["DevelopmentEnvironment"] == "true")
return ConfigurationManager.ConnectionStrings["LocalDb"].ConnectionString;
else
return ConfigurationManager.ConnectionStrings["ExternalDb"].ConnectionString;
}
}
public ApplicationDbContext() : base(ConnectionString)
{
}
Craig Stuntz has written an extensive (in my opinion) blog post on troubleshooting this exact error message, I personally would start there.
The following res:
(resource) references need to point to your model.
<add name="Entities" connectionString="metadata=
res://*/Models.WraithNath.co.uk.csdl|
res://*/Models.WraithNath.co.uk.ssdl|
res://*/Models.WraithNath.co.uk.msl;
Make sure each one has the name of your .edmx file after the "*/", with the "edmx" changed to the extension for that res (.csdl, .ssdl, or .msl).
It also may help to specify the assembly rather than using "//*/".
Worst case, you can check everything (a bit slower but should always find the resource) by using
<add name="Entities" connectionString="metadata=
res://*/;provider= <!-- ... -->
To get the path of file in application package;
ContextWrapper c = new ContextWrapper(this);
Toast.makeText(this, c.getFilesDir().getPath(), Toast.LENGTH_LONG).show();
This is common issue only. Even I have faced this issue. On the development machine, configured with Windows authentication, it is worked perfectly:
<add name="ShoppingCartAdminEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQlExpress;initial catalog=ShoppingCartAdmin;Integrated Security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
Once hosted in IIS with the same configuration, I got this error:
The underlying provider failed on Open
It was solved changing connectionString
in the configuration file:
<add name="MyEntities" connectionString="metadata=res://*/ShoppingCartAPIModel.csdl|res://*/ShoppingCartAPIModel.ssdl|res://*/ShoppingCartAPIModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MACHINE_Name\SQlExpress;initial catalog=ShoppingCartAdmin;persist security info=True;user id=sa;password=notmyrealpassword;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
Other common mistakes could be:
You can change configuration file schema back to DotNetConfig.xsd
via properties of the app.config
file. To find destination of needed schema, you can search it by name or create a WinForms application, add to project the configuration file and in it's properties, you'll find full path to file.
Valid from Symfony v2.1 through v4.1+
If you want the base URL to a Symfony application, you should use getSchemeAndHttpHost()
concatenated together with getBaseUrl()
, similar to how getUri()
works, except without the router path and query string.
{{ app.request.schemeAndHttpHost ~ app.request.baseUrl }}
For example, if your Symfony website URL lives at https://www.stackoverflow.com/app1/
, then these two methods return these values:
getSchemeAndHttpHost
https://www.stackoverflow.com
getBaseUrl
/app1
Note: getBaseUrl()
includes the script filename (ie /app.php
) if it's in your URL.
For example you can find any textView:
TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);
If you installed Eclipse have Android SDK, go to DDMS. If the list device display "?????????"
you do adb kill-server
and then adb start-server
.
Please make sure you install USB driver and enable debug mode.
You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common type are:
Type application
application/java-archive
application/EDI-X12
application/EDIFACT
application/javascript
application/octet-stream
application/ogg
application/pdf
application/xhtml+xml
application/x-shockwave-flash
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
Type audio
audio/mpeg
audio/x-ms-wma
audio/vnd.rn-realaudio
audio/x-wav
Type image
image/gif
image/jpeg
image/png
image/tiff
image/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Type multipart
multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Type text
text/css
text/csv
text/html
text/javascript (obsolete)
text/plain
text/xml
Type video
video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
Type vnd :
application/vnd.android.package-archive
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml
Try out this package to tail all the queries (without oplog operations): https://www.npmjs.com/package/mongo-tail-queries
(Disclaimer: I wrote this package exactly for this need)
You can just call the Execute command.
EXEC spDoSomthing @myDate
Edit:
Since you want to return data..that's a little harder. You can use user defined functions instead that return data.
yum install python-devel
will work.
If yum
doesn't work then use
apt-get install python-dev
There already exists a function for this:
from operator import itemgetter
my_dict = {x: x**2 for x in range(10)}
itemgetter(1, 3, 2, 5)(my_dict)
#>>> (1, 9, 4, 25)
itemgetter
will return a tuple if more than one argument is passed. To pass a list to itemgetter
, use
itemgetter(*wanted_keys)(my_dict)
Keep in mind that itemgetter
does not wrap its output in a tuple when only one key is requested, and does not support zero keys being requested.
I needed this for javascript for use in an html5 canvas for detecting if the users cursor was over or near a certain line. So I modified the answer given by Darius Bacon into coffeescript:
is_on = (a,b,c) ->
# "Return true if point c intersects the line segment from a to b."
# (or the degenerate case that all 3 points are coincident)
return (collinear(a,b,c) and withincheck(a,b,c))
withincheck = (a,b,c) ->
if a[0] != b[0]
within(a[0],c[0],b[0])
else
within(a[1],c[1],b[1])
collinear = (a,b,c) ->
# "Return true if a, b, and c all lie on the same line."
((b[0]-a[0])*(c[1]-a[1]) < (c[0]-a[0])*(b[1]-a[1]) + 1000) and ((b[0]-a[0])*(c[1]-a[1]) > (c[0]-a[0])*(b[1]-a[1]) - 1000)
within = (p,q,r) ->
# "Return true if q is between p and r (inclusive)."
p <= q <= r or r <= q <= p
I think this is a feature currently missing right now.
I noticed when I was making a guide for the keyboard shortcut differences between it and Sublime.
It's a new editor though, I wouldn't be surprised if they added it back in a new version.
is just going to look for a div with class="outer inner", is that correct?
No, '.outer .inner'
will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner'
(no space) would give the results you're thinking of.
'.outer > .inner'
will look for immediate children of an element with the .outer class for elements with the .inner class.
Both '.outer .inner'
and '.outer > .inner'
should work for your example, although the selectors are fundamentally different and you should be wary of this.
In your svn\repos\YourRepo\conf folder you will find two files, authz and passwd. These are the two you need to adjust.
In the passwd file you need to add some usernames and passwords. I assume you have already done this since you have people using it:
[users]
User1=password1
User2=password2
Then you want to assign permissions accordingly with the authz file:
Create the conceptual groups you want, and add people to it:
[groups]
allaccess = user1
someaccess = user2
Then choose what access they have from both the permissions and project level.
So let's give our "all access" guys all access from the root:
[/]
@allaccess = rw
But only give our "some access" guys read-only access to some lower level project:
[/someproject]
@someaccess = r
You will also find some simple documentation in the authz and passwd files.
I originally found a CSS way to bypass this when using the Cycle jQuery plugin. Cycle uses JavaScript to set my slide to overflow: hidden
, so when setting my pictures to width: 100%
the pictures would look vertically cut, and so I forced them to be visible with !important
and to avoid showing the slide animation out of the box I set overflow: hidden
to the container div of the slide. Hope it works for you.
UPDATE - New Solution:
Original problem -> http://jsfiddle.net/xMddf/1/
(Even if I use overflow-y: visible
it becomes "auto" and actually "scroll".)
#content {
height: 100px;
width: 200px;
overflow-x: hidden;
overflow-y: visible;
}
The new solution -> http://jsfiddle.net/xMddf/2/
(I found a workaround using a wrapper div to apply overflow-x
and overflow-y
to different DOM elements as James Khoury advised on the problem of combining visible
and hidden
to a single DOM element.)
#wrapper {
height: 100px;
overflow-y: visible;
}
#content {
width: 200px;
overflow-x: hidden;
}
I found this solution amazing.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
ArrayList list = new ArrayList();
list.add("one");
list.add("two");
list.add("three");
%>
<c:set var="list" value="<%=list%>" />
<html>
<body>
My list is ${list}<br/>
<c:if test='${fn:contains(list, "two")}'>
My list contains two <br/>
</c:if>
<c:if test='${fn:contains(list, ",")}'>
My list contains ,
</c:if>
</body>
</html>
The output for the code above is
My list is [one, two, three]
My list contains two
My list contains ,
I hope it helps someone.
As stated in PostgreSQL docs here:
The SQL CASE expression is a generic conditional expression, similar to if/else statements in other programming languages.
Code snippet specifically answering your question:
SELECT field1, field2,
CASE
WHEN field1>0 THEN field2/field1
ELSE 0
END
AS field3
FROM test
IoC Containers are also good for loading deeply nested class dependencies. For example if you had the following code using Depedency Injection.
public void GetPresenter()
{
var presenter = new CustomerPresenter(new CustomerService(new CustomerRepository(new DB())));
}
class CustomerPresenter
{
private readonly ICustomerService service;
public CustomerPresenter(ICustomerService service)
{
this.service = service;
}
}
class CustomerService
{
private readonly IRespository<Customer> repository;
public CustomerService(IRespository<Customer> repository)
{
this.repository = repository;
}
}
class CustomerRepository : IRespository<Customer>
{
private readonly DB db;
public CustomerRepository(DB db)
{
this.db = db;
}
}
class DB { }
If you had all of these dependencies loaded into and IoC container you could Resolve the CustomerService and the all the child dependencies will automatically get resolved.
For example:
public static IoC
{
private IUnityContainer _container;
static IoC()
{
InitializeIoC();
}
static void InitializeIoC()
{
_container = new UnityContainer();
_container.RegisterType<ICustomerService, CustomerService>();
_container.RegisterType<IRepository<Customer>, CustomerRepository>();
}
static T Resolve<T>()
{
return _container.Resolve<T>();
}
}
public void GetPresenter()
{
var presenter = IoC.Resolve<CustomerPresenter>();
// presenter is loaded and all of its nested child dependencies
// are automatically injected
// -
// Also, note that only the Interfaces need to be registered
// the concrete types like DB and CustomerPresenter will automatically
// resolve.
}
From http://www.epochconverter.com/
SELECT DATEDIFF(s, '1970-01-01 00:00:00', GETUTCDATE())
My bad, SELECT unix_timestamp(time) Time format: YYYY-MM-DD HH:MM:SS or YYMMDD or YYYYMMDD. More on using timestamps with MySQL:
http://www.epochconverter.com/programming/mysql-from-unixtime.php
Using table-layout: fixed
as a property for table
and width: calc(100%/3);
for td
(assuming there are 3 td
's). With these two properties set, the table cells will be equal in size.
Refer to the demo.
Every time you used the mysql console, the version is shown.
mysql -u user
Successful console login shows the following which includes the mysql server version.
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1432
Server version: 5.5.9-log Source distribution
Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
You can also check the mysql server version directly by executing the following command:
mysql --version
You may also check the version information from the mysql console itself using the version variables:
mysql> SHOW VARIABLES LIKE "%version%";
Output will be something like this:
+-------------------------+---------------------+
| Variable_name | Value |
+-------------------------+---------------------+
| innodb_version | 1.1.5 |
| protocol_version | 10 |
| slave_type_conversions | |
| version | 5.5.9-log |
| version_comment | Source distribution |
| version_compile_machine | i386 |
| version_compile_os | osx10.4 |
+-------------------------+---------------------+
7 rows in set (0.01 sec)
You may also use this:
mysql> select @@version;
The STATUS command display version information as well.
mysql> STATUS
You can also check the version by executing this command:
mysql -v
It's worth mentioning that if you have encountered something like this:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket
'/tmp/mysql.sock' (2)
you can fix it by:
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /tmp/mysql.sock
Working Solution
Step 1: Create Cors middleware
php artisan make:middleware Cors
Step 2: Set header in Cors middleware inside handle function
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
Step 3: Add Cors class in app/Http/Kernel.php
protected $routeMiddleware = [
....
'cors' => \App\Http\Middleware\Cors::class,
];
Step 4: Replace mapApiRoutes in app/providers/routeServiceProvider.php
Route::prefix('api')
->middleware(['api', 'cors'])
->namespace($this->namespace)
->group(base_path('routes/api.php'));
Step 5: Add your routes in routes/api.php
Route::post('example', 'controllerName@functionName')->name('example');
Responding to an earlier comment, you can change the background by variable in the "container" example if the CSS is in your php page and not in the css style sheet.
$bgimage = '[some image url];
background-image: url('<?php echo $bgimage; ?>');
I feel like the answer provided by static_rtti is hacky in some sense. I don't know if this was available earlier, but Git tools now provide credential storage.
Cache Mode
$ git config --global credential.helper cache
Use the “cache” mode to keep credentials in memory for a certain period of time. None of the passwords are ever stored on disk, and they are purged from the cache after 15 minutes.
Store Mode
$ git config --global credential.helper 'store --file ~/.my-credentials'
Use the “store” mode to save the credentials to a plain-text file on disk, and they never expire.
I personally used the store mode. I deleted my repository, cloned it, and then had to enter my credentials once.
Reference: 7.14 Git Tools - Credential Storage
Explanation: Use unix command find
with -ctime
(creation time) flag
The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the 'primaries' and 'operands') in terms of each file in the tree.
Solution: According to documenation
-ctime n[smhdw]
If no units are specified, this primary evaluates to true if the difference
between the time of last change of file status information and the time find
was started, rounded up to the next full 24-hour period, is n 24-hour peri-
ods.
If units are specified, this primary evaluates to true if the difference
between the time of last change of file status information and the time find
was started is exactly n units. Please refer to the -atime primary descrip-
tion for information on supported time units.
Formula: find <path> -ctime +[number][timeMeasurement] -ctime -[number][timeMeasurment]
Examples:
1.Find everything that were created after 1 week ago ago and before 2 weeks ago
find / -ctime +1w -ctime -2w
2.Find all javascript files (.js
) in current directory that were created between 1 day ago to 3 days ago
find . -name "*\.js" -type f -ctime +1d -ctime -3d
Depending on the version you are running. It is basically the same just go to
File -> Invalidate caches, then restart Intellij
or
File -> Invalidate caches / Restart
The main difference is that in older versions you had to manually restart as cache files are not removed until you restart. The newer versions will ask if you also want to restart.
As seen here on this official Jetbrains help page
You can also try delete caches manually in the system
folder for your installed version. The location of this folder depends on your OS and version installed.
Windows Vista, 7, 8, 10
<SYSTEM DRIVE>\Users\<USER ACCOUNT NAME>\.<PRODUCT><VERSION>
Linux/Unix
~/.<PRODUCT><VERSION>
Mac OS
~/Library/Caches/<PRODUCT><VERSION>
Read this for more details on cache locations.
In python strings are list of characters, but they are not explicitly list type, just list-like (i.e. it can be treated like a list). More formally, they're known as sequence
(see http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange):
>>> a = 'foo bar'
>>> isinstance(a, list)
False
>>> isinstance(a, str)
True
Since strings are sequence, you can use slicing
to access parts of the list, denoted by list[start_index:end_index]
see Explain Python's slice notation . For example:
>>> a = [1,2,3,4]
>>> a[0]
1 # first element, NOT a sequence.
>>> a[0:1]
[1] # a slice from first to second, a list, i.e. a sequence.
>>> a[0:2]
[1, 2]
>>> a[:2]
[1, 2]
>>> x = "foo bar"
>>> x[0:2]
'fo'
>>> x[:2]
'fo'
When undefined, the slice notation takes the starting position as the 0, and end position as len(sequence).
In the olden C days, it's an array of characters, the whole issue of dynamic vs static list sounds like legend now, see Python List vs. Array - when to use?
Following command
docker-compose restart worker
will just STOP and START the container. i.e without loading any changes from the docker-compose.xml
STOP is similar to hibernating in PC . Hence stop/start will not look for any changes made in configuration file . To reload from the recipe of container (docker-compose.xml) we need to remove and create the container (Similar analogy to rebooting the PC )
So commands will be as following
docker-compose stop worker // go to hibernate
docker-compose rm worker // shutdown the PC
docker-compose create worker // create the container from image and put it in hibernate
docker-compose start worker //bring container to life from hibernation
Try writing the following in the terminal:
sudo apt-get install python-tk
Don't forget to actually import Tkinter module at the beginning of your program:
import Tkinter
ngClass
should be wrapped in square brackets as this is a property binding. Try this:
<div class="my_class" (click)="clickEvent($event)" [ngClass]="{'active': toggle}">
Some content
</div>
In your component:
//define the toogle property
private toggle : boolean = false;
//define your method
clickEvent(event){
//if you just want to toggle the class; change toggle variable.
this.toggle = !this.toggle;
}
Hope that helps.
i did find something like this, helps get rid of hardcoded tempdata tags
public class AccountController : Controller
{
[HttpGet]
public ActionResult Index(IndexPresentationModel model)
{
return View(model);
}
[HttpPost]
public ActionResult Save(SaveUpdateModel model)
{
// save the information
var presentationModel = new IndexPresentationModel();
presentationModel.Message = model.Message;
return this.RedirectToAction(c => c.Index(presentationModel));
}
}
You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.
Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String
'Assign data to first item in array
compArray(1) = "asdf"
'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"
'Prints "ErrorState"
Debug.Print Computers("Computer Name")
Collections cannot be sorted so if you need to sort data you will probably want to use an array.
Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx
Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx
Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!
Edit:
Sub ArrayExample()
Dim subject As String
Dim TestArray() As String
Dim counter As Long
subject = "Example"
counter = Len(subject)
ReDim TestArray(1 To counter) As String
For counter = 1 To Len(subject)
TestArray(counter) = Right(Left(subject, counter), 1)
Next
End Sub
if you want to find index for more than 2 occurrence:
public static int ordinalIndexOf(String fullText,String subText,int pos){
if(fullText.contains(subText)){
if(pos <= 1){
return fullText.indexOf(subText);
}else{
--pos;
return fullText.indexOf(subText, ( ordinalIndexOf(fullText,subText,pos) + 1) );
}
}else{
return -1;
}
}
The real question is why does it generate a 500 error. If it is related to any input parameters, then I would argue that it should be handled internally and returned as a 400 series error. Generally a 400, 404 or 406 would be appropriate to reflect bad input since the general convention is that a RESTful resource is uniquely identified by the URL and a URL that cannot generate a valid response is a bad request (400) or similar.
If the error is caused by anything other than the inputs explicitly or implicitly supplied by the request, then I would say a 500 error is likely appropriate. So a failed database connection or other unpredictable error is accurately represented by a 500 series error.
Atomic = thread safety
Non-atomic = No thread safety
Instance variables are thread-safe if they behave correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
If a thread changes the value of the instance the changed value is available to all the threads, and only one thread can change the value at a time.
atomic
:if the instance variable is gonna be accessed in a multithreaded environment.
atomic
:Not as fast as nonatomic
because nonatomic
doesn't require any watchdog work on that from runtime .
nonatomic
:If the instance variable is not gonna be changed by multiple threads you can use it. It improves the performance.
I found this in another blog that can explain it a little bit more these differences:
Though both the interfaces are implemented by the classes who wish to execute in a different thread of execution, but there are few differences between the two interface which are:
Callable<V>
instance returns a result of type V
, whereas a Runnable
instance doesn't.Callable<V>
instance may throw checked exceptions, whereas a Runnable
instance can'tThe designers of Java felt a need of extending the capabilities of the Runnable
interface, but they didn't want to affect the uses of the Runnable
interface and probably that was the reason why they went for having a separate interface named Callable
in Java 1.5 than changing the already existing Runnable
.
Looks like I'm a little late to the party, but here's an example for some of the top browsers:
/* IE10 */
background-image: -ms-linear-gradient(top, #444444 0%, #999999 100%);
/* Mozilla Firefox */
background-image: -moz-linear-gradient(top, #444444 0%, #999999 100%);
/* Opera */
background-image: -o-linear-gradient(top, #444444 0%, #999999 100%);
/* Webkit (Safari/Chrome 10) */
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0, #444444), color-stop(1, #999999));
/* Webkit (Chrome 11+) */
background-image: -webkit-linear-gradient(top, #444444 0%, #999999 100%);
/* Proposed W3C Markup */
background-image: linear-gradient(top, #444444 0%, #999999 100%);
Source: http://ie.microsoft.com/testdrive/Graphics/CSSGradientBackgroundMaker/Default.html
Note: all of these browsers also support rgb/rgba in place of hexadecimal notation.
Dummy data (you should supply this for us)
visual1 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
visual2 = data.frame(ISSUE_DATE=runif(100,2006,2008),COUNTED=runif(100,0,50))
combine:
visuals = rbind(visual1,visual2)
visuals$vis=c(rep("visual1",100),rep("visual2",100)) # 100 points of each flavour
Now do:
ggplot(visuals, aes(ISSUE_DATE,COUNTED,group=vis,col=vis)) +
geom_point() + geom_smooth()
and adjust colours etc to taste.
You are right, there is no datatype in SQL-Server which can hold a list of integers. But what you can do is store a list of integers as a string.
DECLARE @listOfIDs varchar(8000);
SET @listOfIDs = '1,2,3,4';
You can then split the string into separate integer values and put them into a table. Your procedure might already do this.
You can also use a dynamic query to achieve the same outcome:
DECLARE @SQL nvarchar(8000);
SET @SQL = 'SELECT * FROM TabA WHERE TabA.ID IN (' + @listOfIDs + ')';
EXECUTE (@SQL);
It all depends on the type of classification problem you are dealing with. There are three main categories
In the first case, binary cross-entropy should be used and targets should be encoded as one-hot vectors.
In the second case, categorical cross-entropy should be used and targets should be encoded as one-hot vectors.
In the last case, binary cross-entropy should be used and targets should be encoded as one-hot vectors. Each output neuron (or unit) is considered as a separate random binary variable, and the loss for the entire vector of outputs is the product of the loss of single binary variables. Therefore it is the product of binary cross-entropy for each single output unit.
The binary cross-entropy is defined as
and categorical cross-entropy is defined as
where c
is the index running over the number of classes C
.
For Googlers:
STATEFULNESS
MECHANISMS
Authorization
, are just headers without any special treatment, client has to manage all aspects of the transferSTATEFULNESS COMPARISON
hash(data + secret key)
, where secret key is only known to server, so the integrity of token data can be verifiedMECHANISM COMPARISON
httpOnly
thus prevent client JavaScript accessSUM-UP
To fix your code you can simply change [Cov]
to Cov.values
, the first parameter of pd.DataFrame
will become a multi-dimensional numpy
array:
Cov = pd.read_csv("path/to/file.txt", sep='\t')
Frame=pd.DataFrame(Cov.values, columns = ["Sequence", "Start", "End", "Coverage"])
Frame.to_csv("path/to/file.txt", sep='\t')
But the smartest solution still is use pd.read_excel
with header=None
and names=columns_list
.
First off:
public class ProfileCollection implements Iterable<Profile> {
Second:
return m_Profiles.get(m_ActiveProfile);
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
"FirstLine" + "<br/>" "SecondLine"
I found the product key for Visual Studio 2008 Professional under a slightly different key:
HKLM\SOFTWARE\Wow6432Node\Microsoft\MSDN\8.0\Registration\PIDKEY
it was listed without the dashes as stated above.
Take a pointer to the first element instead:
process_data (&something [0]);
Python3:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')
handle.mainFunction(parameter)
This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).
There's also the more normal way of importing a python module in Python3,
import importlib
module = importlib.load_module('folder.filename')
module.function()
Kudos to Sebastian for spplying a similar answer for Python2:
import imp
foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()
The accepted answer is correct but I'd like to add my two cents. I've run into a problem where I had a project A that had a project B as a dependency. Both projects use slf4j but project B uses log4j while project A uses logback. Project B uses slf4j 1.6.1, while project A uses slf4j 1.7.5 (due to the already included logback 1.2.3 dependency).
The problem: Project A couldn't find a function that exists on slf4j 1.7.5, after checking eclipe's dependency hierarchy tab I found out that during build it was using slf4j 1.6.1 from project B, instead of using logback's slf4j 1.7.5.
I solved the issue by changing the order of the dependencies on project A pom, when I moved project B entry below the logback entry then maven started to build the project using slf4j 1.7.5.
Edit: Adding the slf4j 1.7.5 dependency before Project B dependency worked too.
I see a few answers here, most of them complicated or with some cons (additional divs, text-align doesn't work because of display: inline-block). I think this is the simplest and problem-free solution:
HTML:
<table>
<!-- Rows -->
<tr>
<td>E-MAIL</td>
<td><input name="email" type="email" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Register!" /></td>
</tr>
</table>
CSS:
table input[type="submit"] {
display: block;
margin: 0 auto;
}
Basically shared folders are renamed to synced folder from v1 to v2 (docs), under the bonnet it is still using vboxsf
between host and guest (there is known performance issues if there are large numbers of files/directories).
/vagrant
in guestVagrant is mounting the current working directory (where Vagrantfile
resides) as /vagrant
in the guest, this is the default behaviour.
See docs
NOTE: By default, Vagrant will share your project directory (the directory with the Vagrantfile) to /vagrant.
You can disable this behaviour by adding cfg.vm.synced_folder ".", "/vagrant", disabled: true
in your Vagrantfile
.
Based on the output /tmp
on host was NOT mounted during up time.
Use VAGRANT_INFO=debug vagrant up
or VAGRANT_INFO=debug vagrant reload
to start the VM for more output regarding why the synced folder is not mounted. Could be a permission issue (mode bits of /tmp
on host should be drwxrwxrwt
).
I did a test quick test using the following and it worked (I used opscode bento raring vagrant base box)
config.vm.synced_folder "/tmp", "/tmp/src"
output
$ vagrant reload
[default] Attempting graceful shutdown of VM...
[default] Setting the name of the VM...
[default] Clearing any previously set forwarded ports...
[default] Creating shared folders metadata...
[default] Clearing any previously set network interfaces...
[default] Available bridged network interfaces:
1) eth0
2) vmnet8
3) lxcbr0
4) vmnet1
What interface should the network bridge to? 1
[default] Preparing network interfaces based on configuration...
[default] Forwarding ports...
[default] -- 22 => 2222 (adapter 1)
[default] Running 'pre-boot' VM customizations...
[default] Booting VM...
[default] Waiting for VM to boot. This can take a few minutes.
[default] VM booted and ready for use!
[default] Configuring and enabling network interfaces...
[default] Mounting shared folders...
[default] -- /vagrant
[default] -- /tmp/src
Within the VM, you can see the mount info /tmp/src on /tmp/src type vboxsf (uid=900,gid=900,rw)
.
I've been fighting with this all day: I have a Perl script that builds a set of tables by first doing a DROP IF EXISTS ...
on them and then CREATE
ing them. The DROP
succeeded, but on CREATE
I got this error message: table already exists
I finally got to the bottom of it: The new version of MySQL that I'm using has a default engine of InnoDB ("show engine \G;") I changed it in the my.cnf file to default to MyISAM, re-started MySQL, and now I no longer get the "table already exists" error.
sudo su root
chown -R user:group dir
The dir is your git repo.
Then do:
git pull origin master
You'll see changes about commits by others.
Run this in the command line (or git bash on windows):
echo "" > $(npm config get userconfig)
npm config edit
echo "" > $(npm config get globalconfig)
npm config --global edit
sudo sh -c 'echo "" > $(npm config get globalconfig)'
Python may be good, but it isn't God...
There are a few different ways to solve equations. SymPy has already been mentioned, if you're looking for analytic solutions.
If you're happy to just have a numerical solution, Numpy has a few routines that can help. If you're just interested in solutions to polynomials, numpy.roots will work. Specifically for the case you mentioned:
>>> import numpy
>>> numpy.roots([2,-6])
array([3.0])
For more complicated expressions, have a look at scipy.fsolve.
Either way, you can't escape using a library.
Disclaimer: The original question was about MySQL. The SQL Server answer is below.
In MySQL, the regex syntax is the following:
SELECT * FROM YourTable WHERE (`url` NOT REGEXP '^[-A-Za-z0-9/.]+$')
Use the REGEXP
clause instead of LIKE
. The latter is for pattern matching using %
and _
wildcards.
Since you made a typo, and you're using SQL Server (not MySQL), you'll have to create a user-defined CLR function to expose regex functionality.
Take a look at this article for more details.
There is a difference between initialization and assignment. What you want to do is not initialization, but assignment. But such assignment to array is not possible in C++.
Here is what you can do:
#include <algorithm>
int array [] = {1,3,34,5,6};
int newarr [] = {34,2,4,5,6};
std::copy(newarr, newarr + 5, array);
However, in C++0x, you can do this:
std::vector<int> array = {1,3,34,5,6};
array = {34,2,4,5,6};
Of course, if you choose to use std::vector
instead of raw array.
You can also get a direct link to a view within a folder by using "TreeValue", "TreeField" and "RootFolder".
Example:
http://sharepoint/Docs/YourLibrary/Forms/YourView.aspx?RootFolder=MyFolder&TreeField=Folders&TreeValue=MyFolder
To further explain: I have a SharePoint site, with a docs library called YourLibrary. I have a folder called MyFolder. I created a view that can be used at any level of that Library structure with a URL path of YourView.aspx Using that link, it will take me to the view I created, with all the filters and styles, but only show the results that would occur in the contents of that folder in RootFolder and TreeValue.
If the string is
$STR = 'HELLO WORLD'
and you want to remove the empty space between 'HELLO' and 'WORLD'
$STR.replace(' ','')
replace
takes the string and replaces white space with empty string (of length 0), in other words the white space is just deleted.
It seems that Google has updated its developer page and added various trainings there.
One of them deals with the creation of custom views and can be found here
FormsAuthentication.Decrypt takes the actual value of the cookie, not the name of it. You can get the cookie value like
HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value;
and decrypt that.
You can call CREATE Function
near the beginning of your script and DROP Function
near the end.
I came up with another solution, which I don't love but gets the job done.
Basically duplicate the child elements in such a way that the duplicates are not visible.
<div id="parent">
<div class="width-calc">
<div class="child1"></div>
<div class="child2"></div>
</div>
<div class="child1"></div>
<div class="child2"></div>
</div>
CSS:
.width-calc {
height: 0;
overflow: hidden;
}
If those child elements contain little markup, then the impact will be small.
It will evaluate X and, if X is not null, the empty string, or 0 (logical false), then it will assign it to z. If X is null, the empty string, or 0 (logical false), then it will assign y to z.
var x = '';
var y = 'bob';
var z = x || y;
alert(z);
Will output 'bob';
The first part is answered in the FAQ as slain pointed out.
As for a workaround, you can wrap the body of the loop in a function and return
early from that, e.g.
-- Print the odd numbers from 1 to 99
for a = 1, 99 do
(function()
if a % 2 == 0 then
return
end
print(a)
end)()
end
Or if you want both break
and continue
functionality, have the local function perform the test, e.g.
local a = 1
while (function()
if a > 99 then
return false; -- break
end
if a % 2 == 0 then
return true; -- continue
end
print(a)
return true; -- continue
end)() do
a = a + 1
end
For using DOSBox with SDL, you will need to set or change the following:
[sdl]
windowresolution=1280x960
output=opengl
Here is three options to put those settings:
Edit user's default configuration, for example, using vi
:
$ dosbox -printconf
/home/USERNAME/.dosbox/dosbox-0.74.conf
$ vi "$(dosbox -printconf)"
$ dosbox
For temporary resize, create a new configuration with the three lines above, say newsize.conf
:
$ dosbox -conf newsize.conf
You can use -conf
to load multiple configuration and/or with -userconf
for default configuration, for example:
$ dosbox -userconf -conf newsize.conf
[snip]
---
CONFIG:Loading primary settings from config file /home/USERNAME/.dosbox/dosbox-0.74.conf
CONFIG:Loading additional settings from config file newsize.conf
[snip]
Create a dosbox.conf
under current directory, DOSBox loads it as default.
DOSBox should start up and resize to 1280x960 in this case.
Note that you probably would not get any size you desired, for instance, I set 1280x720 and I got 1152x720.
Posting parameters Using POST:-
URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");
The part which you missed is in the the following... i.e., as follows..
// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();
The rest of the thing you can do it.
Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern
it will create 0 byte file and not write anything:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
<param name="append" value="false"/>
<param name="maxFileSize" value="1GB"/>
<param name="maxBackupIndex" value="2"/>
<param name="file" value="/tmp/bd.log"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
</layout>
</appender>
<logger name="com.example.mypackage" additivity="false">
<level value="debug"/>
<appender-ref ref="bdfile"/>
</logger>
<root>
<priority value="info"/>
<appender-ref ref="bdfile"/>
<appender-ref ref="console"/>
</root>
</log4j:configuration>
The reason you getting the error with COMP is that the utility assumes the files that you are comparing are of the same size. To overcome that you can use th '/n'
option with which you can specify the number of lines you want to compare. (see the options supported by comp by typing 'comp /?'
on the command line.
so your command would look like :
C:\>comp "filepath1" "filepath2" /a /l /n=(the number of lines you want to compare) /c
This should solve your problem if you wanna stick to using COMP. But this will be a problem for really large files.
Though comp
is an option, but I feel it is primitive and FC
is a better option. you can use FORFILES
and FC
together to probably make a really good filecompare utility if you require one on a frequent basis.
FC is used this way for ref:
C:\>fc /c(case insensistive) /lbn(number of errors allowed before you wanna stop compare) /n(display line number) "filename1" "filename2"
there are many options available which you can see by 'fc /?'
hope this helps
Nothing worked for IE (Internet Explorer). My testers were able to break my modal by clicking off the popup window on buttons behind it. So, I listened for a click on my modal screen div and forced refocus on a popup button.
<div class="modal-backscreen" (click)="modalOutsideClick($event)">
</div>
modalOutsideClick(event: any) {
event.preventDefault()
// handle IE click-through modal bug
event.stopPropagation()
setTimeout(() => {
this.renderer.invokeElementMethod(this.myModal.nativeElement, 'focus')
}, 100)
}
As simple as joining lists in python itself.
ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost
localhost | SUCCESS => {
"msg": "list-joined-together" }
Works the same way using variables:
ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost
Just for the record in modern times,
1 - Just have updated Xcode on your machine as you normally do
2 - Open terminal and
$ xcode-select --install
it will perform a short install of a minute or two.
3 - Launch Xcode. "New" "Project" ... you have to choose "Command line tool"
Note - confusingly this is under the "macOS" tab.
Select "C" language on the next screen...
4- You'll be asked to save the project somewhere on your desktop. The name you give the project here is just the name of the folder that will hold the project. It does not have any importance in the actual software.
5 - You're golden! You can now enjoy c with Mac and Xcode.
I'm not sure that I understand what you mean by "rights of ownership".
If User B owns a stored procedure, User B can grant User A permission to run the stored procedure
GRANT EXECUTE ON b.procedure_name TO a
User A would then call the procedure using the fully qualified name, i.e.
BEGIN
b.procedure_name( <<list of parameters>> );
END;
Alternately, User A can create a synonym in order to avoid having to use the fully qualified procedure name.
CREATE SYNONYM procedure_name FOR b.procedure_name;
BEGIN
procedure_name( <<list of parameters>> );
END;
Define a behavior in your .config
file:
<configuration>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="debug">
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
...
</system.serviceModel>
</configuration>
Then apply the behavior to your service along these lines:
<configuration>
<system.serviceModel>
...
<services>
<service name="MyServiceName" behaviorConfiguration="debug" />
</services>
</system.serviceModel>
</configuration>
You can also set it programmatically. See this question.
Had this Xms
and Xmx
memory low issue happen to me any time I was working with the XML. I also tried increasing this memory, only to find that it just took a little longer for it to happen again.
After getting very frustrated and almost deciding to convert all my current projects back over to Eclipse, which I did not want to do, I figured out what was causing it and was able to repeat this failure and prevent it every time.
While editing the XML in (Text view), and using the "Preview" render view, this causes the loss of memory, every time. Turning off "Preview" and using the Design tab to render the screen only, I am able to use Android Studio all day long, with no crash.
I wish this could be fixed for good, because it would be very nice to use the "Preview" render while editing the XML, however I am glad I can keep using Android Studio.
This works:
myElement.className = 'foo bar baz';
Since your task might contain asynchronous code you have to signal gulp when your task has finished executing (= "async completion").
In Gulp 3.x you could get away without doing this. If you didn't explicitly signal async completion gulp would just assume that your task is synchronous and that it is finished as soon as your task function returns. Gulp 4.x is stricter in this regard. You have to explicitly signal task completion.
You can do that in six ways:
This is not really an option if you're only trying to print something, but it's probably the most frequently used async completion mechanism since you're usually working with gulp streams. Here's a (rather contrived) example demonstrating it for your use case:
var print = require('gulp-print');
gulp.task('message', function() {
return gulp.src('package.json')
.pipe(print(function() { return 'HTTP Server Started'; }));
});
The important part here is the return
statement. If you don't return the stream, gulp can't determine when the stream has finished.
Promise
This is a much more fitting mechanism for your use case. Note that most of the time you won't have to create the Promise
object yourself, it will usually be provided by a package (e.g. the frequently used del
package returns a Promise
).
gulp.task('message', function() {
return new Promise(function(resolve, reject) {
console.log("HTTP Server Started");
resolve();
});
});
Using async/await syntax this can be simplified even further. All functions marked async
implicitly return a Promise so the following works too (if your node.js version supports it):
gulp.task('message', async function() {
console.log("HTTP Server Started");
});
This is probably the easiest way for your use case: gulp automatically passes a callback function to your task as its first argument. Just call that function when you're done:
gulp.task('message', function(done) {
console.log("HTTP Server Started");
done();
});
This is mostly useful if you have to invoke a command line tool directly because there's no node.js wrapper available. It works for your use case but obviously I wouldn't recommend it (especially since it's not very portable):
var spawn = require('child_process').spawn;
gulp.task('message', function() {
return spawn('echo', ['HTTP', 'Server', 'Started'], { stdio: 'inherit' });
});
Observable
.I've never used this mechanism, but if you're using RxJS it might be useful. It's kind of overkill if you just want to print something:
var of = require('rxjs').of;
gulp.task('message', function() {
var o = of('HTTP Server Started');
o.subscribe(function(msg) { console.log(msg); });
return o;
});
EventEmitter
Like the previous one I'm including this for completeness sake, but it's not really something you're going to use unless you're already using an EventEmitter
for some reason.
gulp.task('message3', function() {
var e = new EventEmitter();
e.on('msg', function(msg) { console.log(msg); });
setTimeout(() => { e.emit('msg', 'HTTP Server Started'); e.emit('finish'); });
return e;
});
The above answers give a good insight on how to delete the "Cars"
However, I want this answer to challenge the approach itself:
1- SQLite CoreData is a relational database. In this case, where there isn't any releation, I would advise against using CoreData and maybe using the file system instead, or keep things in memory.
2- In other examples, where "Car" entity have other relations, and therefore CoreData, I would advise against having 2000 cars as root entity. Instead I would give them a parent, let's say "CarsRepository" entity. Then you can give a one-to-many relationship to the "Car" entity, and just replace the relationship to point to the new cars when they are downloaded. Adding the right deletion rule to the relationships ensures the integrity of the model.
Directly from the Windows.h header file:
#ifndef WIN32_LEAN_AND_MEAN
#include <cderr.h>
#include <dde.h>
#include <ddeml.h>
#include <dlgs.h>
#ifndef _MAC
#include <lzexpand.h>
#include <mmsystem.h>
#include <nb30.h>
#include <rpc.h>
#endif
#include <shellapi.h>
#ifndef _MAC
#include <winperf.h>
#include <winsock.h>
#endif
#ifndef NOCRYPT
#include <wincrypt.h>
#include <winefs.h>
#include <winscard.h>
#endif
#ifndef NOGDI
#ifndef _MAC
#include <winspool.h>
#ifdef INC_OLE1
#include <ole.h>
#else
#include <ole2.h>
#endif /* !INC_OLE1 */
#endif /* !MAC */
#include <commdlg.h>
#endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */
if you want to know what each of the headers actually do, typeing the header names into the search in the MSDN library will usually produce a list of the functions in that header file.
Also, from Microsoft's support page:
To speed the build process, Visual C++ and the Windows Headers provide the following new defines:
VC_EXTRALEAN
WIN32_LEAN_AND_MEANYou can use them to reduce the size of the Win32 header files.
Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.
Try moving the button styling to the TouchableHighlight
itself:
Styles:
submit:{
marginRight:40,
marginLeft:40,
marginTop:10,
paddingTop:20,
paddingBottom:20,
backgroundColor:'#68a0cf',
borderRadius:10,
borderWidth: 1,
borderColor: '#fff'
},
submitText:{
color:'#fff',
textAlign:'center',
}
Button (same):
<TouchableHighlight
style={styles.submit}
onPress={() => this.submitSuggestion(this.props)}
underlayColor='#fff'>
<Text style={[this.getFontSize(),styles.submitText]}>Submit</Text>
</TouchableHighlight>
You need to put it in the join
clause, not the where
:
SELECT *
FROM categories
LEFT JOIN user_category_subscriptions ON
user_category_subscriptions.category_id = categories.category_id
and user_category_subscriptions.user_id =1
See, with an inner join
, putting a clause in the join
or the where
is equivalent. However, with an outer join
, they are vastly different.
As a join
condition, you specify the rowset that you will be joining to the table. This means that it evaluates user_id = 1
first, and takes the subset of user_category_subscriptions
with a user_id
of 1
to join to all of the rows in categories
. This will give you all of the rows in categories
, while only the categories
that this particular user has subscribed to will have any information in the user_category_subscriptions
columns. Of course, all other categories
will be populated with null
in the user_category_subscriptions
columns.
Conversely, a where
clause does the join, and then reduces the rowset. So, this does all of the joins and then eliminates all rows where user_id
doesn't equal 1
. You're left with an inefficient way to get an inner join
.
Hopefully this helps!
In most of the cases it’s only a need for the transpiler/bundler, which might not be configured to work with JSX files, but with JS! So you are forced to use JS files instead of JSX.
And since react is just a library for javascript, it makes no difference for you to choose between JSX or JS. They’re completely interchangeable!
In some cases users/developers might also choose JSX over JS, because of code highlighting, but the most of the newer editors are also viewing the react syntax correctly in JS files.
In Java:
String str = " hello world ";
// prints "hello world"
System.out.println(str.replaceAll("^(\\s+)|(\\s+)$", ""));
CMP
subtracts the operands and sets the flags. Namely, it sets the zero flag if the difference is zero (operands are equal).
TEST
sets the zero flag, ZF
, when the result of the AND operation is zero. If two operands are equal, their bitwise AND is zero when both are zero. TEST
also sets the sign flag, SF
, when the most significant bit is set in the result, and the parity flag, PF
, when the number of set bits is even.
JE
[Jump if Equals] tests the zero flag and jumps if the flag is set. JE
is an alias of JZ
[Jump if Zero] so the disassembler cannot select one based on the opcode. JE
is named such because the zero flag is set if the arguments to CMP
are equal.
So,
TEST %eax, %eax
JE 400e77 <phase_1+0x23>
jumps if the %eax
is zero.
Use this :
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.package.name");
startActivity(intent);
I felt a like I needed to share this manipulated code to the accepted answer - as I have no reputation, I'm unable to comment..
using System;
using System.Xml.Serialization;
using System.IO;
namespace ObjectSerialization
{
public static class ObjectSerialization
{
// THIS: (C): https://stackoverflow.com/questions/2434534/serialize-an-object-to-string
/// <summary>
/// A helper to serialize an object to a string containing XML data of the object.
/// </summary>
/// <typeparam name="T">An object to serialize to a XML data string.</typeparam>
/// <param name="toSerialize">A helper method for any type of object to be serialized to a XML data string.</param>
/// <returns>A string containing XML data of the object.</returns>
public static string SerializeObject<T>(this T toSerialize)
{
// create an instance of a XmlSerializer class with the typeof(T)..
XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType());
// using is necessary with classes which implement the IDisposable interface..
using (StringWriter stringWriter = new StringWriter())
{
// serialize a class to a StringWriter class instance..
xmlSerializer.Serialize(stringWriter, toSerialize); // a base class of the StringWriter instance is TextWriter..
return stringWriter.ToString(); // return the value..
}
}
// THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
/// <summary>
/// Deserializes an object which is saved to an XML data string. If the object has no instance a new object will be constructed if possible.
/// <note type="note">An exception will occur if a null reference is called an no valid constructor of the class is available.</note>
/// </summary>
/// <typeparam name="T">An object to deserialize from a XML data string.</typeparam>
/// <param name="toDeserialize">An object of which XML data to deserialize. If the object is null a a default constructor is called.</param>
/// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
/// <returns>An object which is deserialized from the XML data string.</returns>
public static T DeserializeObject<T>(this T toDeserialize, string xmlData)
{
// if a null instance of an object called this try to create a "default" instance for it with typeof(T),
// this will throw an exception no useful constructor is found..
object voidInstance = toDeserialize == null ? Activator.CreateInstance(typeof(T)) : toDeserialize;
// create an instance of a XmlSerializer class with the typeof(T)..
XmlSerializer xmlSerializer = new XmlSerializer(voidInstance.GetType());
// construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
using (StringReader stringReader = new StringReader(xmlData))
{
// return the "new" object deserialized via the XmlSerializer class instance..
return (T)xmlSerializer.Deserialize(stringReader);
}
}
// THIS: (C): VPKSoft, 2018, https://www.vpksoft.net
/// <summary>
/// Deserializes an object which is saved to an XML data string.
/// </summary>
/// <param name="toDeserialize">A type of an object of which XML data to deserialize.</param>
/// <param name="xmlData">A string containing a serialized XML data do deserialize.</param>
/// <returns>An object which is deserialized from the XML data string.</returns>
public static object DeserializeObject(Type toDeserialize, string xmlData)
{
// create an instance of a XmlSerializer class with the given type toDeserialize..
XmlSerializer xmlSerializer = new XmlSerializer(toDeserialize);
// construct a StringReader class instance of the given xmlData parameter to be deserialized by the XmlSerializer class instance..
using (StringReader stringReader = new StringReader(xmlData))
{
// return the "new" object deserialized via the XmlSerializer class instance..
return xmlSerializer.Deserialize(stringReader);
}
}
}
}
Through the Computer management console, navigate through Event Viewer > Windows Logs > System. Every services that change state will be logged here.
You'll see info like: The XXXX service entered the running state or The XXXX service entered the stopped state, etc.
You can use the onload
event to detect when the iframe has finished loading, and there you can use the scrollTo function on the contentWindow of the iframe, to scroll to a defined position of pixels, from left and top (x, y):
var myIframe = document.getElementById('iframe');
myIframe.onload = function () {
myIframe.contentWindow.scrollTo(xcoord,ycoord);
}
You can check a working example here.
Note: This will work if both pages reside on the same domain.
Pickle uses different protocols
to convert your data to a binary stream.
In python 2 there are 3 different protocols (0
, 1
, 2
) and the default is 0
.
In python 3 there are 5 different protocols (0
, 1
, 2
, 3
, 4
) and the default is 3
.
You must specify in python 3 a protocol lower than 3
in order to be able to load the data in python 2. You can specify the protocol
parameter when invoking pickle.dump
.
While I agree that Graeme Blackwood's should be the accepted answer, because it practically solves the issue, it should be noted that a fixed element can be positioned relatively to its container.
I noticed by accident that when applying
-webkit-transform: translateZ(0);
to the body, it made a fixed child relative to it (instead of the viewport). So my fixed elements left
and top
properties were now relative to the container.
So I did some research, and found that the issue was already been covered by Eric Meyer and even if it felt like a "trick", turns out that this is part of the specifications:
For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block. The object acts as a containing block for fixed positioned descendants.
http://www.w3.org/TR/css3-transforms/
So, if you apply any transformation to a parent element, it will become the containing block.
The problem is that the implementation seems buggy/creative, because the elements also stop behaving as fixed (even if this bit doesn't seem to be part of specification).
The same behavior will be found in Safari, Chrome and Firefox, but not in IE11 (where the fixed element will still remain fixed).
Another interesting (undocumented) thing is that when a fixed element is contained inside a transformed element, while its top
and left
properties will now be related to the container, respecting the box-sizing
property, its scrolling context will extend over the border of the element, as if box-sizing was set to border-box
. For some creative out there, this could possibly become a plaything :)
I like pospi's suggestion. Why not go all-out any use the 'tag' property of a view (which you can specify in XML - 'android:tag') to specify any additional styling that you can't do in XML. I like JSON so I'd use a JSON string to specify a key/value set. This class does the work - just call Style.setContentView(this, [resource id])
in your activity.
public class Style {
/**
* Style a single view.
*/
public static void apply(View v) {
if (v.getTag() != null) {
try {
JSONObject json = new JSONObject((String)v.getTag());
if (json.has("typeface") && v instanceof TextView) {
((TextView)v).setTypeface(Typeface.createFromAsset(v.getContext().getAssets(),
json.getString("typeface")));
}
}
catch (JSONException e) {
// Some views have a tag without it being explicitly set!
}
}
}
/**
* Style the passed view hierarchy.
*/
public static View applyTree(View v) {
apply(v);
if (v instanceof ViewGroup) {
ViewGroup g = (ViewGroup)v;
for (int i = 0; i < g.getChildCount(); i++) {
applyTree(g.getChildAt(i));
}
}
return v;
}
/**
* Inflate, style, and set the content view for the passed activity.
*/
public static void setContentView(Activity activity, int resource) {
activity.setContentView(applyTree(activity.getLayoutInflater().inflate(resource, null)));
}
}
Obviously you'd want to handle more than just the typeface to make using JSON worthwhile.
A benefit of the 'tag' property is that you can set it on a base style which you use as a theme and thus have it apply to all of your views automatically. EDIT: Doing this results in a crash during inflation on Android 4.0.3. You can still use a style and apply it to text views individually.
One thing you'll see in the code - some views have a tag without one being explicitly set - bizarrely it's the string '?p???p?' - which is 'cut' in greek, according to google translate! What the hell...?
There are indeed a lot of string similarity measures out there:
You can find explanation and java implementation of these here: https://github.com/tdebatty/java-string-similarity
I was in the same boat. Installed Eclipse, realized need CDT.
sudo apt-get install eclipse eclipse-cdt g++
This just adds the CDT package on top of existing installation - no un-installation etc. required.
If your pair of lines will only appear once in your file, you could use
File.ReadLines(pathToTextFile)
.SkipWhile(line => !line.Contains("CustomerEN"))
.Skip(1) // optional
.TakeWhile(line => !line.Contains("CustomerCh"));
If you could have multiple occurrences in one file, you're probably better off using a regular foreach
loop - reading lines, keeping track of whether you're currently inside or outside a customer etc:
List<List<string>> groups = new List<List<string>>();
List<string> current = null;
foreach (var line in File.ReadAllLines(pathToFile))
{
if (line.Contains("CustomerEN") && current == null)
current = new List<string>();
else if (line.Contains("CustomerCh") && current != null)
{
groups.Add(current);
current = null;
}
if (current != null)
current.Add(line);
}
Put the varible in an array and Use a for Loop to assign the same value to multiple variables.
myArray[moveUP, moveDown, moveLeft];
for(var i = 0; i < myArray.length; i++){
myArray[i] = true;
}
Phonegap is pretty slow: clicking a button can take up to 3 sec to display the next screen. iscroll is slow and jumpy.
There other funny bugs and issues that i was able to overcome, but in total - not fully matured.
EDIT: Per Grumpy comment, it is not Phonegap who is actually slow, it is the JS/Browser native engine
Hi you can achieve your result with use of <marquee behavior="alternate"></marquee>
HTML
<div class="wrapper">
<marquee behavior="alternate"><span class="marquee">This is a marquee!</span></marquee>
</div>
CSS
.wrapper{
max-width: 400px;
background: green;
height: 40px;
text-align: right;
}
.marquee {
background: red;
white-space: nowrap;
-webkit-animation: rightThenLeft 4s linear;
}
see the demo:- http://jsfiddle.net/gXdMc/6/
Not sure why this worked for me while nothing else did but just in case anyone else is still looking...
In between head tags:
<script>
function myFunction() {
script code
}
</script>
Then for the < a > tag:
<a href='' onclick='myFunction()' > Call Function </a>
Try this:
img{border:0;}
You can also limitate the scope and only remove border on some images by doing so:
.myClass img{border:0;}
More information about the border css property can by found here.
Edit: Changed border from 0px
to 0
. As explained in comments, px
is redundant for a unit of 0
.
Incorrect:
SELECT * FROM customers WHERE name LIKE '%Bob Smith%';
Instead:
select count(*)
from rearp.customers c
where c.name LIKE '%Bob smith.8%';
select count
will just query (totals)
C
will link the db.table to the names row you need this to index
LIKE
should be obvs
8
will call all references in DB 8 or less (not really needed but i like neatness)
In Qt 4.7, there is the QDateTime::currentMSecsSinceEpoch()
static function, which does exactly what you need, without any intermediary steps. Hence I'd recommend that for projects using Qt 4.7 or newer.
Other way which I found useful is:
git checkout <wildcard>
Example:
git checkout *.html
More generally:
git checkout <branch> <filename/wildcard>
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Thin.otf);
font-weight: 200;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Light.otf);
font-weight: 300;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Regular.otf);
font-weight: normal;
}
@font-face {
font-family: Kaffeesatz;
src: url(YanoneKaffeesatz-Bold.otf);
font-weight: bold;
}
h3, h4, h5, h6 {
font-size:2em;
margin:0;
padding:0;
font-family:Kaffeesatz;
font-weight:normal;
}
h6 { font-weight:200; }
h5 { font-weight:300; }
h4 { font-weight:normal; }
h3 { font-weight:bold; }
If you using Java then follow below code snippet :
GoogleCredential refreshTokenCredential = new GoogleCredential.Builder().setJsonFactory(JSON_FACTORY).setTransport(HTTP_TRANSPORT).setClientSecrets(CLIENT_ID, CLIENT_SECRET).build().setRefreshToken(yourOldToken);
refreshTokenCredential.refreshToken(); //do not forget to call this
String newAccessToken = refreshTokenCredential.getAccessToken();
Here is another site that will help you with all the code you need as long as you have a correctly formated JSON string available:
If Ubuntu Docker image isn't recognizing 'ifconfig' inside of GNS3, you'll need to open Ubuntu docker image on your host.
Assuming you already have docker on your host pc and ubuntu pull'd from docker images. Enter these commands in your host OS (Linux, CentOS, etc.) CLI.
$docker images
$docker run -it ubuntu
$apt-get update
$apt-get install net-tools
(side note: you can add whatever other tools and services that you would like to add now, but for now this is just to get ifconfig to work.)
$exit
Now you will commit these changes to Docker. This link for committing changes is the best summary and works (skip to Step 4):
https://phoenixnap.com/kb/how-to-commit-changes-to-docker-image#htoc-step-3-modify-the-container
When you re-open the docker image in GNS3 you should now have the ifconfig command usable and whatever other tools or services you added to the container.
Enjoy!
I find Geany (http://geany.uvena.de/) quite good.
I found that this is caused by me having the same namespace name as class name (MyWorld.MyWorld = Namespace.ClassName
).
Change your namespace to a name that is not the same name as your class and this will compile.
Here's a simple single threaded sleep based version that drifts, but tries to auto-correct when it detects drift.
NOTE: This will only work if the following 3 reasonable assumptions are met:
-
from datetime import timedelta
from datetime import datetime
def exec_every_n_seconds(n,f):
first_called=datetime.now()
f()
num_calls=1
drift=timedelta()
time_period=timedelta(seconds=n)
while 1:
time.sleep(n-drift.microseconds/1000000.0)
current_time = datetime.now()
f()
num_calls += 1
difference = current_time - first_called
drift = difference - time_period* num_calls
print "drift=",drift
According to the RFC that introduced the operator, $a <=> $b
evaluates to:
$a == $b
$a < $b
$a > $b
which seems to be the case in practice in every scenario I've tried, although strictly the official docs only offer the slightly weaker guarantee that $a <=> $b
will return
an integer less than, equal to, or greater than zero when
$a
is respectively less than, equal to, or greater than$b
Regardless, why would you want such an operator? Again, the RFC addresses this - it's pretty much entirely to make it more convenient to write comparison functions for usort
(and the similar uasort
and uksort
).
usort
takes an array to sort as its first argument, and a user-defined comparison function as its second argument. It uses that comparison function to determine which of a pair of elements from the array is greater. The comparison function needs to return:
an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
The spaceship operator makes this succinct and convenient:
$things = [
[
'foo' => 5.5,
'bar' => 'abc'
],
[
'foo' => 7.7,
'bar' => 'xyz'
],
[
'foo' => 2.2,
'bar' => 'efg'
]
];
// Sort $things by 'foo' property, ascending
usort($things, function ($a, $b) {
return $a['foo'] <=> $b['foo'];
});
// Sort $things by 'bar' property, descending
usort($things, function ($a, $b) {
return $b['bar'] <=> $a['bar'];
});
More examples of comparison functions written using the spaceship operator can be found in the Usefulness section of the RFC.
I came up with an generic, interesting solution to this problem:
class SafeInvocator(object):
def __init__(self, module):
self._module = module
def _safe(self, func):
def inner(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
return None
return inner
def __getattr__(self, item):
obj = getattr(self.module, item)
return self._safe(obj) if hasattr(obj, '__call__') else obj
and you can use it like so:
safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
# do something
You can use setattr
name = 'varname'
value = 'something'
setattr(self, name, value) #equivalent to: self.varname= 'something'
print (self.varname)
#will print 'something'
But, since you should inform an object to receive the new variable, this only works inside classes or modules.
If your email address is '[email protected]', try changing the createDirectoryEntry() as below.
XYZ is an optional parameter if it exists in mydomain directory
static DirectoryEntry createDirectoryEntry()
{
// create and return new LDAP connection with desired settings
DirectoryEntry ldapConnection = new DirectoryEntry("myname.mydomain.com");
ldapConnection.Path = "LDAP://OU=Users, OU=XYZ,DC=mydomain,DC=com";
ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
return ldapConnection;
}
This will basically check for com -> mydomain -> XYZ -> Users -> abcd
The main function looks as below:
try
{
username = "Firstname LastName"
DirectoryEntry myLdapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(myLdapConnection);
search.Filter = "(cn=" + username + ")";
....
@Lauren?iu Dascalu's answer explains how / why you get a ClassCastException.
Your exception message looks rather suspicious to me, but it might help you to know that "[Lcom.rsa.authagent.authapi.realmstat.AUTHw" means that the actual type of the object that you were trying to cast was com.rsa.authagent.authapi.realmstat.AUTHw[]
; i.e. it was an array object.
Normally, the next steps to solving a problem like this are:
Updating/completing zszep answer:
After copying the request as cUrl (bash), simply import it in the Postman App:
I simply make 2 queries, first to get query output (limit 1) with column names (no hardcode, no problems with Joins, Order by, custom column names, etc), and second to make query itself, and combine files into one CSV file:
CSVHEAD=`/usr/bin/mysql $CONNECTION_STRING -e "$QUERY limit 1;"|head -n1|xargs|sed -e "s/ /'\;'/g"`
echo "\'$CSVHEAD\'" > $TMP/head.txt
/usr/bin/mysql $CONNECTION_STRING -e "$QUERY into outfile '${TMP}/data.txt' fields terminated by ';' optionally enclosed by '\"' escaped by '' lines terminated by '\r\n';"
cat $TMP/head.txt $TMP/data.txt > $TMP/data.csv
just remove the alignItems: 'center'
in the container styles and add textAlign: "center"
to the line1
style like given below.
It will work well
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#F5FCFF',
borderWidth: 1,
}
line1: {
backgroundColor: '#FDD7E4',
textAlign:'center'
},
you can use android:textColor= "
whatever text color u want to give" in xml file where your text view is declared.
Instead of directly decreasing number of days from the date object directly, first get date value then subtract days. See below example:
DateTime SevenDaysFromEndDate = someDate.Value.AddDays(-1);
Here, someDate is a variable of type DateTime.
Use this
openssl ciphers -v | awk '{print $2}' | sort | uniq
Well java.lang.Exception extends java.lang.Throwable. java.io.FileNotFoundException extends java.lang.Exception. So if a method throws java.io.FileNotFoundException then in the override method you cannot throw anything higher up the hierarchy than FileNotFoundException e.g. you can't throw java.lang.Exception. You could throw a subclass of FileNotFoundException though. However you would be forced to handle the FileNotFoundException in the overriden method. Knock up some code and give it a try!
The rules are there so you don't lose the original throws declaration by widening the specificity, as the polymorphism means you can invoke the overriden method on the superclass.
border-color: transparent; border: 1px solid red;
Though this one is obvious, and even mentioned in a way put up by Tom who asked this question. But lets put up again.
NVL can have only 2 arguments. Coalesce may have more than 2.
select nvl('','',1) from dual;
//Result: ORA-00909
: invalid number of arguments
select coalesce('','','1') from dual;
//Output: returns 1
I am a little late for the show but in case the above answer didn't solve the query then I found another way. Simply remove the specific large file from .pack. I had this issue where I checked in a large 2GB file accidentally. I followed the steps explained in this link: http://www.ducea.com/2012/02/07/howto-completely-remove-a-file-from-git-history/
move
in windows is equivalent of mv
command in Linux
del
in windows is equivalent of rm
command in Linux
Use first the method OpenTextFile
, and then...
either read the file at once with the method ReadAll
:
Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll
or line by line with the method ReadLine
:
Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
line = file.Readline
dict.Add row, line
row = row + 1
Loop
file.Close
'Loop over it
For Each line in dict.Items
WScript.Echo line
Next
I think its better to avoid recursion because its costly.
function padLeft(str,size,padwith) {_x000D_
if(size <= str.length) {_x000D_
// not padding is required._x000D_
return str;_x000D_
} else {_x000D_
// 1- take array of size equal to number of padding char + 1. suppose if string is 55 and we want 00055 it means we have 3 padding char so array size should be 3 + 1 (+1 will explain below)_x000D_
// 2- now join this array with provided padding char (padwith) or default one ('0'). so it will produce '000'_x000D_
// 3- now append '000' with orginal string (str = 55), will produce 00055_x000D_
_x000D_
// why +1 in size of array? _x000D_
// it is a trick, that we are joining an array of empty element with '0' (in our case)_x000D_
// if we want to join items with '0' then we should have at least 2 items in the array to get joined (array with single item doesn't need to get joined)._x000D_
// <item>0<item>0<item>0<item> to get 3 zero we need 4 (3+1) items in array _x000D_
return Array(size-str.length+1).join(padwith||'0')+str_x000D_
}_x000D_
}_x000D_
_x000D_
alert(padLeft("59",5) + "\n" +_x000D_
padLeft("659",5) + "\n" +_x000D_
padLeft("5919",5) + "\n" +_x000D_
padLeft("59879",5) + "\n" +_x000D_
padLeft("5437899",5));
_x000D_
an exapansion on Gala's answer that will also include the causes for the exception:
private String extrapolateStackTrace(Exception ex) {
Throwable e = ex;
String trace = e.toString() + "\n";
for (StackTraceElement e1 : e.getStackTrace()) {
trace += "\t at " + e1.toString() + "\n";
}
while (e.getCause() != null) {
e = e.getCause();
trace += "Cause by: " + e.toString() + "\n";
for (StackTraceElement e1 : e.getStackTrace()) {
trace += "\t at " + e1.toString() + "\n";
}
}
return trace;
}
private class GoogleShortenedURLResponse
{
public string id { get; set; }
public string kind { get; set; }
public string longUrl { get; set; }
}
private class GoogleShortenedURLRequest
{
public string longUrl { get; set; }
}
public ActionResult Index1()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ShortenURL(string longurl)
{
string googReturnedJson = string.Empty;
JavaScriptSerializer javascriptSerializer = new JavaScriptSerializer();
GoogleShortenedURLRequest googSentJson = new GoogleShortenedURLRequest();
googSentJson.longUrl = longurl;
string jsonData = javascriptSerializer.Serialize(googSentJson);
byte[] bytebuffer = Encoding.UTF8.GetBytes(jsonData);
WebRequest webreq = WebRequest.Create("https://www.googleapis.com/urlshortener/v1/url");
webreq.Method = WebRequestMethods.Http.Post;
webreq.ContentLength = bytebuffer.Length;
webreq.ContentType = "application/json";
using (Stream stream = webreq.GetRequestStream())
{
stream.Write(bytebuffer, 0, bytebuffer.Length);
stream.Close();
}
using (HttpWebResponse webresp = (HttpWebResponse)webreq.GetResponse())
{
using (Stream dataStream = webresp.GetResponseStream())
{
using (StreamReader reader = new StreamReader(dataStream))
{
googReturnedJson = reader.ReadToEnd();
}
}
}
//GoogleShortenedURLResponse googUrl = javascriptSerializer.Deserialize<googleshortenedurlresponse>(googReturnedJson);
//ViewBag.ShortenedUrl = googUrl.id;
return View();
}
When you use Vector *one
you are merely creating a pointer to the structure but there is no memory allocated to it.
Simply use one = (Vector *)malloc(sizeof(Vector));
to declare memory and instantiate it.
This worked in ubuntu 16.04 for python 2.7:
sudo pip install mysql-connector
You can use the ui
object provided to the events, specifically you want the stop
event, the ui.item
property and .index()
, like this:
$("#sortable").sortable({
stop: function(event, ui) {
alert("New position: " + ui.item.index());
}
});
You can see a working demo here, remember the .index()
value is zero-based, so you may want to +1 for display purposes.
You can put the data in a file and re-direct it like this:
$ cat file.sh
#!/bin/bash
read x
read y
echo $x
echo $y
Data for the script:
$ cat data.txt
2
3
Executing the script:
$ file.sh < data.txt
2
3
Adding the following to my stored procedure, solved the time out error by me:
SET NOCOUNT ON;
SET ARITHABORT ON;
class Second:
def __init__(self, data):
self.data = data
class First:
def SecondClass(self, data):
return Second(data)
FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data
The above answers are nice.You can also go like this programmatically if you want
First, your layout should have an ID. Add it by writing following +id
line in res/layout/*.xml
<RelativeLayout ...
...
android:id="@+id/your_layout_id"
...
</RelativeLayout>
Then, in your Java code, make following changes.
RelativeLayout rl = (RelativeLayout)findViewById(R.id.your_layout_id);
rl.setBackgroundColor(Color.RED);
apart from this, if you have the color defined in colors.xml, then also you can do programmatically :
rl.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.red));
On Linux Mint 17.1 Rebecca - Call to undefined function mcrypt_create_iv...
Solved by adding the following line to the php.ini
extension=mcrypt.so
After that a
service apache2 restart
solved it...
function compare(propName) {
return function(a,b) {
if (a[propName] < b[propName])
return -1;
if (a[propName] > b[propName])
return 1;
return 0;
};
}
objs.sort(compare("last_nom"));
window.open
will open a new browser with the specified URL.
window.location.href
will open the URL in the window in which the code is called.
Note also that window.open()
is a function on the window object itself whereas window.location
is an object that exposes a variety of other methods and properties.
Well, here's my version of confirm
, modified from James' one:
function confirm() {
local response msg="${1:-Are you sure} (y/[n])? "; shift
read -r $* -p "$msg" response || echo
case "$response" in
[yY][eE][sS]|[yY]) return 0 ;;
*) return 1 ;;
esac
}
These changes are:
local
to prevent variable names from collidingread
use $2 $3 ...
to control its action, so you may use -n
and -t
read
exits unsuccessfully, echo
a line feed for beautyGit on Windows
only has bash-3.1
and has no true
or false
, so use return
instead. Of course, this is also compatible with bash-4.4 (the current one in Git for Windows).Adding on to @Alexandre Aimbiré
's answer - sometimes you may need to specify z-index:1
to have the element always on top while scrolling.
Like this:
position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
z-index: 1;
why not pull the data directly out of the data source.
DataBinder.Eval(e.Row.DataItem, "ColumnName")
Start with this:
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
msg = path & " exists."
Else
msg = path & " doesn't exist."
End If
Taken from the documentation.
file_put_contents($file, print_r($array, true), FILE_APPEND)
The problem is that --exclude="*"
says to exclude (for example) the 1260000000/
directory, so rsync
never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include
.
I think the closest thing to what you want is this:
rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
(which will include all directories, and all files matching file_11*.jpg
, but no other files), or maybe this:
rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/
(same concept, but much pickier about the directories it will include).
Try this:
$('#contact-form input[type="text"]').val('');
$('#contact-form textarea').val('');
val is immutable
and var is mutable
in Kotlin.
DON'T FORGET - Use parseFloat();
if your dealing with decimals.
As the answer of 'sepehr' this issues are because of VC++ Redistributable suitable version for PHP are not installed or need to be reinstalled again.
I faced it before so i'll explain my steps to fix it.
1- Each PHP version is built by a specific Visual C++ Redistributable version like (10, 11,12,14,..) what ever. ((How you know!! look.. ))
Check back enter link description here The PHP Site then at the left side of this page, look at "Which version do I choose?" then see what version of VC++ is fits your PHP version installed.
Now YOU HAVE TO Download both of VC++ 32 and 64. and if your PC has it already then Unistall them first. and then install what you downloaded recently bu (first 32 then 64).
- VC download links are exists on the mentioned PHP Site on the left side also.
I hope it helps you.
Example:
SELECT TRIM(' Sample ');
Result: 'Sample'
UPDATE TableName SET ColumnName = TRIM(ColumnName)
I faced same issue apply all possible solution but finally this solve my problem
export class AppRoutingModule {
constructor(private router: Router) {
this.router.errorHandler = (error: any) => {
this.router.navigate(['404']); // or redirect to default route
}
}
}
Hope this will help you.
You can easily add multiple classes to divs... So:
<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>
Then in the CSS call to the share class to apply the same styles:
.myclass {...}
And you can still use your other classes like this:
.myclass-three {...}
Or if you want to be more specific in the CSS like this:
.myclass.myclass-three {...}
getRandom (min, max) {
return Math.floor(Math.random() * (max - min)) + min
}
getNRandom (min, max, n) {
const numbers = []
if (min > max) {
return new Error('Max is gt min')
}
if (min === max) {
return [min]
}
if ((max - min) >= n) {
while (numbers.length < n) {
let rand = this.getRandom(min, max + 1)
if (numbers.indexOf(rand) === -1) {
numbers.push(rand)
}
}
}
if ((max - min) < n) {
for (let i = min; i <= max; i++) {
numbers.push(i)
}
}
return numbers
}
To achieve the 360 degree rotation, here is the Working Solution.
The HTML:
<img class="image" src="your-image.png">
The CSS:
.image {
overflow: hidden;
transition-duration: 0.8s;
transition-property: transform;
}
.image:hover {
transform: rotate(360deg);
-webkit-transform: rotate(360deg);
}
You have to hover on the image and you will get the 360 degree rotation effect.
PS: Add a -webkit-
extension for it to work on chrome and other webkit browers. You can check the updated fiddle for webkit HERE
If you want to set styles of all elements in body you should use next code^
body{
color: green;
}
I use this:
jQuery Plugin
(function($){
$.fn.getFormData = function(){
var data = {};
var dataArray = $(this).serializeArray();
for(var i=0;i<dataArray.length;i++){
data[dataArray[i].name] = dataArray[i].value;
}
return data;
}
})(jQuery);
HTML Form
<form id='myform'>
<input name='myVar1' />
<input name='myVar2' />
</form>
Get the Data
var myData = $("#myForm").getFormData();
You asked:
wouldn't it be easier to just accept JSON object through normal $_POST and then respond in JSON as well
From the Wikipedia on REST:
RESTful applications maximize the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimize the addition of new application-specific features on top of it
From what (little) I've seen, I believe this is usually accomplished by maximizing the use of existing HTTP verbs, and designing a URL scheme for your service that is as powerful and self-evident as possible.
Custom data protocols (even if they are built on top of standard ones, such as SOAP or JSON) are discouraged, and should be minimized to best conform to the REST ideology.
SOAP RPC over HTTP, on the other hand, encourages each application designer to define a new and arbitrary vocabulary of nouns and verbs (for example getUsers(), savePurchaseOrder(...)), usually overlaid onto the HTTP 'POST' verb. This disregards many of HTTP's existing capabilities such as authentication, caching and content type negotiation, and may leave the application designer re-inventing many of these features within the new vocabulary.
The actual objects you are working with can be in any format. The idea is to reuse as much of HTTP as possible to expose your operations the user wants to perform on those resource (queries, state management/mutation, deletion).
You asked:
Am I missing something?
There is a lot more to know about REST and the URI syntax/HTTP verbs themselves. For example, some of the verbs are idempotent, others aren't. I didn't see anything about this in your question, so I didn't bother trying to dive into it. The other answers and Wikipedia both have a lot of good information.
Also, there is a lot to learn about the various network technologies built on top of HTTP that you can take advantage of if you're using a truly restful API. I'd start with authentication.
It's actually best just to use Apple's implementation, as provided in the docs. However, the code they provide is faulty. Replace the portion found in keyboardWasShown:
just below the comments to the following:
NSDictionary* info = [aNotification userInfo];
CGRect keyPadFrame=[[UIApplication sharedApplication].keyWindow convertRect:[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue] fromView:self.view];
CGSize kbSize =keyPadFrame.size;
CGRect activeRect=[self.view convertRect:activeField.frame fromView:activeField.superview];
CGRect aRect = self.view.bounds;
aRect.size.height -= (kbSize.height);
CGPoint origin = activeRect.origin;
origin.y -= backScrollView.contentOffset.y;
if (!CGRectContainsPoint(aRect, origin)) {
CGPoint scrollPoint = CGPointMake(0.0,CGRectGetMaxY(activeRect)-(aRect.size.height));
[backScrollView setContentOffset:scrollPoint animated:YES];
}
The problems with Apple's code are these:
(1) They always calculate if the point is within the view's frame, but it's a ScrollView
, so it may already have scrolled and you need to account for that offset:
origin.y -= scrollView.contentOffset.y
(2) They shift the contentOffset by the height of the keyboard, but we want the opposite (we want to shift the contentOffset
by the height that is visible on the screen, not what isn't):
activeField.frame.origin.y-(aRect.size.height)
Yes, I also found it here: http://developer.android.com/tools/testing/activity_testing.html It's seems a key-input protection mechanism which includes the screen-lock, but not only includes it. According to this webpage, it also defines some key-input restriction for auto-test framework in Android.
What do you even want the result to be? 888888? If so, just remove the spaces with str_replace
, then convert.
$.getJSON("example.json", function() {_x000D_
alert("success");_x000D_
})_x000D_
.success(function() { alert("second success"); })_x000D_
.error(function() { alert("error"); })
_x000D_
It is fixed in jQuery 2.x; In jQuery 1.x you will never get an error callback
I've made basic black launch screens that will make the app scale properly on the iPhone 6 and iPhone 6+:
If you already have a LaunchImage in your .xcassett, open it, switch to the third tab in the right menu in Xcode and tick the iOS 8.0 iPhone images to add them to the existing set. Then drag the images over:
$("#elementwithhover").click(function() {
// code that makes element or parent slide or otherwise move out from under mouse.
$(this).clone(true).insertAfter($(this));
$(this).remove();
});
This is the job for style
property:
document.getElementById("remember").style.visibility = "visible";
The simplest solution might be to limit the number of characters in the HTML itself. Rails has a truncate(string, length) helper, and I'm certain that whichever backend you're using provides something similar.
Due to the cross-browser issues you're already familiar with regarding the width of select boxes, this seems to me to be the most straightforward and least error-prone option.
<select>
<option value="1">One</option>
<option value="100">One hund...</option>
<select>
Try This :
**ob_start();**
include('header.php');
$name = $_POST['name'];
$score = $_POST['score'];
$dept = $_POST['dept'];
$MyDB->prep("INSERT INTO demo (`id`,`name`,`score`,`dept`, `date`) VALUES ('','$name','$score','$dept','$date')");
// Bind a value to our :id hook
// Produces: SELECT * FROM demo_table WHERE id = '23'
$MyDB->bind(':date', $date);
// Run the query
$MyDB->run();
header('Location:index.php');
**ob_end_flush();**
exit;
create table like this,
CommentId UserId
---------------------
1 usr1
1 usr2
In this way you can check whether the user posted the comments are not..
Apart from this there should be tables for Comments
and Users
with respective id's
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
Here is an alternative to sleep:
Sub TDelay(delay As Long)
Dim n As Long
For n = 1 To delay
DoEvents
Next n
End Sub
In the following code I make a "glow" effect blink on a spin button to direct users to it if they are "having trouble", using "sleep 1000" in the loop resulted in no visible blinking, but the loop is working great.
Sub SpinFocus()
Dim i As Long
For i = 1 To 3 '3 blinks
Worksheets(2).Shapes("SpinGlow").ZOrder (msoBringToFront)
TDelay (10000) 'this makes the glow stay lit longer than not, looks nice.
Worksheets(2).Shapes("SpinGlow").ZOrder (msoSendBackward)
TDelay (100)
Next i
End Sub
I also used bcp and found a couple other helpful posts that would benefit others if finding this thread
Don't use VARCHAR(MAX)
as your @sql
or @cmd
variable for xp_cmdshell; you will get and error
Msg 214, Level 16, State 201, Procedure xp_cmdshell, Line 1 Procedure expects parameter 'command_string' of type 'varchar'.
http://www.sqlservercentral.com/Forums/Topic1071530-338-1.aspx
Use NULLIF
to get blanks for the csv file instead of a NUL
(viewable in hex editor, or notepad++). I used that in the SELECT
statement for bcp
How to make Microsoft BCP export empty string instead of a NUL char?
That can be achieve in plain LaTeX without any specific package.
\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
\left\{
\begin{array}{l}
0\\
1
\end{array}
\right.
\end{math}
\end{document}
This code produces something which looks what you seems to need.
The same example as in the @Tombart can be obtained with similar code.
\documentclass{article}
\begin{document}
\begin{math}
f(x)=\left\{
\begin{array}{ll}
1, & \mbox{if $x<0$}.\\
0, & \mbox{otherwise}.
\end{array}
\right.
\end{math}
\end{document}
This code produces very similar results.
Use the AsyncTask class (instead of Runnable). It has a method called onProgressUpdate which can affect the UI (it's invoked in the UI thread).
IBM has some more documentation on how to use this. Briefly, you're using the pointer as an offset into the class. You can't use these pointers apart from the class they refer to, so:
int Car::*pSpeed = &Car::speed;
Car mycar;
mycar.*pSpeed = 65;
It seems a little obscure, but one possible application is if you're trying to write code for deserializing generic data into many different object types, and your code needs to handle object types that it knows absolutely nothing about (for example, your code is in a library, and the objects into which you deserialize were created by a user of your library). The member pointers give you a generic, semi-legible way of referring to the individual data member offsets, without having to resort to typeless void * tricks the way you might for C structs.
This comment syntax should work for you:
@* enter comments here *@
I had the same problem. The problem, by some strange reason Chrome turned himself as the default tool to open a mailto: link. The solution, put your mail client as the default app to open it. How to : http://windows.microsoft.com/en-nz/windows/change-default-programs#1TC=windows-7
Good luck
I had a similar problem.
My Problem:
I want to calculate an SVD and need to sort my eigenvalues in descending order. But I want to keep the mapping between eigenvalues and eigenvectors. My eigenvalues were in the first row and the corresponding eigenvector below it in the same column.
So I want to sort a two-dimensional array column-wise by the first row in descending order.
My Solution
a = a[::, a[0,].argsort()[::-1]]
So how does this work?
a[0,]
is just the first row I want to sort by.
Now I use argsort to get the order of indices.
I use [::-1]
because I need descending order.
Lastly I use a[::, ...]
to get a view with the columns in the right order.
As an alternative (mostly on aesthetics) to Ted Petrou's answer, I found I preferred a slightly more compact listing. Please don't consider accepting it, it's just a much-more-detailed comment on Ted's answer, plus code/data. Python/pandas is not my first/best, but I found this to read well:
df.groupby('group') \
.apply(lambda x: pd.Series({
'a_sum' : x['a'].sum(),
'a_max' : x['a'].max(),
'b_mean' : x['b'].mean(),
'c_d_prodsum' : (x['c'] * x['d']).sum()
})
)
a_sum a_max b_mean c_d_prodsum
group
0 0.530559 0.374540 0.553354 0.488525
1 1.433558 0.832443 0.460206 0.053313
I find it more reminiscent of dplyr
pipes and data.table
chained commands. Not to say they're better, just more familiar to me. (I certainly recognize the power and, for many, the preference of using more formalized def
functions for these types of operations. This is just an alternative, not necessarily better.)
I generated data in the same manner as Ted, I'll add a seed for reproducibility.
import numpy as np
np.random.seed(42)
df = pd.DataFrame(np.random.rand(4,4), columns=list('abcd'))
df['group'] = [0, 0, 1, 1]
df
a b c d group
0 0.374540 0.950714 0.731994 0.598658 0
1 0.156019 0.155995 0.058084 0.866176 0
2 0.601115 0.708073 0.020584 0.969910 1
3 0.832443 0.212339 0.181825 0.183405 1
To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):
import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"
evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)
in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script
. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.
What to do to correct this is create a file called php.ini and save it in the same location as your .htaccess file and enter the following code instead:
upload_max_filesize = "250M"
post_max_size = "250M"
For those who are using web servers make sure that the bcprov-jdk16-145.jar has been installed in you servers lib, for weblogic had to put the jar in:
<weblogic_jdk_home>\jre\lib\ext
should avoid using unstable npm version.
I observed one thing that is npm version based issue, npm version 4.6.1 is the stable one but 5.x is unstable because package.json will be configured perfectly while creating with default template if it's a stable version and so we manually don't need to add that scripts.
I got the below issue on the npm 5 so I downgraded to npm 4.6.1 then its worked for me,
ERROR: npm 5 is not supported yet
It looks like you're using npm 5 which was recently released.
Create React Native App doesn't work with npm 5 yet, unfortunately. We recommend using npm 4 or yarn until some bugs are resolved.
You can follow the known issues with npm 5 at: https://github.com/npm/npm/issues/16991
Devas-MacBook-Air:SampleTestApp deva$ npm start npm ERR! missing script: start
Code Snippet1:
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray * values = [dictionary allValues];
[array addObject:values];
Code Snippet2: If you want to add further
[array addObject:value1];
[array addObject:value2];
[array addObject:value3];
And so on
Also you can store key values of dictionary to array
NSArray *keys = [dictionary allKeys];
EF 4.1 to EF 6
There is a strongly typed .Include
which allows the required depth of eager loading to be specified by providing Select expressions to the appropriate depth:
using System.Data.Entity; // NB!
var company = context.Companies
.Include(co => co.Employees.Select(emp => emp.Employee_Car))
.Include(co => co.Employees.Select(emp => emp.Employee_Country))
.FirstOrDefault(co => co.companyID == companyID);
The Sql generated is by no means intuitive, but seems performant enough. I've put a small example on GitHub here
EF Core
EF Core has a new extension method, .ThenInclude()
, although the syntax is slightly different:
var company = context.Companies
.Include(co => co.Employees)
.ThenInclude(emp => emp.Employee_Car)
.Include(co => co.Employees)
.ThenInclude(emp => emp.Employee_Country)
With some notes
Employees.Employee_Car
and Employees.Employee_Country
), if you need to include 2 or more child properties of an intermediate child collection, you'll need to repeat the .Include
navigation for the collection for each child of the collection..ThenInclude
to preserve your sanity.As of Laravel 5.2+, you can fetch it directly with $request->input('item')
as well.
Retrieving JSON Input Values
When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig deeper into JSON arrays:
$name = $request->input('user.name');
https://laravel.com/docs/5.2/requests
As noted above, the content-type header must be set to application/json
so the jQuery ajax call would need to include contentType: "application/json",
$.ajax({
type: "POST",
url: "/people",
data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
dataType: "json",
contentType: "application/json",
success:function(data) {
$('#save_message').html(data.message);
}
});
By fixing the AJAX call, $request->all()
should work.
Simply call list
on the generator.
lst = list(gen)
lst
Be aware that this affects the generator which will not return any further items.
You also cannot directly call list
in IPython, as it conflicts with a command for listing lines of code.
Tested on this file:
def gen():
yield 1
yield 2
yield 3
yield 4
yield 5
import ipdb
ipdb.set_trace()
g1 = gen()
text = "aha" + "bebe"
mylst = range(10, 20)
which when run:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.
There are debugger commands p
and pp
that will print
and prettyprint
any expression following them.
So you could use it as follows:
$ python code.py
> /home/javl/sandbox/so/debug/code.py(10)<module>()
9
---> 10 g1 = gen()
11
ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
11
---> 12 text = "aha" + "bebe"
13
ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c
There is also an exec
command, called by prefixing your expression with !
, which forces debugger to take your expression as Python one.
ipdb> !list(g1)
[]
For more details see help p
, help pp
and help exec
when in debugger.
ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']
Your query contains columns which could be present with the same name in more than one table you are referencing, hence the not unique error. It's best if you make the references explicit and/or use table aliases when joining.
Try
SELECT pa.ProjectID, p.Project_Title, a.Account_ID, a.Username, a.Access_Type, c.First_Name, c.Last_Name
FROM Project_Assigned pa
INNER JOIN Account a
ON pa.AccountID = a.Account_ID
INNER JOIN Project p
ON pa.ProjectID = p.Project_ID
INNER JOIN Clients c
ON a.Account_ID = c.Account_ID
WHERE a.Access_Type = 'Client';
Just to add a note, since I can't comment without 50+ rep...
If you have FIPS enabled on the server, it doesn't allow you to create users. Because IIS v8 (and lower I would imagine) does not use FIPS encryption algorithms. It would be great if it supported it , because obviously a user account in windows is insecure compared to a virtual user mapped to an isolated folder. Too bad.
In bash version 4 associative arrays were introduced.
declare -A arr
arr["key1"]=val1
arr+=( ["key2"]=val2 ["key3"]=val3 )
The arr array now contains the three key value pairs. Bash is fairly limited what you can do with them though, no sorting or popping etc.
for key in ${!arr[@]}; do
echo ${key} ${arr[${key}]}
done
Will loop over all key values and echo them out.
Note: Bash 4 does not come with Mac OS X because of its GPLv3 license; you have to download and install it. For more on that see here
used a reference like "///<reference path="web.ts" />
and then in the VS2013 project properties for building "app.ts","Typescript Build"->"Combine javascript output into file:"(checked)->"app.js"
To include a file one directory back, use '../file'
.
For two directories back, use '../../file'
.
And so on.
Although, realistically you shouldn't be performing includes relative to the current directory. What if you wanted to move that file? All of the links would break. A way to ensure that you can still link to other files, while retaining those links if you move your file, is:
require_once($_SERVER['DOCUMENT_ROOT'] . 'directory/directory/file');
DOCUMENT_ROOT
is a server variable that represents the base directory that your code is located within.
I made some optimization in the row, col, diagonal checks. Its mainly decided in the first nested loop if we need to check a particular column or diagonal. So, we avoid checking of columns or diagonals saving time. This makes big impact when the board size is more and a significant number of the cells are not filled.
Here is the java code for that.
int gameState(int values[][], int boardSz) {
boolean colCheckNotRequired[] = new boolean[boardSz];//default is false
boolean diag1CheckNotRequired = false;
boolean diag2CheckNotRequired = false;
boolean allFilled = true;
int x_count = 0;
int o_count = 0;
/* Check rows */
for (int i = 0; i < boardSz; i++) {
x_count = o_count = 0;
for (int j = 0; j < boardSz; j++) {
if(values[i][j] == x_val)x_count++;
if(values[i][j] == o_val)o_count++;
if(values[i][j] == 0)
{
colCheckNotRequired[j] = true;
if(i==j)diag1CheckNotRequired = true;
if(i + j == boardSz - 1)diag2CheckNotRequired = true;
allFilled = false;
//No need check further
break;
}
}
if(x_count == boardSz)return X_WIN;
if(o_count == boardSz)return O_WIN;
}
/* check cols */
for (int i = 0; i < boardSz; i++) {
x_count = o_count = 0;
if(colCheckNotRequired[i] == false)
{
for (int j = 0; j < boardSz; j++) {
if(values[j][i] == x_val)x_count++;
if(values[j][i] == o_val)o_count++;
//No need check further
if(values[i][j] == 0)break;
}
if(x_count == boardSz)return X_WIN;
if(o_count == boardSz)return O_WIN;
}
}
x_count = o_count = 0;
/* check diagonal 1 */
if(diag1CheckNotRequired == false)
{
for (int i = 0; i < boardSz; i++) {
if(values[i][i] == x_val)x_count++;
if(values[i][i] == o_val)o_count++;
if(values[i][i] == 0)break;
}
if(x_count == boardSz)return X_WIN;
if(o_count == boardSz)return O_WIN;
}
x_count = o_count = 0;
/* check diagonal 2 */
if( diag2CheckNotRequired == false)
{
for (int i = boardSz - 1,j = 0; i >= 0 && j < boardSz; i--,j++) {
if(values[j][i] == x_val)x_count++;
if(values[j][i] == o_val)o_count++;
if(values[j][i] == 0)break;
}
if(x_count == boardSz)return X_WIN;
if(o_count == boardSz)return O_WIN;
x_count = o_count = 0;
}
if( allFilled == true)
{
for (int i = 0; i < boardSz; i++) {
for (int j = 0; j < boardSz; j++) {
if (values[i][j] == 0) {
allFilled = false;
break;
}
}
if (allFilled == false) {
break;
}
}
}
if (allFilled)
return DRAW;
return INPROGRESS;
}
This is a corner image
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/img_main_blue"
android:bottom="5dp"
android:left="5dp"
android:right="5dp"
android:top="5dp" />
<item>
<shape
android:padding="10dp"
android:shape="rectangle">
<corners android:radius="10dp" />
<stroke
android:width="5dp"
android:color="@color/white" />
</shape>
</item>
</layer-list>
I didn't understand why my this didn't work but I found out that this setting is now also under the programming language itself at:
'Editor' | 'Code Style' | < your language > | 'Wrapping and Braces' | 'Right margin (columns)'
There are differences between
ABSTRAACTION
and
ENCAPSULATION
1. First difference between Abstraction and Encapsulation is that, Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.
2. Data abstraction simply means generalizing something to hide the complex logic that goes underneath where Encapsulation is DATA HIDING.
3. Encapsulation is combining related logic data (variables and methods) where as Abstraction is hiding internal implementation details and expose only relevant details to the user. In a way you can Abstraction is achieved by Encapsulation.
Perhaps it is late for the party. But there is an alternative solution for this is to use ApiMultipartFormFormatter plugin.
This plugin helps you to receive the multipart/formdata content as ASP.NET Core does.
In the github page, demo is already provided.
To replace anything that starts with "text" until the last character:
text.+(.*)$
Example
text hsjh sdjh sd jhsjhsdjhsdj hsd ^ last character
text.+(\ 123)
Example
text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e ^ ^ From here To here
SELECT *
FROM (
SELECT q.*, rownum rn
FROM (
SELECT *
FROM maps006
ORDER BY
id
) q
)
WHERE rn BETWEEN 50 AND 100
Note the double nested view. ROWNUM
is evaluated before ORDER BY
, so it is required for correct numbering.
If you omit ORDER BY
clause, you won't get consistent order.