Import namespace :
using System.Configuration;
Create ConfigurationElement Company :
public class Company : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true)]
public string Name
{
get
{
return this["name"] as string;
}
}
[ConfigurationProperty("code", IsRequired = true)]
public string Code
{
get
{
return this["code"] as string;
}
}
}
ConfigurationElementCollection:
public class Companies
: ConfigurationElementCollection
{
public Company this[int index]
{
get
{
return base.BaseGet(index) as Company ;
}
set
{
if (base.BaseGet(index) != null)
{
base.BaseRemoveAt(index);
}
this.BaseAdd(index, value);
}
}
public new Company this[string responseString]
{
get { return (Company) BaseGet(responseString); }
set
{
if(BaseGet(responseString) != null)
{
BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
}
BaseAdd(value);
}
}
protected override System.Configuration.ConfigurationElement CreateNewElement()
{
return new Company();
}
protected override object GetElementKey(System.Configuration.ConfigurationElement element)
{
return ((Company)element).Name;
}
}
and ConfigurationSection:
public class RegisterCompaniesConfig
: ConfigurationSection
{
public static RegisterCompaniesConfig GetConfig()
{
return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
}
[System.Configuration.ConfigurationProperty("Companies")]
[ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
public Companies Companies
{
get
{
object o = this["Companies"];
return o as Companies ;
}
}
}
and you must also register your new configuration section in web.config (app.config):
<configuration>
<configSections>
<section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>
then you load your config with
var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
do something ..
}
So I ended up taking a slightly different approach. I followed Dan's steps through step 3, but added another file: App.Base.Config. This file contains the configuration settings you want in every generated App.Config. Then I use BeforeBuild (with Yuri's addition to TransformXml) to transform the current configuration with the Base config into the App.config. The build process then uses the transformed App.config as normal. However, one annoyance is you kind of want to exclude the ever-changing App.config from source control afterwards, but the other config files are now dependent upon it.
<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
<Target Name="BeforeBuild" Condition="exists('app.$(Configuration).config')">
<TransformXml Source="App.Base.config" Transform="App.$(Configuration).config" Destination="App.config" />
</Target>
This worked for me:
string connection = System.Configuration.ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
Outputs:
Data Source=.;Initial Catalog=OmidPayamak;IntegratedSecurity=True"
Thanks Jahmic for the answer. Worked properly for me.
another useful code snippet that read the values and return a string:
public static string ReadSetting(string key)
{
System.Configuration.Configuration cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
System.Configuration.AppSettingsSection appSettings = (System.Configuration.AppSettingsSection)cfg.GetSection("appSettings");
return appSettings.Settings[key].Value;
}
You can have separate configuration file, but you'll have to read it "manually", the ConfigurationManager.AppSettings["key"]
will read only the config of the running assembly.
Assuming you're using Visual Studio as your IDE, you can right click the desired project ? Add ? New item ? Application Configuration File
This will add App.config
to the project folder, put your settings in there under <appSettings>
section. In case you're not using Visual Studio and adding the file manually, make sure to give it such name: DllName.dll.config, otherwise the below code won't work properly.
Now to read from this file have such function:
string GetAppSetting(Configuration config, string key)
{
KeyValueConfigurationElement element = config.AppSettings.Settings[key];
if (element != null)
{
string value = element.Value;
if (!string.IsNullOrEmpty(value))
return value;
}
return string.Empty;
}
And to use it:
Configuration config = null;
string exeConfigPath = this.GetType().Assembly.Location;
try
{
config = ConfigurationManager.OpenExeConfiguration(exeConfigPath);
}
catch (Exception ex)
{
//handle errror here.. means DLL has no sattelite configuration file.
}
if (config != null)
{
string myValue = GetAppSetting(config, "myKey");
...
}
You'll also have to add reference to System.Configuration namespace in order to have the ConfigurationManager class available.
When building the project, in addition to the DLL you'll have DllName.dll.config
file as well, that's the file you have to publish with the DLL itself.
The above is basic sample code, for those interested in a full scale example, please refer to this other answer.
As Marc says, this is not possible (although Visual Studio allows you to add an application configuration file in a class library project).
You might want to check out the AssemblySettings class which seems to make assembly config files possible.
Here's an explanation I wrote recently to help with the void of information on this attribute. http://www.marklio.com/marklio/PermaLink,guid,ecc34c3c-be44-4422-86b7-900900e451f9.aspx (Internet Archive Wayback Machine link)
To quote the most relevant bits:
[Installing .NET] v4 is “non-impactful”. It should not change the behavior of existing components when installed.
The useLegacyV2RuntimeActivationPolicy attribute basically lets you say, “I have some dependencies on the legacy shim APIs. Please make them work the way they used to with respect to the chosen runtime.”
Why don’t we make this the default behavior? You might argue that this behavior is more compatible, and makes porting code from previous versions much easier. If you’ll recall, this can’t be the default behavior because it would make installation of v4 impactful, which can break existing apps installed on your machine.
The full post explains this in more detail. At RTM, the MSDN docs on this should be better.
Your unit tests are considered as an environment that runs your code to test it. Just like any normal environment, you have i.e. staging/production. You may need to add a .config
file for your test project as well. A workaround is to create a class library and convert it to Test Project by adding necessary NuGet packages such as NUnit and NUnit Adapter. it works perfectly fine with both Visual Studio Test Runner and Resharper and you have your app.config
file in your test project.
And finally debugged my test and value from App.config
:
Here's the full use-case for ASP.NET Core!
articles.json
{
"shownArticlesCount": 3,
"articles": [
{
"title": "My Title 1",
"thumbnailLink": "example.com/img1.png",
"authorProfileLink": "example.com/@@alper",
"authorName": "Alper Ebicoglu",
"publishDate": "2018-04-17",
"text": "...",
"link": "..."
},
{
"title": "My Title 2",
"thumbnailLink": "example.com/img2.png",
"authorProfileLink": "example.com/@@alper",
"authorName": "Alper Ebicoglu",
"publishDate": "2018-04-17",
"text": "...",
"link": "..."
},
]
}
ArticleContainer.cs
public class ArticleContainer
{
public int ShownArticlesCount { get; set; }
public List<Article> Articles { get; set; }
}
public class Article
{
public string Title { get; set; }
public string ThumbnailLink { get; set; }
public string AuthorName { get; set; }
public string AuthorProfileLink { get; set; }
public DateTime PublishDate { get; set; }
public string Text { get; set; }
public string Link { get; set; }
}
Startup.cs
public class Startup
{
public IConfigurationRoot ArticleConfiguration { get; set; }
public Startup(IHostingEnvironment env)
{
ArticleConfiguration = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("articles.json")
.Build();
}
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.Configure<ArticleContainer>(ArticleConfiguration);
}
}
Index.cshtml.cs
public class IndexModel : PageModel
{
public ArticleContainer ArticleContainer { get;set; }
private readonly IOptions<ArticleContainer> _articleContainer;
public IndexModel(IOptions<ArticleContainer> articleContainer)
{
_articleContainer = articleContainer;
}
public void OnGet()
{
ArticleContainer = _articleContainer.Value;
}
}
Index.cshtml.cs
<h1>@Model.ArticleContainer.ShownArticlesCount</h1>
You could have them semi-colon delimited in a single value, e.g.
App.config
<add key="paths" value="C:\test1;C:\test2;C:\test3" />
C#
var paths = new List<string>(ConfigurationManager.AppSettings["paths"].Split(new char[] { ';' }));
You normally define your connection strings in Web.config. After generating the edmx the connection string will get stored in the App.Config. If you want to change the connection string go to the app.config and remove all the connection strings. Now go to the edmx, right click on the designer surface, select Update model from database, choose the connection string from the dropdown, Click next, Add or Refresh (select what you want) and finish.
In the output window it will show something like this,
Generated model file: UpostDataModel.edmx. Loading metadata from the database took 00:00:00.4258157. Generating the model took 00:00:01.5623765. Added the connection string to the App.Config file.
I've had a similar requirement: I needed to inject a Spring-managed repository bean into my Person
entity class ("entity" as in "something with an identity", for example an JPA entity). A Person
instance has friends, and for this Person
instance to return its friends, it shall delegate to its repository and query for friends there.
@Entity
public class Person {
private static PersonRepository personRepository;
@Id
@GeneratedValue
private long id;
public static void setPersonRepository(PersonRepository personRepository){
this.personRepository = personRepository;
}
public Set<Person> getFriends(){
return personRepository.getFriends(id);
}
...
}
.
@Repository
public class PersonRepository {
public Person get Person(long id) {
// do database-related stuff
}
public Set<Person> getFriends(long id) {
// do database-related stuff
}
...
}
So how did I inject that PersonRepository
singleton into the static field of the Person
class?
I created a @Configuration
, which gets picked up at Spring ApplicationContext construction time. This @Configuration
gets injected with all those beans that I need to inject as static fields into other classes. Then with a @PostConstruct
annotation, I catch a hook to do all static field injection logic.
@Configuration
public class StaticFieldInjectionConfiguration {
@Inject
private PersonRepository personRepository;
@PostConstruct
private void init() {
Person.setPersonRepository(personRepository);
}
}
I thought I just saw this question.
In short, no, there's no variable interpolation within an application configuration.
You have two options
An easier alternative for those who would prefer not to write all that configuration boilerplate manually...
1) Install Nerdle.AutoConfig from NuGet
2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)
public interface IServiceConfiguration
{
int Port { get; }
ReportType ReportType { get; }
}
3) You'll need a type to hold the collection, e.g.
public interface IServiceCollectionConfiguration
{
IEnumerable<IServiceConfiguration> Services { get; }
}
4) Add the config section like so (note camelCase naming)
<configSections>
<section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>
<serviceCollection>
<services>
<service port="6996" reportType="File" />
<service port="7001" reportType="Other" />
</services>
</serviceCollection>
5) Map with AutoConfig
var services = AutoConfig.Map<IServiceCollectionConfiguration>();
You can access keys in the App.Config using:
ConfigurationSettings.AppSettings["KeyName"]
Take alook at this Thread
If you mean you are only getting a null return when you use NUnit, then you probably need to copy the ConnectionString value the your app.config of your application to the app.config of your test library.
When it is run by the test loader, the test assembly is loaded at runtime and will look in its own app.config (renamed to testAssembly.dll.config at compile time) rather then your applications config file.
To get the location of the assembly you're running, try
System.Reflection.Assembly.GetExecutingAssembly().Location
MyServiceClient client = new MyServiceClient(binding, endpoint);
client.Endpoint.Address = new EndpointAddress("net.tcp://localhost/webSrvHost/service.svc");
client.Endpoint.Binding = new NetTcpBinding()
{
Name = "yourTcpBindConfig",
ReaderQuotas = XmlDictionaryReaderQuotas.Max,
ListenBacklog = 40 }
It's very easy to modify the uri in config or binding info in config. Is this what you want?
I installed System.Configuration.ConfigurationManager
from Nuget into my .net core 2.2 application.
I then reference using System.Configuration;
Next, I changed
WebConfigurationManager.AppSettings
to ..
ConfigurationManager.AppSettings
So far I believe this is correct. 4.5.0 is typical with .net core 2.2
I have not had any issues with this.
Underneath the file system, files are represented by inodes. (Or is it multiple inodes? Not sure.)
A file in the file system is basically a link to an inode.
A hard link, then, just creates another file with a link to the same underlying inode.
When you delete a file, it removes one link to the underlying inode. The inode is only deleted (or deletable/over-writable) when all links to the inode have been deleted.
A symbolic link is a link to another name in the file system.
Once a hard link has been made the link is to the inode. Deleting, renaming, or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode.
Note: Hard links are only valid within the same File System. Symbolic links can span file systems as they are simply the name of another file.
# oneline solution using zip
>> x = {'a':100, 'b':999}
>> y = dict(zip(x.values(), x.keys()))
>> y
{100: 'a', 999: 'b'}
The Answer i was looking for was:
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
I've also learned that you can do it this way:
DateTime myDateTime = DateTime.Now;
string sqlFormattedDate = myDateTime.ToString(myCountryDateFormat);
where myCountryDateFormat can be changed to meet change depending on requirement.
Please note that the tagged "This question may already have an answer here:" has not actually answered the question because as you can see it used a ".Date" instead of omitting it. It's quite confusing for new programmers of .NET
I use json
:
import json
# convert to string
input = json.dumps({'id': id })
# load to dict
my_dict = json.loads(input)
Use the SimpleDateFormat.format
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
String sDate= sdf.format(date);
In Java 7 and up:
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"))) {
writer.write("something");
}
There are useful utilities for that though:
Note also that you can use a FileWriter
, but it uses the default encoding, which is often a bad idea - it's best to specify the encoding explicitly.
Below is the original, prior-to-Java 7 answer
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("filename.txt"), "utf-8"));
writer.write("Something");
} catch (IOException ex) {
// Report
} finally {
try {writer.close();} catch (Exception ex) {/*ignore*/}
}
See also: Reading, Writing, and Creating Files (includes NIO2).
Between those two syntaxes, you should really choose the one you prefer :-)
Personally, I would go with your second solution in such a case (Variable interpolation), which I find easier to both write and read.
The result will be the same; and even if there are performance implications, those won't matter 1.
As a sidenote, so my answer is a bit more complete: the day you'll want to do something like this:
echo "Welcome $names!";
PHP will interpret your code as if you were trying to use the $names
variable -- which doesn't exist.
- note that it will only work if you use "" not '' for your string.
That day, you'll need to use {}
:
echo "Welcome {$name}s!"
No need to fallback to concatenations.
Also note that your first syntax:
echo "Welcome ".$name."!";
Could probably be optimized, avoiding concatenations, using:
echo "Welcome ", $name, "!";
(But, as I said earlier, this doesn't matter much...)
1 - Unless you are doing hundreds of thousands of concatenations vs interpolations -- and it's probably not quite the case.
I'll right simple example show you the right way to use wait
and notify
in Java.
So I'll create two class named ThreadA & ThreadB. ThreadA will call ThreadB.
public class ThreadA {
public static void main(String[] args){
ThreadB b = new ThreadB();//<----Create Instance for seconde class
b.start();//<--------------------Launch thread
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();//<-------------WAIT until the finish thread for class B finish
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}
}
and for Class ThreadB:
class ThreadB extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();//<----------------Notify the class wich wait until my finish
//and tell that I'm finish
}
}
}
This untested, but I think you may be able to try something like this:
$('#listItem').not('span').text();
You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.
I think what you were looking for in your Range was this:
Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete
Just change the column letters to match your needs.
I made quite easy, Django style JSP Template inheritance tag library. https://github.com/kwon37xi/jsp-template-inheritance
I think it make easy to manage layouts without learning curve.
example code :
base.jsp : layout
<%@page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://kwonnam.pe.kr/jsp/template-inheritance" prefix="layout"%>
<!DOCTYPE html>
<html lang="en">
<head>
<title>JSP Template Inheritance</title>
</head>
<h1>Head</h1>
<div>
<layout:block name="header">
header
</layout:block>
</div>
<h1>Contents</h1>
<div>
<p>
<layout:block name="contents">
<h2>Contents will be placed under this h2</h2>
</layout:block>
</p>
</div>
<div class="footer">
<hr />
<a href="https://github.com/kwon37xi/jsp-template-inheritance">jsp template inheritance example</a>
</div>
</html>
view.jsp : contents
<%@page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://kwonnam.pe.kr/jsp/template-inheritance" prefix="layout"%>
<layout:extends name="base.jsp">
<layout:put name="header" type="REPLACE">
<h2>This is an example about layout management with JSP Template Inheritance</h2>
</layout:put>
<layout:put name="contents">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin porta,
augue ut ornare sagittis, diam libero facilisis augue, quis accumsan enim velit a mauris.
</layout:put>
</layout:extends>
Simple really create a long variable that represents a default start date for your program Get the date to another long variable. Then deduct the long start date and convert to a integer voila To read and convert back just add rather than subtract. obviously this is dependant on how large a date range you require.
Hope this would help:
-> And that serial number is UDID
Easy as this, that worked for my project
composer install
php artisan serve
You can use the sequence method list.extend
to extend the list by multiple values from any kind of iterable, being it another list or any other thing that provides a sequence of values.
>>> lst = [1, 2]
>>> lst.append(3)
>>> lst.append(4)
>>> lst
[1, 2, 3, 4]
>>> lst.extend([5, 6, 7])
>>> lst.extend((8, 9, 10))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> lst.extend(range(11, 14))
>>> lst
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
So you can use list.append()
to append a single value, and list.extend()
to append multiple values.
For someone who needs an explanation and an example of how to use a regxp in Eclipse. Here is my example illustrating the problem.
I want to rename
/download.mp4^lecture_id=271
to
/271.mp4
And there can be multiple of these.
Here is how it should be done.
Then hit find/replace button
In my case, I got the error because I had mixed UPPER- and lower-case package names on a Windows 7 system. Changing the package names to all lower case resolved the issue. Note also that in this scenario, I got no error compiling the .java file into a .class file; it just wouldn't run from the same (sub-sub-sub-) directory.
An alternative to get a byte array is to encode the string in ascii: b=s.encode('ascii')
.
If your images are small, consider storing them as base64 in a plain text field.
The reason is that while base64 has an overhead of 33%, with compression that mostly goes away. (See What is the space overhead of Base64 encoding?) Your database will be bigger, but the packets your webserver sends to the client won't be. In html, you can inline base64 in an <img src=""> tag, which can possibly simplify your app because you won't have to serve up the images as binary in a separate browser fetch. Handling images as text also simplifies things when you have to send/receive json, which doesn't handle binary very well.
Yes, I understand you could store the binary in the database and convert it to/from text on the way in and out of the database, but sometimes ORMs make that a hassle. It can be simpler just to treat it as straight text just like all your other fields.
This is definitely the right way to handle thumbnails.
(OP's images are not small, so this is not really an answer to his question.)
Here is a very simple way available in current Swiftmailer. Most of the other answers are old and reinvent the wheel.
As per Swiftmailer documentation: https://swiftmailer.symfony.com/docs/messages.html#quick-reference
use Egulias\EmailValidator\EmailValidator;
use Egulias\EmailValidator\Validation\RFCValidation;
$validator = new EmailValidator();
$validator->isValid("[email protected]", new RFCValidation()); //true
This is by far the simplest and most robust approach, imo. Just install via Composer the Egulias\EmailValidator library which should already be brought in as a dependency of SwiftMailer anyway.
You can instruct the child process to print its environment variables (by calling "env"), then loop over the printed environment variables in the parent process and call "export" on those variables.
The following code is based on Capturing output of find . -print0 into a bash array
If the parent shell is the bash, you can use
while IFS= read -r -d $'\0' line; do
export "$line"
done < <(bash -s <<< 'export VARNAME=something; env -0')
echo $VARNAME
If the parent shell is the dash, then read
does not provide the -d flag and the code gets more complicated
TMPDIR=$(mktemp -d)
mkfifo $TMPDIR/fifo
(bash -s << "EOF"
export VARNAME=something
while IFS= read -r -d $'\0' line; do
echo $(printf '%q' "$line")
done < <(env -0)
EOF
) > $TMPDIR/fifo &
while read -r line; do export "$(eval echo $line)"; done < $TMPDIR/fifo
rm -r $TMPDIR
echo $VARNAME
Both these work for me. Maybe post a complete example?
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class PaneBackgroundTest extends Application {
@Override
public void start(Stage primaryStage) {
BorderPane root = new BorderPane();
VBox vbox = new VBox();
root.setCenter(vbox);
ToggleButton toggle = new ToggleButton("Toggle color");
HBox controls = new HBox(5, toggle);
controls.setAlignment(Pos.CENTER);
root.setBottom(controls);
// vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
// .then("-fx-background-color: cornflowerblue;")
// .otherwise("-fx-background-color: white;"));
vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
.then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
.otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
if someone is still facing this issue, for me it started to occur after I changed my mysql/data
with mysql/backup
earlier to solve another issue.
I tried a lot of methods, and finally found the solution was very simple! Just click on this icon(Reset session) after opening PhPMyAdmin(it was loading in my case) just below the logo of PhPMyAdmin. It fixed the issue in one-click!
For me, the error code was #1142
PhpMyAdmin Reset Session
For Winforms
private void listBox1_DoubleClick(object sender, MouseEventArgs e)
{
int index = this.listBox1.IndexFromPoint(e.Location);
if (index != System.Windows.Forms.ListBox.NoMatches)
{
MessageBox.Show(listBox1.SelectedItem.ToString());
}
}
and
public Form()
{
InitializeComponent();
listBox1.MouseDoubleClick += new MouseEventHandler(listBox1_DoubleClick);
}
that should also, prevent for the event firing if you select an item then click on a blank area.
Just add water style="display:none";
to the <div>
Fiddles I say: http://jsfiddle.net/krY56/13/
jQuery:
function toggler(divId) {
$("#" + divId).toggle();
}
Preferred to have a CSS Class .hidden
.hidden {
display:none;
}
The short answer is yes the "new" keyword is incredibly important as when you use it the object data is stored on the heap as opposed to the stack, which is most important!
The code that worked for me is:
ThisWorkbook.Sheets("sheetName").Activate
To make this process more robust, you could consider using the SAX parser (that way you don't have to hold the whole file in memory), read & write till the end of tree and then start appending.
if you are using XDocument.Load(url);
to fetch xml from another domain, it's possible that the host will reject the request and return and unexpected (non-xml) result, which results in the above XmlException
See my solution to this eventuality here: XDocument.Load(feedUrl) returns "Data at the root level is invalid. Line 1, position 1."
Make sure the Visible property is set to true or the control won't render to the page. Then you can use script to manipulate it.
You can use an anchor to "focus" the div. I.e:
<div id="myDiv"></div>
and then use the following javascript:
// the next line is required to work around a bug in WebKit (Chrome / Safari)
location.href = "#";
location.href = "#myDiv";
It is time to revisit this old question.
You should not use solutions relying on toLowerCase
. They are inefficient and simply don't work in some languages (Turkish for instance). Prefer this:
['Foo', 'bar'].sort((a, b) => a.localeCompare(b, undefined, {sensitivity: 'base'}))
Check the documentation for browser compatibility and all there is to know about the sensitivity
option.
You can try these some steps:
Stop Mysql Service 1st
sudo /etc/init.d/mysql stop
Login as root without password
sudo mysqld_safe --skip-grant-tables &
After login mysql terminal you should need execute commands more:
use mysql;
UPDATE mysql.user SET authentication_string=PASSWORD('solutionclub3@*^G'), plugin='mysql_native_password' WHERE User='root';
flush privileges;
sudo mysqladmin -u root -p -S /var/run/mysqld/mysqld.sock shutdown
After you restart your mysql server If you still facing error you must visit : Reset MySQL 5.7 root password Ubuntu 16.04
The message:
Waiting for available socket...
is shown, because you've reached a limit on the ssl_socket_pool either per Host, Proxy or Group.
Here are the maximum number of HTTP connections which you can make with a Chrome browser:
Maximum per Host: 6 connections.
This is likely hardcoded in the source code of the web browser, so you can't change it.
Total 256 HTTP connections pooled per browser.
Source: Enterprise networking for Chrome devices
The above limits can be checked or flushed at chrome://net-internals/#sockets
(or in real-time at chrome://net-internals/#events&q=type:SOCKET%20is:active
).
Your issue with audio can be related to Chrome bug 162627 where HTML5 audio fails to load and it hits max simultaneous connections per server:proxy. This is still active issue at the time of writing (2016).
Much older issue related to HTML5 video request stay pending, then it's probably related to Issue #234779 which has been fixed 2014. And related to SPDY which can be found in Issue 324653: SPDY issue: waiting for available sockets, but this was already fixed in 2014, so probably it's not related.
Other related issue now marked as duplicate can be found in Issue 401845: Failure to preload audio metadata. Loaded only 6 of 10+ which was related to the problem with the media player code leaving a bunch of paused requests hanging around.
This also may be related to some Chrome adware or antivirus extensions using your sockets in the backgrounds (like Sophos or Kaspersky), so check for Network activity in DevTools.
In my case I had to compare column E and I.
I used conditional formatting with new rule. Formula was "=IF($E1<>$I1,1,0)" for highlights in orange and "=IF($E1=$I1,1,0)" to highlight in green.
Next problem is how many columns you want to highlight. If you open Conditional Formatting Rules Manager you can edit for each rule domain of applicability: Check "Applies to"
In my case I used "=$E:$E,$I:$I" for both rules so I highlight only two columns for differences - column I and column E.
IE is even worse with 2 connection per domain limit. But I wouldn't rely on fixing client browsers. Even if you have control over them, browsers like chrome will auto update and a future release might behave differently than you expect. I'd focus on solving the problem within your system design.
Your choices are to:
Load the images in sequence so that only 1 or 2 XHR calls are active at a time (use the success event from the previous image to check if there are more images to download and start the next request).
Use sub-domains like serverA.myphotoserver.com and serverB.myphotoserver.com. Each sub domain will have its own pool for connection limits. This means you could have 2 requests going to 5 different sub-domains if you wanted to. The downfall is that the photos will be cached according to these sub-domains. BTW, these don't need to be "mirror" domains, you can just make additional DNS pointers to the exact same website/server. This means you don't have the headache of administrating many servers, just one server with many DNS records.
Ahhhh, now it is clear. You seem to have problems binding back the value. Not with displaying it on the view. Indeed, that's the fault of the default model binder. You could write and use a custom one that will take into consideration the [DisplayFormat]
attribute on your model. I have illustrated such a custom model binder here: https://stackoverflow.com/a/7836093/29407
Apparently some problems still persist. Here's my full setup working perfectly fine on both ASP.NET MVC 3 & 4 RC.
Model:
public class MyViewModel
{
[DisplayName("date of birth")]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? Birth { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel
{
Birth = DateTime.Now
});
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
@model MyViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(x => x.Birth)
@Html.EditorFor(x => x.Birth)
@Html.ValidationMessageFor(x => x.Birth)
<button type="submit">OK</button>
}
Registration of the custom model binder in Application_Start
:
ModelBinders.Binders.Add(typeof(DateTime?), new MyDateTimeModelBinder());
And the custom model binder itself:
public class MyDateTimeModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var displayFormat = bindingContext.ModelMetadata.DisplayFormatString;
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (!string.IsNullOrEmpty(displayFormat) && value != null)
{
DateTime date;
displayFormat = displayFormat.Replace("{0:", string.Empty).Replace("}", string.Empty);
// use the format specified in the DisplayFormat attribute to parse the date
if (DateTime.TryParseExact(value.AttemptedValue, displayFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
return date;
}
else
{
bindingContext.ModelState.AddModelError(
bindingContext.ModelName,
string.Format("{0} is an invalid date format", value.AttemptedValue)
);
}
}
return base.BindModel(controllerContext, bindingContext);
}
}
Now, no matter what culture you have setup in your web.config (<globalization>
element) or the current thread culture, the custom model binder will use the DisplayFormat
attribute's date format when parsing nullable dates.
The 2019 optimal solution for this is HTTP/2 Server Push.
You do not need any hacky javascript solutions or inline styles. However, you do need a server that supports HTTP 2.0 (any modern server version will), which itself requires your server to run SSL. However, with Let's Encrypt there's no reason not to be using SSL anyway.
My site https://r.je/ has a 100/100 score for both mobile and desktop.
The reason for these errors is that the browser gets the HTML, then has to wait for the CSS to be downloaded before the page can be rendered. Using HTTP2 you can send both the HTML and the CSS at the same time.
You can use HTTP/2 push by setting the Link header.
Apache example (.htaccess):
Header add Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload"
For NGINX you can add the header to your location tag in the server configuration:
location = / {
add_header Link "</style.css>; as=style; rel=preload, </font.css>; as=style; rel=preload";
}
With this header set, the browser receives the HTML and CSS at the same time which stops the CSS from blocking rendering.
You will want to tweak it so that the CSS is only sent on the first request, but the Link header is the most complete and least hacky solution to "Eliminate Render Blocking Javascript and CSS"
For a detailed discussion, take a look at my post here: Eliminate Render Blocking CSS using HTTP/2 Push
Simplest way to do is as follows:
git fetch && git checkout <branch_name>
Here is a more generic solution based on @Arun answer
public abstract class TextViewLinkHandler extends LinkMovementMethod {
public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_UP)
return super.onTouchEvent(widget, buffer, event);
int x = (int) event.getX();
int y = (int) event.getY();
x -= widget.getTotalPaddingLeft();
y -= widget.getTotalPaddingTop();
x += widget.getScrollX();
y += widget.getScrollY();
Layout layout = widget.getLayout();
int line = layout.getLineForVertical(y);
int off = layout.getOffsetForHorizontal(line, x);
URLSpan[] link = buffer.getSpans(off, off, URLSpan.class);
if (link.length != 0) {
onLinkClick(link[0].getURL());
}
return true;
}
abstract public void onLinkClick(String url);
}
To use it just implement onLinkClick
of TextViewLinkHandler
class. For instance:
textView.setMovementMethod(new TextViewLinkHandler() {
@Override
public void onLinkClick(String url) {
Toast.makeText(textView.getContext(), url, Toast.LENGTH_SHORT).show();
}
});
From: http://nginx.org/r/large_client_header_buffers
Syntax:
large_client_header_buffers
number
size
;
Default:large_client_header_buffers 4 8k;
Context: http, serverSets the maximum
number
andsize
of buffers used for reading large client request header. A request line cannot exceed the size of one buffer, or the 414 (Request-URI Too Large) error is returned to the client. A request header field cannot exceed the size of one buffer as well, or the 400 (Bad Request) error is returned to the client. Buffers are allocated only on demand. By default, the buffer size is equal to 8K bytes. If after the end of request processing a connection is transitioned into the keep-alive state, these buffers are released.
so you need to change the size parameter at the end of that line to something bigger for your needs.
I tried all the answers above, but none of them worked for me, so I was forced to try something else. I just removed the whole package with settings org.eclipse.Java and it worked fine, starts again like before and even keeps all settings like color themes and others. Worked like charm.
On Linux or Mac go to /home/{your_user_name}/.var/app and run the following command:
rm -r org.eclipse.Java
On Windows just find the same directory and move it to Trash.
After this is done, the settings and the errors are deleted, so Eclipse will start and re-create them with the proper settings.
When Eclipse starts it will ask for the workspace directory. When specified, everything works like before.
Use this:
myFunction.bookName = 'mybook';
myFunction.bookdesc = 'new';
Or, if you are using jQuery:
$(myFunction).extend({
bookName:'mybook',
bookdesc: 'new'
});
The push
method is wrong because it belongs to the Array.prototype
object.
To create a named object, try this:
var myObj = function(){
this.property = 'foo';
this.bar = function(){
}
}
myObj.prototype.objProp = true;
var newObj = new myObj();
Another formula option is to use REPLACE function to replace the first n characters with nothing, e.g. if n = 4
=REPLACE(A1,1,4,"")
if (!file_get_contents($data)) {
exit('<h1>ERROR MESSAGE</h1>');
} else {
return file_get_contents($data);
}
IMHO Lookup tables is the way to go, with referential integrity. But only if you avoid "Evil Magic Numbers" by following an example such as this one: Generate enum from a database lookup table using T4
Have Fun!
the tutorial of how to build NodeJS for Android https://github.com/dna2github/dna2oslab/tree/master/android/build
there are several versions v0.12, v4, v6, v7
It is easy to run compiled binary on Android; for example run compiled Nginx: https://github.com/dna2github/dna2mtgol/tree/master/fileShare
You just need to modify code to replace Nginx to NodeJS; it is better if using Android Service to run node js server on the backend.
"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:
file.py
will be uploaded into your HOME
dir on remote server.
or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:
After connecting to the server pscp will ask for a password.
Google allows you to search in the project, but not the code :(
If it's a large file and you don't want to consume a ton of memory as might happen with Ben's solution, the extra code in
>>> import shutil
>>> import sys
>>> with open("test.txt", "r") as f:
... shutil.copyfileobj(f, sys.stdout)
also works.
In addition to adding python's bin
directory to $PATH
variable, I also had to change the owner of that directory, to make it work. No idea why I wasn't the owner already.
chown -R ~/Library/Python/
I do not know of any in-built method, but you could just use linq:
parameterList = parameterList.Where(x => x != null).ToList();
Here's a version of @Julian Mosquera's code that also supports sorting by object key:
yourApp.filter('orderObjectBy', function () {
return function (items, field, reverse) {
// Build array
var filtered = [];
for (var key in items) {
if (field === 'key')
filtered.push(key);
else
filtered.push(items[key]);
}
// Sort array
filtered.sort(function (a, b) {
if (field === 'key')
return (a > b ? 1 : -1);
else
return (a[field] > b[field] ? 1 : -1);
});
// Reverse array
if (reverse)
filtered.reverse();
return filtered;
};
});
Here is my simple but efficient algorithm (in C++) for calculating running median from a stream of integers:
#include<algorithm>
#include<fstream>
#include<vector>
#include<list>
using namespace std;
void runningMedian(std::ifstream& ifs, std::ofstream& ofs, const unsigned bufSize) {
if (bufSize < 1)
throw exception("Wrong buffer size.");
bool evenSize = bufSize % 2 == 0 ? true : false;
list<int> q;
vector<int> nums;
int n;
unsigned count = 0;
while (ifs.good()) {
ifs >> n;
q.push_back(n);
auto ub = std::upper_bound(nums.begin(), nums.end(), n);
nums.insert(ub, n);
count++;
if (nums.size() >= bufSize) {
auto it = std::find(nums.begin(), nums.end(), q.front());
nums.erase(it);
q.pop_front();
if (evenSize)
ofs << count << ": " << (static_cast<double>(nums[nums.size() / 2 - 1] +
static_cast<double>(nums[nums.size() / 2]))) / 2.0 << '\n';
else
ofs << count << ": " << static_cast<double>(nums[nums.size() / 2]);
}
}
}
The bufferSize
specifies the size of the numbers sequence, on which the running median must be calculated. When reading numbers from the input stream ifs
the vector of the size bufferSize
is maintained in sorted order. The median is calculated by taking the middle of the sorted vector, if bufferSize
is odd, or the sum of the two middle elements divided by 2, when bufferSize
is even. Additinally, I maintain a list of last bufferSize
elements read from input. When a new element is added, I put it in the right place in sorted vector and remove from the vector the element added bufferSize
steps before (the value of the element retained in the front of the list). In the same time I remove the old element from the list: every new element is placed on the back of the list, every old element is removed from the front. After reaching the bufferSize
, both the list and the vector stop to grow, and every insertion of a new element is compensated be deletion of an old element, placed in the list bufferSize
steps before. Note, I do not care, whether I remove from the vector exactly the element, placed bufferSize
steps before, or just an element that has the same value. For the value of median it does not matter.
All calculated median values are output in the output stream.
I tried this:
long now = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
new Date().getTime();
}
long result = System.currentTimeMillis() - now;
System.out.println("Date(): " + result);
now = System.currentTimeMillis();
for (int i = 0; i < 10000000; i++) {
System.currentTimeMillis();
}
result = System.currentTimeMillis() - now;
System.out.println("currentTimeMillis(): " + result);
And result was:
Date(): 199
currentTimeMillis(): 3
You can use %%~nf
to get the filename only as described in the reference for for
:
@echo off
for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
echo %%~nf
)
pause
The following options are available:
Variable with modifier Description %~I Expands %I which removes any surrounding quotation marks (""). %~fI Expands %I to a fully qualified path name. %~dI Expands %I to a drive letter only. %~pI Expands %I to a path only. %~nI Expands %I to a file name only. %~xI Expands %I to a file extension only. %~sI Expands path to contain short names only. %~aI Expands %I to the file attributes of file. %~tI Expands %I to the date and time of file. %~zI Expands %I to the size of file. %~$PATH:I Searches the directories listed in the PATH environment variable and expands %I to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, this modifier expands to the empty string.
origin is a name for remote git url. There can be many more remotes example below.
bangalore => bangalore.example.com:project.git boston => boston.example.com:project.git
as far as origin/master (example bangalore/master) goes, it is pointer to "master" commit on bangalore site . You see it in your clone.
It is possible that remote bangalore has advanced since you have done "fetch" or "pull"
This is an old but still very relevant question, so I'll add this: What's the first thing you look for when you open up a class file that you may or may not have read before? Fields? Properties? I've realized from experience that almost invariably I go hunting for the constructors, because the most basic thing to understand is how this object is constructed.
Therefore, I've started putting constructors first in class files, and the result has been psychologically very positive. The standard recommendation of putting constructors after a bunch of other things feels dissonant.
The upcoming primary constructor feature in C# 6 provides evidence that the natural place for a constructor is at the very top of a class - in fact primary constructors are specified even before the open brace.
It's funny how much of a difference a reordering like this makes. It reminds me of how using
statements used to be ordered - with the System namespaces first. Visual Studio's "Organize Usings" command used this order. Now using
s are just ordered alphabetically, with no special treatment given to System namespaces. The result just feels simpler and cleaner.
jQuery “ $(”#datepicker“).datepicker is not a function”
I have fixed the issue by placing the below three files in the body section of the form at the end.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="Stylesheet" type="text/css" />
There is one characteristic about inline-block which may not be straight-forward though. That is that the default value for vertical-align in CSS is baseline. This may cause some unexpected alignment behavior. Look at this article.
http://www.brunildo.org/test/inline-block.html
Instead, when you do a float:left, the divs are independent of each other and you can align them using margin easily.
solve(c)
does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c
to invoke matrix multiplication in R.
R performs element by element multiplication when you invoke solve(c) * c
.
I too got the same error, when I did this behind a proxy. But after I exported the following from a terminal and re-tried the same command, the problem got resolved:
export http_proxy="http://username:password@proxy_ip_addr:port/"
export https_proxy="https://username:password@proxy_ip_addr:port/"
Use ng-value
for set value of input box after clicking on a button
:
"input type="email" class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"
and
Set Value as:
$scope.myForm.email2 = $scope.names[0].success;
I know this was asked over 6 years ago now, but just wanted to add my solution, as some of the suggestions above seem horribly complicated, but my solution was actually very simple.
All I had to do was wrap the pool.map() call to a helper function. Passing the class object along with args for the method as a tuple, which looked a bit like this.
def run_in_parallel(args):
return args[0].method(args[1])
myclass = MyClass()
method_args = [1,2,3,4,5,6]
args_map = [ (myclass, arg) for arg in method_args ]
pool = Pool()
pool.map(run_in_parallel, args_map)
I used ProcessBuilder but had the same issue. The issue was with using command as one String line (like I would type it in cmd) instead of String array. In example from above. If I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar x myjar.jar *.* new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
I got an error. But if I ran
ProcessBuilder pb = new ProcessBuilder("C:/Program Files/WinRAR/winrar", "x", "myjar.jar", "*.*", "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);
Process p = pb.start();
everything was OK.
Are you just looking to verify that the file is of a given extension? You can simplify what you are trying to do with something like this:
(.*?)\.(jpg|gif|doc|pdf)$
Then, when you call IsMatch() make sure to pass RegexOptions.IgnoreCase as your second parameter. There is no reason to have to list out the variations for casing.
Edit: As Dario mentions, this is not going to work for the RegularExpressionValidator, as it does not support casing options.
You need the full path to the regsvr32 so %windir$\system32\regsvr32 <*.dll>
I have not used bundle exec
much, but am setting it up now.
I have had instances where the wrong rake was used and much time wasted tracking down the problem. This helps you avoid that.
Here's how to set up RVM so you can use bundle exec
by default within a specific project directory:
Hope it will help u:
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:
{{people.[1].name}}
{{people.1.name}}
However, the square brackets are required in:
{{#with people.[1]}}
{{name}}
{{/with}}
In the latter, using the index number without the square brackets would get one:
Error: Parse error on line ...:
... {{#with people.1}}
-----------------------^
Expecting 'ID', got 'INTEGER'
As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?
(Tested with Handlebars in YUI.)
You can now use the get
helper for this:
(get people index)
although if you get an error about index needing to be a string, do:
(get people (concat index ""))
For one-way data binding from parent to child, use the @Input
decorator (as recommended by the style guide) to specify an input property on the child component
@Input() model: any; // instead of any, specify your type
and use template property binding in the parent template
<child [model]="parentModel"></child>
Since you are passing an object (a JavaScript reference type) any changes you make to object properties in the parent or the child component will be reflected in the other component, since both components have a reference to the same object. I show this in the Plunker.
If you reassign the object in the parent component
this.model = someNewModel;
Angular will propagate the new object reference to the child component (automatically, as part of change detection).
The only thing you shouldn't do is reassign the object in the child component. If you do this, the parent will still reference the original object. (If you do need two-way data binding, see https://stackoverflow.com/a/34616530/215945).
@Component({
selector: 'child',
template: `<h3>child</h3>
<div>{{model.prop1}}</div>
<button (click)="updateModel()">update model</button>`
})
class Child {
@Input() model: any; // instead of any, specify your type
updateModel() {
this.model.prop1 += ' child';
}
}
@Component({
selector: 'my-app',
directives: [Child],
template: `
<h3>Parent</h3>
<div>{{parentModel.prop1}}</div>
<button (click)="updateModel()">update model</button>
<child [model]="parentModel"></child>`
})
export class AppComponent {
parentModel = { prop1: '1st prop', prop2: '2nd prop' };
constructor() {}
updateModel() { this.parentModel.prop1 += ' parent'; }
}
Plunker - Angular RC.2
Note: when it says "B5" in the explanation below, it actually means "B{current_row}", so for C5 it's B5, for C6 it's B6 and so on. Unless you specify $B$5 - then you refer to one specific cell.
This is supported in Google Sheets as of 2015: https://support.google.com/drive/answer/78413#formulas
In your case, you will need to set conditional formatting on B5.
=B5>0.8*C5
.B5
.You can repeat this process to add more colors for the background or text or a color scale.
Even better, make a single rule apply to all rows by using ranges in "Range". Example assuming the first row is a header:
=B2>0.8*C2
.B2:B
.Will be like the previous example but works on all rows, not just row 5.
Ranges can also be used in the "Custom formula is" so you can color an entire row based on their column values.
In addition to the aforementioned std::div family of functions, there is also the std::remquo family of functions, return the rem-ainder and getting the quo-tient via a passed-in pointer.
[Edit:] It looks like std::remquo doesn't really return the quotient after all.
Select TableName.* from TableName DESC LIMIT 5
As of 15th August 2016, the repo is a massive 2.39GB file. I opened the Activity Monitor to look at what the terminal was doing. It was downloading this huge file.
Use
label.setOpaque(true);
Otherwise the background is not painted, since the default of opaque
is false
for JLabel
.
From the JavaDocs:
If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.
For more information, read the Java Tutorial How to Use Labels.
For portability, one should probably use std::signal
from the standard C++ library, but there is a lot of restriction on what a signal handler can do. Unfortunately, it is not possible to catch a SIGSEGV from within a C++ program without introducing undefined behavior because the specification says:
abort
, exit
, some atomic functions, reinstall current signal handler, memcpy
, memmove
, type traits, `std::move, std::forward
, and some more).throw
expression.This proves that it is impossible to catch SIGSEGV from within a program using strictly standard and portable C++. SIGSEGV is still caught by the operating system and is normally reported to the parent process when a wait family function is called.
You will probably run into the same kind of trouble using POSIX signal because there is a clause that says in 2.4.3 Signal Actions:
The behavior of a process is undefined after it returns normally from a signal-catching function for a SIGBUS, SIGFPE, SIGILL, or SIGSEGV signal that was not generated by
kill()
,sigqueue()
, orraise()
.
A word about the longjump
s. Assuming we are using POSIX signals, using longjump
to simulate stack unwinding won't help:
Although
longjmp()
is an async-signal-safe function, if it is invoked from a signal handler which interrupted a non-async-signal-safe function or equivalent (such as the processing equivalent toexit()
performed after a return from the initial call tomain()
), the behavior of any subsequent call to a non-async-signal-safe function or equivalent is undefined.
This means that the continuation invoked by the call to longjump cannot reliably call usually useful library function such as printf
, malloc
or exit
or return from main without inducing undefined behavior. As such, the continuation can only do a restricted operations and may only exit through some abnormal termination mechanism.
To put things short, catching a SIGSEGV and resuming execution of the program in a portable is probably infeasible without introducing UB. Even if you are working on a Windows platform for which you have access to Structured exception handling, it is worth mentioning that MSDN suggest to never attempt to handle hardware exceptions: Hardware Exceptions.
At last but not least, whether any SIGSEGV would be raised when dereferencing a null valued pointer (or invalid valued pointer) is not a requirement from the standard. Because indirection through a null valued pointer or any invalid valued pointer is an undefined behaviour, which means the compiler assumes your code will never attempt such a thing at runtime, the compiler is free to make code transformation that would elide such undefined behavior. For example, from cppreference,
int foo(int* p) {
int x = *p;
if(!p)
return x; // Either UB above or this branch is never taken
else
return 0;
}
int main() {
int* p = nullptr;
std::cout << foo(p);
}
Here the true path of the if
could be completely elided by the compiler as an optimization; only the else
part could be kept. Said otherwise, the compiler infers foo()
will never receive a null valued pointer at runtime since it would lead to an undefined behaviour. Invoking it with a null valued pointer, you may observe the value 0
printed to standard output and no crash, you may observe a crash with SIGSEG, in fact you could observe anything since no sensible requirements are imposed on programs that are not free of undefined behaviors.
I've created a plunker based off of the answers here and elsewhere.
Additionally I had to add an @Input
, @ViewChild
, and ElementRef
of the <input>
and create and subscribe()
to an observable of it.
Angular2 Search Filter: PLUNKR (UPDATE: plunker no longer works)
It's very easy if you use Kotlin:
val textFile = File(cacheDir, "/text_file.txt")
val allText = textFile.readText()
println(allText)
From readText()
docs:
Gets the entire content of this file as a String using UTF-8 or specified charset. This method is not recommended on huge files. It has an internal limitation of 2 GB file size.
ConfigurationManager.RefreshSection("appSettings")
string value = System.Configuration.ConfigurationManager.AppSettings[key];
According the @saswanb's response, this is a Swift 4 version :
var iphoneX = false
if #available(iOS 11.0, *) {
if ((UIApplication.shared.keyWindow?.safeAreaInsets.top)! > CGFloat(0.0)) {
iphoneX = true
}
}
http://en.wikipedia.org/wiki/Division_by_zero
http://en.wikipedia.org/wiki/Unix_signal#SIGFPE
This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0
IS division by zero and as such, will trigger a SIGFPE being thrown.
Try this:
from random import randrange, uniform
# randrange gives you an integral value
irand = randrange(0, 10)
# uniform gives you a floating-point value
frand = uniform(0, 10)
with a reference to Microsoft.VisualBasic
Interaction.Shell("copy /b Image1.jpg + Archive.rar Image2.jpg", AppWinStyle.Hide);
for the mac user inside the python console type
import os
os.system('clear')
for windows
os.system('cls')
I firstly recommend you to read Hannes Dorfmann's great article about this topic.
When new view type comes, you have to edit your adapter and you have to handle so many mess things. Your adapter should be Open for extension but Closed for modification.
You may check this two project, they can give the idea about how to handle different ViewTypes in Adapter:
Update 2015/06
As jQuery has evolved since the question was posted, the recommended approach now is using $.on
$(document).ready(function() {
$("input[name=group2]").on( "change", function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
} );
});
or outside $.ready()
$(document).on( "change", "input[name=group2]", function() { ... } );
Original answer
You should use .change()
event handler:
$(document).ready(function(){
$("input[name=group2]").change(function() {
var test = $(this).val();
$(".desc").hide();
$("#"+test).show();
});
});
should work
Try this
function readRows() {
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
//var values = rows.getValues();
var Names = sheet.getRange("A2:A7");
var Name = [
Names.getCell(1, 1).getValue(),
Names.getCell(2, 1).getValue(),
.....
Names.getCell(5, 1).getValue()]
You can define arrays simply as follows, instead of allocating and then assigning.
var arr = [1,2,3,5]
Your initial error was because of the following line, and ones like it
var Name[0] = Name_cell.getValue();
Since Name
is already defined and you are assigning the values to its elements, you should skip the var
, so just
Name[0] = Name_cell.getValue();
Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.
HashMap
is an implementation of Map
. Map is just an interface for any type of map.
You can always use Sharepoint Solution Generator to create a project and edit in VS2008.
You can find the Generator along with Sharepoint Developer tools.
As already stated in earlier answers, ng-pristine
is for indicating that the field has not been modified, whereas ng-dirty
is for telling it has been modified. Why need both?
Let's say we've got a form with phone and e-mail address among the fields. Either phone or e-mail is required, and you also have to notify the user when they've got invalid data in each field. This can be accomplished by using ng-dirty
and ng-pristine
together:
<form name="myForm">
<input name="email" ng-model="data.email" ng-required="!data.phone">
<div class="error"
ng-show="myForm.email.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.email.$invalid && myForm.email.$dirty">
E-mail is invalid
</div>
<input name="phone" ng-model="data.phone" ng-required="!data.email">
<div class="error"
ng-show="myForm.phone.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.phone.$invalid && myForm.phone.$dirty">
Phone is invalid
</div>
</form>
When you want to convert your code to result( executable, library or whatever ), there is 2 steps:
1) compile
2) link
In first step compiler should now about some things like sizeof objects that used by you, prototype of functions and maybe inheritance. on the other hand linker want to find implementation of functions and global variables in your code.
Now when you use ClassTwo
in File1.cpp
compiler know nothing about it and don't know how much memory should allocate for it or for example witch members it have or is it a class and enum or even a typedef of int, so compilation will be failed by the compiler. adding File2.cpp
solve the problem of linker that look for implementation but the compiler is still unhappy, because it know nothing about your type.
So remember, in compile phase you always work with just one file( and of course files that included by that one file ) and in link phase you need multiple files that contain implementations. and since C/C++ are statically typed and they allow their identifier to work for many purposes( definition, typedef, enum class, ... ) so you should always identify you identifier to the compiler and then use it and as a rule compiler should always know size of your variable!!
this worked for me!
if some_queryset.objects.all().exists(): print("this table is not empty")
There are several scenarios to consider. First of all, you need to check the type of your object. You can simply call GetType() for this. If the type does not implement IDynamicMetaObjectProvider, then you can use reflection same as for any other object. Something like:
var propertyInfo = test.GetType().GetProperties();
However, for IDynamicMetaObjectProvider implementations, the simple reflection doesn't work. Basically, you need to know more about this object. If it is ExpandoObject (which is one of the IDynamicMetaObjectProvider implementations), you can use the answer provided by itowlson. ExpandoObject stores its properties in a dictionary and you can simply cast your dynamic object to a dictionary.
If it's DynamicObject (another IDynamicMetaObjectProvider implementation), then you need to use whatever methods this DynamicObject exposes. DynamicObject isn't required to actually "store" its list of properties anywhere. For example, it might do something like this (I'm reusing an example from my blog post):
public class SampleObject : DynamicObject
{
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = binder.Name;
return true;
}
}
In this case, whenever you try to access a property (with any given name), the object simply returns the name of the property as a string.
dynamic obj = new SampleObject();
Console.WriteLine(obj.SampleProperty);
//Prints "SampleProperty".
So, you don't have anything to reflect over - this object doesn't have any properties, and at the same time all valid property names will work.
I'd say for IDynamicMetaObjectProvider implementations, you need to filter on known implementations where you can get a list of properties, such as ExpandoObject, and ignore (or throw an exception) for the rest.
I solved the same problem following this example:
This example uses the jQuery JavaScript library.
First, create an Ajax icon using the AjaxLoad site.
Then add the following to your HTML :
<img src="/images/loading.gif" id="loading-indicator" style="display:none" />
And the following to your CSS file:
#loading-indicator {
position: absolute;
left: 10px;
top: 10px;
}
Lastly, you need to hook into the Ajax events that jQuery provides; one event handler for when the Ajax request begins, and one for when it ends:
$(document).ajaxSend(function(event, request, settings) {
$('#loading-indicator').show();
});
$(document).ajaxComplete(function(event, request, settings) {
$('#loading-indicator').hide();
});
This solution is from the following link. How to display an animated icon during Ajax request processing
I know this question is answered still and I am not trying to be smart here. I'll just want to share another method on this topic.
Download applications with apk grail
APK Grail providing the free zip file of the application.
Two-way binding means that any data-related changes affecting the model are immediately propagated to the matching view(s), and that any changes made in the view(s) (say, by the user) are immediately reflected in the underlying model. When app data changes, so does the UI, and conversely.
This is a very solid concept to build a web application on top of, because it makes the "Model" abstraction a safe, atomic data source to use everywhere within the application. Say, if a model, bound to a view, changes, then its matching piece of UI (the view) will reflect that, no matter what. And the matching piece of UI (the view) can safely be used as a mean of collecting user inputs/data, so as to maintain the application data up-to-date.
A good two-way binding implementation should obviously make this connection between a model and some view(s) as simple as possible, from a developper point of view.
It is then quite untrue to say that Backbone does not support two-way binding: while not a core feature of the framework, it can be performed quite simply using Backbone's Events though. It costs a few explicit lines of code for the simple cases; and can become quite hazardous for more complex bindings. Here is a simple case (untested code, written on the fly just for the sake of illustration):
Model = Backbone.Model.extend
defaults:
data: ''
View = Backbone.View.extend
template: _.template("Edit the data: <input type='text' value='<%= data %>' />")
events:
# Listen for user inputs, and edit the model.
'change input': @setData
initialize: (options) ->
# Listen for model's edition, and trigger UI update
@listenTo @model, 'change:data', @render
render: ->
@$el.html @template(@model.attributes)
@
setData: (e) =>
e.preventDefault()
@model.set 'data', $(e.currentTarget).value()
model: new Model()
view = new View {el: $('.someEl'), model: model}
This is a pretty typical pattern in a raw Backbone application. As one can see, it requires a decent amount of (pretty standard) code.
AngularJS and some other alternatives (Ember, Knockout…) provide two-way binding as a first-citizen feature. They abstract many edge-cases under some DSL, and do their best at integrating two-way binding within their ecosystem. Our example would look something like this with AngularJS (untested code, see above):
<div ng-app="app" ng-controller="MainCtrl">
Edit the data:
<input name="mymodel.data" ng-model="mymodel.data">
</div>
angular.module('app', [])
.controller 'MainCtrl', ($scope) ->
$scope.mymodel = {data: ''}
Rather short!
But, be aware that some fully-fledged two-way binding extensions do exist for Backbone as well (in raw, subjective order of decreasing complexity): Epoxy, Stickit, ModelBinder…
One cool thing with Epoxy, for instance, is that it allows you to declare your bindings (model attributes <-> view's DOM element) either within the template (DOM), or within the view implementation (JavaScript). Some people strongly dislike adding "directives" to the DOM/template (such as the ng-* attributes required by AngularJS, or the data-bind attributes of Ember).
Taking Epoxy as an example, one can rework the raw Backbone application into something like this (…):
Model = Backbone.Model.extend
defaults:
data: ''
View = Backbone.Epoxy.View.extend
template: _.template("Edit the data: <input type='text' />")
# or, using the inline form: <input type='text' data-bind='value:data' />
bindings:
'input': 'value:data'
render: ->
@$el.html @template(@model.attributes)
@
model: new Model()
view = new View {el: $('.someEl'), model: model}
All in all, pretty much all "mainstream" JS frameworks support two-way binding. Some of them, such as Backbone, do require some extra work to make it work smoothly, but those are the same which do not enforce a specific way to do it, to begin with. So it is really about your state of mind.
Also, you may be interested in Flux, a different architecture for web applications promoting one-way binding through a circular pattern. It is based on the concept of fast, holistic re-rendering of UI components upon any data change to ensure cohesiveness and make it easier to reason about the code/dataflow. In the same trend, you might want to check the concept of MVI (Model-View-Intent), for instance Cycle.
text()
and node()
are node tests, in XPath terminology (compare).
Node tests operate on a set (on an axis, to be exact) of nodes and return the ones that are of a certain type. When no axis is mentioned, the child
axis is assumed by default.
There are all kinds of node tests:
node()
matches any node (the least specific node test of them all)text()
matches text nodes onlycomment()
matches comment nodes*
matches any element nodefoo
matches any element node named "foo"
processing-instruction()
matches PI nodes (they look like <?name value?>
).*
also matches attribute nodes, but only along the attribute
axis. @*
is a shorthand for attribute::*
. Attributes are not part of the child
axis, that's why a normal *
does not select them.This XML document:
<produce>
<item>apple</item>
<item>banana</item>
<item>pepper</item>
</produce>
represents the following DOM (simplified):
root node element node (name="produce") text node (value="\n ") element node (name="item") text node (value="apple") text node (value="\n ") element node (name="item") text node (value="banana") text node (value="\n ") element node (name="item") text node (value="pepper") text node (value="\n")
So with XPath:
/
selects the root node/produce
selects a child element of the root node if it has the name "produce"
(This is called the document element; it represents the document itself. Document element and root node are often confused, but they are not the same thing.) /produce/node()
selects any type of child node beneath /produce/
(i.e. all 7 children)/produce/text()
selects the 4 (!) whitespace-only text nodes/produce/item[1]
selects the first child element named "item"
/produce/item[1]/text()
selects all child text nodes (there's only one - "apple" - in this case)And so on.
So, your questions
/produce/item/text()
(3 nodes selected)//department/manager
(1 node selected)Notes
child
axis. You can change the axis by prefixing a different axis name. For example: //item/ancestor::produce
/produce/item[1]/text()
and string(/produce/item[1])
will be the same.Additional to putting the variable in quotation, one could also translate the output of the variable using tr
and converting spaces to newlines.
$ echo $var | tr " " "\n"
foo
bar
baz
Although this is a little more convoluted, it does add more diversity with the output as you can substitute any character as the separator between array variables.
Header file:--
@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
UICollectionView *_collectionView;
}
Implementation File:--
- (void)viewDidLoad
{
[super viewDidLoad];
self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
_collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
[_collectionView setDataSource:self];
[_collectionView setDelegate:self];
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
[_collectionView setBackgroundColor:[UIColor redColor]];
[self.view addSubview:_collectionView];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 15;
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];
cell.backgroundColor=[UIColor greenColor];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(50, 50);
}
Output---
Try something like this:
<div id="LoadingImage" style="display: none">
<img src="" />
</div>
<script>
function ajaxCall(){
$("#LoadingImage").show();
$.ajax({
type: "GET",
url: surl,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "true",
success: function(response) {
$("#LoadingImage").hide();
alert("Success");
},
error: function (xhr, status) {
$("#LoadingImage").hide();
alert('Unknown error ' + status);
}
});
}
</script>
if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
Image = Image.FromFile(@"c:\Images\test.jpg"),
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
OR
PictureBox picture = new PictureBox
{
Name = "pictureBox",
Size = new Size(100, 50),
Location = new Point(14, 17),
ImageLocation = @"c:\Images\test.jpg",
SizeMode = PictureBoxSizeMode.CenterImage
};
p.Controls.Add(picture);
i'm not sure where you put images in your folder structure but you can find the path as bellow
picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");
Here's one more approach by using SET
and FOR /F
@echo off
set "var=<?xml version="1.0" encoding="utf-8" ?>"
for /f "tokens=1* delims==" %%a in ('set var') do echo %%b
and you can beautify it like:
@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "print{[=for /f "tokens=1* delims==" %%a in ('set " & set "]}=') do echo %%b"
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "xml_line.1=<?xml version="1.0" encoding="utf-8" ?>"
set "xml_line.2=<root>"
set "xml_line.3=</root>"
%print{[% xml_line %]}%
Example for Transaction
begin tran tt
Your sql statements
if error occurred rollback tran tt else commit tran tt
As long as you have not executed commit tran tt , data will not be changed
Looks like your form is submitting which is the default behaviour, you can stop it with this:
<form action="" method="post" onsubmit="completeAndRedirect();return false;">
Seeing from your G++ version, you need to update it badly. C++11 has only been available since G++ 4.3. The most recent version is 4.7.
In versions pre-G++ 4.7, you'll have to use -std=c++0x
, for more recent versions you can use -std=c++11
.
Here is another way to loop through XML elements using JDOM.
List<Element> nodeNodes = inputNode.getChildren();
if (nodeNodes != null) {
for (Element nodeNode : nodeNodes) {
List<Element> elements = nodeNode.getChildren(elementName);
if (elements != null) {
elements.size();
nodeNodes.removeAll(elements);
}
}
If you do not really care about rounding, just added a toFixed(x) and then removing trailing 0es and the dot if necessary. It is not a fast solution.
function format(value, decimals) {
if (value) {
value = value.toFixed(decimals);
} else {
value = "0";
}
if (value.indexOf(".") < 0) { value += "."; }
var dotIdx = value.indexOf(".");
while (value.length - dotIdx <= decimals) { value += "0"; } // add 0's
return value;
}
static double Evaluate(string expression) {
var loDataTable = new DataTable();
var loDataColumn = new DataColumn("Eval", typeof (double), expression);
loDataTable.Columns.Add(loDataColumn);
loDataTable.Rows.Add(0);
return (double) (loDataTable.Rows[0]["Eval"]);
}
Explanation of how it works:
First, we make a table in the part var loDataTable = new DataTable();
, just like in a Data Base Engine (MS SQL for example).
Then, a column, with some specific parameters (var loDataColumn = new DataColumn("Eval", typeof (double), expression);
).
The "Eval"
parameter is the name of the column (ColumnName attribute).
typeof (double)
is the type of data to be stored in the column, which is equal to put System.Type.GetType("System.Double");
instead.
expression
is the string that the Evaluate
method receives, and is stored in the attribute Expression
of the column. This attribute is for a really specific purpose (obvious), which is that every row that's put on the column will be fullfilled with the "Expression", and it accepts practically wathever can be put in a SQL Query. Refer to http://msdn.microsoft.com/en-us/library/system.data.datacolumn.expression(v=vs.100).aspx to know what can be put in the Expression attribute, and how it's evaluated.
Then, loDataTable.Columns.Add(loDataColumn);
adds the column loDataColumn
to the loDataTable
table.
Then, a row is added to the table with a personalized column with a Expression attribute, done via loDataTable.Rows.Add(0);
. When we add this row, the cell of the column "Eval" of the table loDataTable
is fullfilled automatically with its "Expression" attribute, and, if it has operators and SQL Queries, etc, it's evaluated and then stored to the cell, so, here happens the "magic", the string with operators is evaluated and stored to a cell...
Finally, just return the value stored to the cell of the column "Eval" in row 0 (it's an index, starts counting from zero), and making a conversion to a double with return (double) (loDataTable.Rows[0]["Eval"]);
.
And that's all... job done!
And here a code eaiser to understand, which does the same... It's not inside a method, and it's explained too.
DataTable MyTable = new DataTable();
DataColumn MyColumn = new DataColumn();
MyColumn.ColumnName = "MyColumn";
MyColumn.Expression = "5+5/5"
MyColumn.DataType = typeof(double);
MyTable.Columns.Add(MyColumn);
DataRow MyRow = MyTable.NewRow();
MyTable.Rows.Add(MyRow);
return (double)(MyTable.Rows[0]["MyColumn"]);
First, create the table with DataTable MyTable = new DataTable();
Then, a column with DataColumn MyColumn = new DataColumn();
Next, we put a name to the column. This so we can search into it's contents when it's stored to the table. Done via MyColumn.ColumnName = "MyColumn";
Then, the Expression, here we can put a variable of type string, in this case there's a predefined string "5+5/5", which result is 6.
The type of data to be stored to the column MyColumn.DataType = typeof(double);
Add the column to the table... MyTable.Columns.Add(MyColumn);
Make a row to be inserted to the table, which copies the table structure DataRow MyRow = MyTable.NewRow();
Add the row to the table with MyTable.Rows.Add(MyRow);
And return the value of the cell in row 0 of the column MyColumn
of the table MyTable
with return (double)(MyTable.Rows[0]["MyColumn"]);
Lesson done!!!
Check this fiddle. You are going to need to take a look at using border-collapse and border-spacing. There are some quirks for IE (as usual). This is based on an answer to this question.
table.test td {
background-color: lime;
margin: 12px 12px 12px 12px;
padding: 12px 12px 12px 12px;
}
table.test {
border-collapse: separate;
border-spacing: 10px;
*border-collapse: expression('separate', cellSpacing='10px');
}
_x000D_
<table class="test">
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
<tr>
<td>Cell</td>
<td>Cell</td>
<td>Cell</td>
</tr>
</table>
_x000D_
I'll mention the more obvious way of dealing with duplicates in lists. In terms of complexity, dictionaries are the way to go because each lookup is O(1). You can be more clever if you're only interested in duplicates...
my_list = [1,1,2,3,4,5,5]
my_dict = {}
for (ind,elem) in enumerate(my_list):
if elem in my_dict:
my_dict[elem].append(ind)
else:
my_dict.update({elem:[ind]})
for key,value in my_dict.iteritems():
if len(value) > 1:
print "key(%s) has indices (%s)" %(key,value)
which prints the following:
key(1) has indices ([0, 1])
key(5) has indices ([5, 6])
<form enctype='multipart/form-data'>
<input onchange="alert(this.value); this.value=null; return false;" type='file'>
<br>
<input type='submit' value='Upload'>
</form>
this.value=null;
is only necessary for Chrome, Firefox will work fine just with return false;
Here is a FIDDLE
With JRE 8 on XP there is another way - to use MSI to deploy package.
or (silent way, usable in batch file etc..)
for %%I in ("*.msi") do if exist "%%I" msiexec.exe /i %%I /qn EULA=0 SKIPLICENSE=1 PROG=0 ENDDIALOG=0
Promo graphic
The promo graphic is used for promotions on older versions of the Android OS (earlier than 4.0). This image is not required to submit an update for your Store Listing.
Requirements
- JPG or 24-bit PNG (no alpha)
- Dimensions: 180px by 120px
https://support.google.com/googleplay/android-developer/answer/1078870
Bootstrap 3 now has Responsive tables out of the box. Hooray! :)
You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive
Add a <div class="table-responsive">
surrounding your table and you should be good to go:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
To make it work on all layouts you can do this:
.table-responsive
{
overflow-x: auto;
}
Please make sure you are using latest jdbc connector as per the mysql. I was facing this problem and when I replaced my old jdbc connector with the latest one, the problem was solved.
You can download latest jdbc driver from https://dev.mysql.com/downloads/connector/j/
Select Operating System as Platform Independent. It will show you two options. One as tar and one as zip. Download the zip and extract it to get the jar file and replace it with your old connector.
This is not only for hibernate framework, it can be used with any platform which requires a jdbc connector.
STEP 1
See npm ls | grep ejs
at root level of your project to check if you have already added ejs
dependency
to your project.
If not, add it as dependencies
to your project. (I prefer adding dependency to package.json
instead of npm install
ing the module.)
eg.
{
"name": "musicpedia",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www"
},
"dependencies": {
"body-parser": "~1.15.1",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"express": "~4.13.4",
"jade": "~1.11.0",
"ejs": "^1.0.0",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0"
}
}
STEP 2 download the dependencies
npm install
STEP 3 check ejs module
$ npm ls | grep ejs
[email protected] /Users/prayagupd/nodejs-fkers/musicpedia
+-- [email protected]
Your regex won't match anything, as it is. You definitely need to remove the quotes -- the "/"
characters are sufficient.
/^\s+$/
is checking whether the string is ALL whitespace:
^
matches the start of the string.\s+
means at least 1, possibly more, spaces.$
matches the end of the string.Try replacing the regex with /\s/
(and no quotes)
select n1.name, n1.author_id, cast(count_1 as numeric)/total_count
from (select id, name, author_id, count(1) as count_1
from names
group by id, name, author_id) n1
inner join (select distinct(author_id), count(1) as total_count
from names) n2
on (n2.author_id = n1.author_id)
Where true
used distinct
if more inner join, because more join group performance is slow
I also had this problem with implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
.
The solution for me was to go File
-> Invalidate Caches / Restart
-> Invalidate
-> Close Project
-> Remove project from project window -> Open Project
(from project window).
A very easy way is to use jQuery and SimpleModal plugin. Then when I need to show my "loading" gif on submit, I do:
$('*').css('cursor','wait');
$.modal("<table style='white-space: nowrap'><tr><td style='white-space: nowrap'><b>Please wait...</b></td><td><img alt='Please wait' src='loader.gif' /></td></tr></table>", {escClose:false} );
First create a Project With PdfCreation in Android Studio
Then Follow below steps:
1.Download itextpdf-5.3.2.jar library from this link [https://sourceforge.net/projects/itext/files/iText/iText5.3.2/][1] and then
2.Add to app>libs>itextpdf-5.3.2.jar
3.Right click on jar file then click on add to library
4. Document document = new Document(PageSize.A4); // Create Directory in External Storage
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/PDF");
System.out.print(myDir.toString());
myDir.mkdirs(); // Create Pdf Writer for Writting into New Created Document
try {
PdfWriter.getInstance(document, new FileOutputStream(FILE));
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} // Open Document for Writting into document
document.open(); // User Define Method
addMetaData(document);
try {
addTitlePage(document);
} catch (DocumentException e) {
e.printStackTrace();
} // Close Document after writting all content
document.close();
5. public void addMetaData(Document document)
{
document.addTitle("RESUME");
document.addSubject("Person Info");
document.addKeywords("Personal, Education, Skills");
document.addAuthor("TAG");
document.addCreator("TAG");
}
public void addTitlePage(Document document) throws DocumentException
{ // Font Style for Document
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 22, Font.BOLD
| Font.UNDERLINE, BaseColor.GRAY);
Font smallBold = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
Font normal = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.NORMAL); // Start New Paragraph
Paragraph prHead = new Paragraph(); // Set Font in this Paragraph
prHead.setFont(titleFont); // Add item into Paragraph
prHead.add("RESUME – Name\n"); // Create Table into Document with 1 Row
PdfPTable myTable = new PdfPTable(1); // 100.0f mean width of table is same as Document size
myTable.setWidthPercentage(100.0f); // Create New Cell into Table
PdfPCell myCell = new PdfPCell(new Paragraph(""));
myCell.setBorder(Rectangle.BOTTOM); // Add Cell into Table
myTable.addCell(myCell);
prHead.setFont(catFont);
prHead.add("\nName1 Name2\n");
prHead.setAlignment(Element.ALIGN_CENTER); // Add all above details into Document
document.add(prHead);
document.add(myTable);
document.add(myTable); // Now Start another New Paragraph
Paragraph prPersinalInfo = new Paragraph();
prPersinalInfo.setFont(smallBold);
prPersinalInfo.add("Address 1\n");
prPersinalInfo.add("Address 2\n");
prPersinalInfo.add("City: SanFran. State: CA\n");
prPersinalInfo.add("Country: USA Zip Code: 000001\n");
prPersinalInfo.add("Mobile: 9999999999 Fax: 1111111 Email: [email protected] \n");
prPersinalInfo.setAlignment(Element.ALIGN_CENTER);
document.add(prPersinalInfo);
document.add(myTable);
document.add(myTable);
Paragraph prProfile = new Paragraph();
prProfile.setFont(smallBold);
prProfile.add("\n \n Profile : \n ");
prProfile.setFont(normal);
prProfile.add("\nI am Mr. XYZ. I am Android Application Developer at TAG.");
prProfile.setFont(smallBold);
document.add(prProfile); // Create new Page in PDF
document.newPage();
}
By the way, it's worth noting that some mobile devices, particularly Apple products like iPhone/iPad completely ignore headers like no-cache, no-store, Expires: 0, or whatever else you may try to force them to not re-use expired form pages.
This has caused us no end of headaches as we try to get the issue of a user's iPad say, being left asleep on a page they have reached through a form process, say step 2 of 3, and then the device totally ignores the store/cache directives, and as far as I can tell, simply takes what is a virtual snapshot of the page from its last state, that is, ignoring what it was told explicitly, and, not only that, taking a page that should not be stored, and storing it without actually checking it again, which leads to all kinds of strange Session issues, among other things.
I'm just adding this in case someone comes along and can't figure out why they are getting session errors with particularly iphones and ipads, which seem by far to be the worst offenders in this area.
I've done fairly extensive debugger testing with this issue, and this is my conclusion, the devices ignore these directives completely.
Even in regular use, I've found that some mobiles also totally fail to check for new versions via say, Expires: 0 then checking last modified dates to determine if it should get a new one.
It simply doesn't happen, so what I was forced to do was add query strings to the css/js files I needed to force updates on, which tricks the stupid mobile devices into thinking it's a file it does not have, like: my.css?v=1, then v=2 for a css/js update. This largely works.
User browsers also, by the way, if left to their defaults, as of 2016, as I continuously discover (we do a LOT of changes and updates to our site) also fail to check for last modified dates on such files, but the query string method fixes that issue. This is something I've noticed with clients and office people who tend to use basic normal user defaults on their browsers, and have no awareness of caching issues with css/js etc, almost invariably fail to get the new css/js on change, which means the defaults for their browsers, mostly MSIE / Firefox, are not doing what they are told to do, they ignore changes and ignore last modified dates and do not validate, even with Expires: 0 set explicitly.
This was a good thread with a lot of good technical information, but it's also important to note how bad the support for this stuff is in particularly mobile devices. Every few months I have to add more layers of protection against their failure to follow the header commands they receive, or to properly interpet those commands.
This issue occurs because of web application security model policy that is Same Origin Policy Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. That means requester must match the exact host, protocol, and port of requesting site.
We have multiple options to over come this CORS header issue.
Using Proxy - In this solution we will run a proxy such that when request goes through the proxy it will appear like it is some same origin. If you are using the nodeJS you can use cors-anywhere to do the proxy stuff. https://www.npmjs.com/package/cors-anywhere.
Example:-
var host = process.env.HOST || '0.0.0.0';
var port = process.env.PORT || 8080;
var cors_proxy = require('cors-anywhere');
cors_proxy.createServer({
originWhitelist: [], // Allow all origins
requireHeader: ['origin', 'x-requested-with'],
removeHeaders: ['cookie', 'cookie2']
}).listen(port, host, function() {
console.log('Running CORS Anywhere on ' + host + ':' + port);
});
JSONP - JSONP is a method for sending JSON data without worrying about cross-domain issues.It does not use the XMLHttpRequest object.It uses the <script>
tag instead. https://www.w3schools.com/js/js_json_jsonp.asp
Server Side - On server side we need to enable cross-origin requests. First we will get the Preflighted requests (OPTIONS) and we need to allow the request that is status code 200 (ok).
Preflighted requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if it uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted. It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
If you are using the spring just adding the bellow code will resolves the issue. Here I have disabled the csrf token that doesn't matter enable/disable according to your requirement.
@SpringBootApplication
public class SupplierServicesApplication {
public static void main(String[] args) {
SpringApplication.run(SupplierServicesApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**").allowedOrigins("*");
}
};
}
}
If you are using the spring security use below code along with above code.
@Configuration
@EnableWebSecurity
public class SupplierSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll().antMatchers("/**").authenticated().and()
.httpBasic();
}
}
In simple terms you need to build your payload into a key array
payload = {'key1': 'value1', 'key2': 'value2'}
Then send the payload directly to the action
this.$store.dispatch('yourAction', payload)
No change in your action
yourAction: ({commit}, payload) => {
commit('YOUR_MUTATION', payload )
},
In your mutation call the values with the key
'YOUR_MUTATION' (state, payload ){
state.state1 = payload.key1
state.state2 = payload.key2
},
application/vnd.ms-excel
vnd class
/ vendor specificHere's an example that will center the content within the parent div. This also makes sure the overlay starts at the edge of the video, even when centered.
<div class="outer-container">
<div class="inner-container">
<div class="video-overlay">Bug Buck Bunny - Trailer</div>
<video id="player" src="http://video.webmfiles.org/big-buck-bunny_trailer.webm" controls autoplay loop></video>
</div>
</div>
with css as
.outer-container {
border: 1px dotted black;
width: 100%;
height: 100%;
text-align: center;
}
.inner-container {
border: 1px solid black;
display: inline-block;
position: relative;
}
.video-overlay {
position: absolute;
left: 0px;
top: 0px;
margin: 10px;
padding: 5px 5px;
font-size: 20px;
font-family: Helvetica;
color: #FFF;
background-color: rgba(50, 50, 50, 0.3);
}
video {
width: 100%;
height: 100%;
}
here's the jsfiddle https://jsfiddle.net/dyrepk2x/2/
Hope that helps :)
Try SchedulerBinding,
SchedulerBinding.instance
.addPostFrameCallback((_) => setState(() {
isDataFetched = true;
}));
If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8
into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.
You can use inWaiting()
to get the amount of bytes available at the input queue.
Then you can use read()
to read the bytes, something like that:
While True:
bytesToRead = ser.inWaiting()
ser.read(bytesToRead)
Why not to use readline()
at this case from Docs:
Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.
You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)
SshClient cSSH = new SshClient("192.168.10.144", 22, "root", "pacaritambo");
cSSH.Connect();
SshCommand x = cSSH.RunCommand("exec \"/var/lib/asterisk/bin/retrieve_conf\"");
cSSH.Disconnect();
cSSH.Dispose();
//using SSH.Net
This is more an add-on to the best answer above (GZip Compression can be enabled directly through IIS) which is correct if your running IIS on Windows desktop however...
If your running IIS on Windows Server, this content compression feature is found in a different place to desktop Windows (not in programs and features in Control Panel). First open "Server Manager" then click Manage -> "Add Roles & Features" then keep clicking NEXT (make sure you select the correct server when you see the list of servers if your managing multiple servers from this instance) until you get to SERVER ROLES, scroll down to and open "Web Server (IIS)..." then "Web Server" then "Performance" then tick "Dynamic Content Compression" then click INSTALL. I tested this on Server 2016 Standard so there may be slight differences if your on an earlier version of Server.
Then follow the instructions from Testing - Check if GZIP Compression is Enabled
Their is no agreement on the rest api response formats of big software giants - Google, Facebook, Twitter, Amazon and others, though many links have been provided in the answers above, where some people have tried to standardize the response format.
As needs of the API's can differ it is very difficult to get everyone on board and agree to some format. If you have millions of users using your API, why would you change your response format?
Following is my take on the response format inspired by Google, Twitter, Amazon and some posts on internet:
https://github.com/adnan-kamili/rest-api-response-format
Swagger file:
You can turn on your PHP errors with error_reporting
:
error_reporting(E_ALL);
ini_set('display_errors', 'on');
Edit: It's possible that even after putting this, errors still don't show up. This can be caused if there is a fatal error in the script. From PHP Runtime Configuration:
Although display_errors may be set at runtime (with ini_set()), it won't have any affect if the script has fatal errors. This is because the desired runtime action does not get executed.
You should set display_errors = 1
in your php.ini
file and restart the server.
Error can be caused by various issues. for more info check suexec or fcgi logs. For example if suexec has wrong user and permssion it can cause the error to occur to solve try
chgrp WEBGROUP /usr/local/apache2/bin/suexec
chmod 4750 /usr/local/apache2/bin/suexec
Note in 2018: readAsBinaryString
is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer
(or in some cases, readAsDataURL
) instead.
readAsBinaryString
says that the data must be represented as a binary string, where:
...every byte is represented by an integer in the range [0..255].
JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)
If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText
and readAsBinaryString
, but with readAsBinaryString
you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText
, because readAsText
will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
font-family: sans-serif;
}
</style>
<script type='text/javascript'>
function loadFile() {
var input, file, fr;
if (typeof window.FileReader !== 'function') {
bodyAppend("p", "The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('fileinput');
if (!input) {
bodyAppend("p", "Um, couldn't find the fileinput element.");
}
else if (!input.files) {
bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
}
else if (!input.files[0]) {
bodyAppend("p", "Please select a file before clicking 'Load'");
}
else {
file = input.files[0];
fr = new FileReader();
fr.onload = receivedText;
fr.readAsText(file);
}
function receivedText() {
showResult(fr, "Text");
fr = new FileReader();
fr.onload = receivedBinary;
fr.readAsBinaryString(file);
}
function receivedBinary() {
showResult(fr, "Binary");
}
}
function showResult(fr, label) {
var markup, result, n, aByte, byteStr;
markup = [];
result = fr.result;
for (n = 0; n < result.length; ++n) {
aByte = result.charCodeAt(n);
byteStr = aByte.toString(16);
if (byteStr.length < 2) {
byteStr = "0" + byteStr;
}
markup.push(byteStr);
}
bodyAppend("p", label + " (" + result.length + "):");
bodyAppend("pre", markup.join(" "));
}
function bodyAppend(tagName, innerHTML) {
var elm;
elm = document.createElement(tagName);
elm.innerHTML = innerHTML;
document.body.appendChild(elm);
}
</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>
If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13): 54 65 73 74 69 6e 67 20 31 20 32 20 33 Binary (28): ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see, readAsText
interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString
didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).
* XMLHttpRequest.response with responseType = "arraybuffer"
is supported in HTML 5.
** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.
System.out.println(Integer.toHexString(test[0]));
OR (pretty print)
System.out.printf("0x%02X", test[0]);
OR (pretty print)
System.out.println(String.format("0x%02X", test[0]));
I found a website with a "simple" tutorial: http://www.winprog.org/tutorial/start.html
One of the reason may be if any one of table column have an underscore(_) in its name . That is considered as invalid characters by the JDBC . Rename the column by a ALTER Command and change in your code SQL , that will fix .
I had the same question. While there are good answers here I decided to create a table-valued function. With a table (or scalar) valued function you don't have to change your stored proc. I simply did a select from the table-valued function. Note that the parameter (MyParameter is optional).
CREATE FUNCTION [dbo].[MyDateFunction]
(@MyParameter varchar(max))
RETURNS TABLE
AS
RETURN
(
--- Query your table or view or whatever and select the results.
SELECT DateValue FROM MyTable WHERE ID = @MyParameter;
)
To assign to your variable you simply can do something like:
Declare @MyDate datetime;
SET @MyDate = (SELECT DateValue FROM MyDateFunction(@MyParameter));
You can also use a scalar valued function:
CREATE FUNCTION TestDateFunction()
RETURNS datetime
BEGIN
RETURN (SELECT GetDate());
END
Then you can simply do
Declare @MyDate datetime;
SET @MyDate = (Select dbo.TestDateFunction());
SELECT @MyDate;
It was giving Illegal Exception.
My workaround with code:
public void dofirst(){
System.setProperty("webdriver.chrome.driver","D:\\Softwares\\selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.facebook.com");
}
Yes you can!
As of November 2016, Microsoft now has integrated .NET Core in it's official .NET Site
They even have a new Visual Studio app that runs on MacOS
This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.
On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it
error instead when making a request to a local URL that is not served, eg: localhost:5000
. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:
[Errno 99] Cannot assign requested address
(if called from within the container), or[Errno 0] Error
(if called from outside of the container).You can reproduce this error and the behaviour described above as follows:
Start a dummy container (note: this will pull the python image if not found locally):
docker run --name serv1 -p 5000:5000 -dit python
Then for [Errno 0] Error
enter a Python console on host, while for [Errno 99] Cannot assign requested address
access a Python console on the container by calling:
docker exec -it -u 0 serv1 python
And then in either case call:
import urllib.request
urllib.request.urlopen('https://localhost:5000')
I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it
rather than trying to fix their cause - although please advise if that's a bad idea.
I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address
point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl
conflicts, docker network issues, TIME_WAIT
being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.
facing similar problem to you. In my case I have 1000's of files from cisco logs that I need to parse manually.
In order to be flexible with fields and types I have successfully tested using StringIO + read_cvs which indeed does accept a dict for the dtype specification.
I usually get each of the files ( 5k-20k lines) into a buffer and create the dtype dictionaries dynamically.
Eventually I concatenate ( with categorical... thanks to 0.19) these dataframes into a large data frame that I dump into hdf5.
Something along these lines
import pandas as pd
import io
output = io.StringIO()
output.write('A,1,20,31\n')
output.write('B,2,21,32\n')
output.write('C,3,22,33\n')
output.write('D,4,23,34\n')
output.seek(0)
df=pd.read_csv(output, header=None,
names=["A","B","C","D"],
dtype={"A":"category","B":"float32","C":"int32","D":"float64"},
sep=","
)
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 4 columns):
A 5 non-null category
B 5 non-null float32
C 5 non-null int32
D 5 non-null float64
dtypes: category(1), float32(1), float64(1), int32(1)
memory usage: 205.0 bytes
None
Not very pythonic.... but does the job
Hope it helps.
JC
"Visual Studio does not support std::cout as debug tool for non-console applications"
- from Marius Amado-Alves' answer to "How can I see cout output in a non-console application?"
Which means if you use it, Visual Studio shows nothing in the "output" window (in my case VS2008)
Simplest solution for line numbers in php storm..There are many other solutions but i think A big picture a good from 1000 words.
To check if a string is just a spaces or newline
Use this simple code
mystr = " \n \r \t "
if not mystr.strip(): # The String Is Only Spaces!
print("\n[!] Invalid String !!!")
exit(1)
mystr = mystr.strip()
print("\n[*] Your String Is: "+mystr)
If you want to check if the string represents an integer that fits in an int type, I did a little modification to the jonas' answer, so that strings that represent integers bigger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE, will now return false. For example: "3147483647" will return false because 3147483647 is bigger than 2147483647, and likewise, "-2147483649" will also return false because -2147483649 is smaller than -2147483648.
public static boolean isInt(String s) {
if(s == null) {
return false;
}
s = s.trim(); //Don't get tricked by whitespaces.
int len = s.length();
if(len == 0) {
return false;
}
//The bottom limit of an int is -2147483648 which is 11 chars long.
//[note that the upper limit (2147483647) is only 10 chars long]
//Thus any string with more than 11 chars, even if represents a valid integer,
//it won't fit in an int.
if(len > 11) {
return false;
}
char c = s.charAt(0);
int i = 0;
//I don't mind the plus sign, so "+13" will return true.
if(c == '-' || c == '+') {
//A single "+" or "-" is not a valid integer.
if(len == 1) {
return false;
}
i = 1;
}
//Check if all chars are digits
for(; i < len; i++) {
c = s.charAt(i);
if(c < '0' || c > '9') {
return false;
}
}
//If we reached this point then we know for sure that the string has at
//most 11 chars and that they're all digits (the first one might be a '+'
// or '-' thought).
//Now we just need to check, for 10 and 11 chars long strings, if the numbers
//represented by the them don't surpass the limits.
c = s.charAt(0);
char l;
String limit;
if(len == 10 && c != '-' && c != '+') {
limit = "2147483647";
//Now we are going to compare each char of the string with the char in
//the limit string that has the same index, so if the string is "ABC" and
//the limit string is "DEF" then we are gonna compare A to D, B to E and so on.
//c is the current string's char and l is the corresponding limit's char
//Note that the loop only continues if c == l. Now imagine that our string
//is "2150000000", 2 == 2 (next), 1 == 1 (next), 5 > 4 as you can see,
//because 5 > 4 we can guarantee that the string will represent a bigger integer.
//Similarly, if our string was "2139999999", when we find out that 3 < 4,
//we can also guarantee that the integer represented will fit in an int.
for(i = 0; i < len; i++) {
c = s.charAt(i);
l = limit.charAt(i);
if(c > l) {
return false;
}
if(c < l) {
return true;
}
}
}
c = s.charAt(0);
if(len == 11) {
//If the first char is neither '+' nor '-' then 11 digits represent a
//bigger integer than 2147483647 (10 digits).
if(c != '+' && c != '-') {
return false;
}
limit = (c == '-') ? "-2147483648" : "+2147483647";
//Here we're applying the same logic that we applied in the previous case
//ignoring the first char.
for(i = 1; i < len; i++) {
c = s.charAt(i);
l = limit.charAt(i);
if(c > l) {
return false;
}
if(c < l) {
return true;
}
}
}
//The string passed all tests, so it must represent a number that fits
//in an int...
return true;
}
As @Alexander solves, the issue is one of async data load - you're rendering immediately and you will not have participants loaded until the async ajax call resolves and populates data
with participants
.
The alternative to the solution they provided would be to prevent render until participants exist, something like this:
render: function() {
if (!this.props.data.participants) {
return null;
}
return (
<ul className="PlayerList">
// I'm the Player List {this.props.data}
// <Player author="The Mini John" />
{
this.props.data.participants.map(function(player) {
return <li key={player}>{player}</li>
})
}
</ul>
);
}
Xauthority becomes an issue with newer systems. I can either discard any protection with xhost + before running my docker containers, or I can pass in a well prepared Xauthority file. Typical Xauthority files are hostname specific. With docker, each container can have a different host name (set with docker run -h), but even setting the hostname of the container identical to the host system did not help in my case. xeyes (I like this example) simply would ignore the magic cookie and pass no credentials to the server. Hence we get an error message 'No protocol specified Cannot open display'
The Xauthority file can be written in a way so that the hostname does not matter. We need to set the Authentication Family to 'FamilyWild'. I am not sure, if xauth has a proper command line for this, so here is an example that combines xauth and sed to do that. We need to change the first 16 bits of the nlist output. The value of FamilyWild is 65535 or 0xffff.
docker build -t xeyes - << __EOF__
FROM debian
RUN apt-get update
RUN apt-get install -qqy x11-apps
ENV DISPLAY :0
CMD xeyes
__EOF__
XSOCK=/tmp/.X11-unix
XAUTH=/tmp/.docker.xauth
xauth nlist :0 | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge -
docker run -ti -v $XSOCK:$XSOCK -v $XAUTH:$XAUTH -e XAUTHORITY=$XAUTH xeyes
C:\>wmic datafile where name="C:\\Windows\\System32\\kernel32.dll" get version
Version
6.1.7601.18229
Try this:
<li onclick="getPaging(this.id)" id="1">1</li>
<li onclick="getPaging(this.id)" id="2">2</li>
function getPaging(str)
{
$("#loading-content").load("dataSearch.php?"+str, hideLoader);
}
You can interrogate the thread instance with getState() which returns an instance of Thread.State enumeration with one of the following values:
* NEW
A thread that has not yet started is in this state.
* RUNNABLE
A thread executing in the Java virtual machine is in this state.
* BLOCKED
A thread that is blocked waiting for a monitor lock is in this state.
* WAITING
A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
* TIMED_WAITING
A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
* TERMINATED
A thread that has exited is in this state.
However I think it would be a better design to have a master thread which waits for the 3 children to finish, the master would then continue execution when the other 3 have finished.
This worked for me:
<dependency>
<groupId>jdk.tools</groupId>
<artifactId>jdk.tools</artifactId>
<version>1.7.0_05</version>
<scope>system</scope>
<systemPath>${JAVA_HOME}/lib/tools.jar</systemPath>
</dependency>
you can use Realm or Sqlite if you want to manage complex data type.
Otherwise go with inbuilt react native asynstorage
1) you can float the image to the left:
<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">
2)You can use an HTML table to place elements on one line.
Code below
<div class="navigation-bar">
<div id="navigation-container">
<table>
<tr>
<td><img src="http://i.imgur.com/hCrQkJi.png"></td>
<td><ul>
<li><a href="#">Home</a></li>
<li><a href="#">Projects</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Get in Touch</a></li>
</ul>
</td></tr></table>
</div>
The lookup time is slow because when you use mmap
to does not load content of array to memory when you invoke load
method. Data is lazy loaded when particular data is needed.
And this happens in lookup in your case. But second lookup won`t be so slow.
This is nice feature of mmap
when you have a big array you do not have to load whole data into memory.
To solve your can use joblib you can dump any object you want using joblib.dump
even two or more numpy arrays
, see the example
firstArray = np.arange(100)
secondArray = np.arange(50)
# I will put two arrays in dictionary and save to one file
my_dict = {'first' : firstArray, 'second' : secondArray}
joblib.dump(my_dict, 'file_name.dat')
Here are a couple good sites to check out for that,
http://www.tripwiremagazine.com/2011/10/css-menu-and-navigation.html (Lots of examples)
http://webdesignerwall.com/tutorials/css3-dropdown-menu (1 example more tutorial like)
Hope this is helpful information!
With C++11 you can now do
struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);
see std::get_time and strftime for reference
The complete example for Express.js, API calling case and sending JSON content is the following:
...
app.get('/api/myApi', (req, res) => {
MongoClient.connect('mongodb://user:[email protected]:port/dbname',
{ useNewUrlParser: true }, (err, db) => {
if (err) throw err
const dbo = db.db('dbname')
dbo.collection('myCollection')
.find({}, { _id: 0 })
.sort({ _id: -1 })
.toArray(
(errFind, result) => {
if (errFind) throw errFind
const resultJson = JSON.stringify(result)
console.log('find:', resultJson)
res.send(resultJson)
db.close()
},
)
})
}
You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?
Java 8 Style for a given date
LocalDate today = LocalDate.of(1982, Month.AUGUST, 31);
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.ENGLISH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.FRENCH)));
System.out.println(today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM).withLocale(Locale.JAPANESE)));
First set a custom attribute into your option for example nameid
(you can set non-standardized attribute of an HTML element, it's allowed):
'<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'
then you can easily get attribute value using jquery .attr()
:
$('option:selected').attr("nameid")
For Example:
<select id="jobSel" class="longcombo" onchange="GetNameId">
<option nameid="32" value="1">test1</option>
<option nameid="67" value="1">test2</option>
<option nameid="45" value="1">test3</option>
</select>
Jquery:
function GetNameId(){
alert($('#jobSel option:selected').attr("nameid"));
}
This function will validate the date to see if it's correct or if it's in the proper format of: DD/MM/YYYY.
function isValidDate(date)
{
var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
if (matches == null) return false;
var d = matches[1];
var m = matches[2]-1;
var y = matches[3];
var composedDate = new Date(y, m, d);
return composedDate.getDate() == d &&
composedDate.getMonth() == m &&
composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));
Using the RESTORE DATABASE
command most likely. bak
is a common extension used for a database backup file. You'll find documentation for this command on MSDN.
widget['bg'] = '#000000'
or
widget['background'] = '#000000'
would also work as hex-valued colors are also accepted.
I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:
%W[
It's a nice day "#{name}"
for a walk!
].join(' ')
where name = 'fred'
this produces It's a nice day "fred" for a walk!
Just a quick note because I had a hard time with this.
By using #container { overflow: hidden; } the page I had started to have layout issues in Firefox and IE (when the zoom would go in and out the content would bounce in and out of the parent div).
The solution to this issue is to add a display: inline-block; to the same div with overflow:hidden;
If you want to set the height of a <div>
or any element, you should set the height of <body>
and <html>
to 100% too. Then you can set the height of element with 100% :)
Here is an example:
body, html {
height: 100%;
}
#right {
height: 100%;
}
AF_INET
is an address family that is used to designate the type of addresses that your socket can communicate with (in this case, Internet Protocol v4 addresses). When you create a socket, you have to specify its address family, and then you can only use addresses of that type with the socket. The Linux kernel, for example, supports 29 other address families such as UNIX (AF_UNIX
) sockets and IPX (AF_IPX
), and also communications with IRDA and Bluetooth (AF_IRDA
and AF_BLUETOOTH
, but it is doubtful you'll use these at such a low level).
For the most part, sticking with AF_INET
for socket programming over a network is the safest option. There is also AF_INET6
for Internet Protocol v6 addresses.
Hope this helps,
With little modification but almost similar approach to get the full file path of each sub folder
dataFolderPath = 'UCR_TS_Archive_2015/';
dirData = dir(dataFolderPath); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
fileList = {dirData(~dirIndex).name}'; %'# Get a list of the files
if ~isempty(fileList)
fileList = cellfun(@(x) fullfile(dataFolderPath,x),... %# Prepend path to files
fileList,'UniformOutput',false);
end
subDirs = {dirData(dirIndex).name}; %# Get a list of the subdirectories
validIndex = ~ismember(subDirs,{'.','..'}); %# Find index of subdirectories
%# that are not '.' or '..'
for iDir = find(validIndex) %# Loop over valid subdirectories
nextDir = fullfile(dataFolderPath,subDirs{iDir}); %# Get the subdirectory path
getAllFiles = dir(nextDir);
for k = 1:1:size(getAllFiles,1)
validFileIndex = ~ismember(getAllFiles(k,1).name,{'.','..'});
if(validFileIndex)
filePathComplete = fullfile(nextDir,getAllFiles(k,1).name);
fprintf('The Complete File Path: %s\n', filePathComplete);
end
end
end
For those who need save objects like {foo: 'bar'}, I share my edited version of @KevinBurke's answer. I've added JSON.stringify and JSON.parse, that's all.
cookie = {
set: function (name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else
var expires = "";
document.cookie = name + "=" + JSON.stringify(value) + expires + "; path=/";
},
get : function(name){
var nameEQ = name + "=",
ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return JSON.parse(c.substring(nameEQ.length,c.length));
}
return null;
}
}
So, now you can do things like this:
cookie.set('cookie_key', {foo: 'bar'}, 30);
cookie.get('cookie_key'); // {foo: 'bar'}
cookie.set('cookie_key', 'baz', 30);
cookie.get('cookie_key'); // 'baz'
string::c.str()
returns a string of type const char *
as seen here
A quick fix: try casting printfunc(num,addr,(char *)data.str().c_str())
;
While the above may work, it is undefined behaviour, and unsafe.
Here's a nicer solution using templates:
char * my_argument = const_cast<char*> ( ...c_str() );
viewStyle : {
backgroundColor: '#F8F8F8',
justifyContent: 'center',
alignItems: 'center',
height: 60,
paddingTop: 15,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
marginBottom: 10,
elevation: 2,
position: 'relative'
},
Use marginBottom: 10
Your data.json
should look like this:
{
"maps":[
{"id":"blabla","iscategorical":"0"},
{"id":"blabla","iscategorical":"0"}
],
"masks":
{"id":"valore"},
"om_points":"value",
"parameters":
{"id":"valore"}
}
Your code should be:
import json
from pprint import pprint
with open('data.json') as data_file:
data = json.load(data_file)
pprint(data)
Note that this only works in Python 2.6 and up, as it depends upon the with
-statement. In Python 2.5 use from __future__ import with_statement
, in Python <= 2.4, see Justin Peel's answer, which this answer is based upon.
You can now also access single values like this:
data["maps"][0]["id"] # will return 'blabla'
data["masks"]["id"] # will return 'valore'
data["om_points"] # will return 'value'
No need to use a macro. Supposing your first string is in A1.
=RIGHT(A1, 4)
Drag this down and you will get your four last characters.
Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()
=RIGHT(TRIMSPACES(A1), 4)
Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:
=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))
use this actiion
$(document).ready(function () {
var a = this.id;
alert (a);
});
I did not find a solution for my issue (first picture) anywhere, but at last I end up with a simplest solution after a few hours of digging. Please note that I tried with a lot of xml attributes like app:setInsetLeft="0dp"
, etc.. but none of them helped in this case.
the following code solved this issue as in the Picture 2
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//NOTE THAT: THE PART SOLVED THE PROBLEM.
android.support.design.widget.AppBarLayout abl = (AppBarLayout)
findViewById(R.id.app_bar_main_app_bar_layout);
abl.setPadding(0,0,0,0);
}
Picture 2
If you want to do this in jQuery instead of CSS, you basically follow the same process.
Assuming you have some <div id="target"></div>
, you can use the following code:
$("#target").hover(function() {
$(this).css('cursor','pointer');
}, function() {
$(this).css('cursor','auto');
});
and that should do it.
Whenever you have seen coding from open source community like Guava and from Google Developer (Android Library) they used this approach
List<String> strings = new ArrayList<String>();
because it's hide the implementation detail from user. You precisely
List<String> strings = new ArrayList<String>();
it's generic approach and this specialized approach
ArrayList<String> strings = new ArrayList<String>();
For Reference: Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces
I meet the same problem today, and solve it by the code follows.
html code:
<div style='display: none'>
<img id='img' src='img/iak.png' width='600' height='400' />
</div>
<canvas id='iak'>broswer don't support canvas</canvas>
js code:
var canvas = document.getElementById('iak')
var iakImg = document.getElementById('img')
var ctx = canvas.getContext('2d')
var image = new Image()
image.src=iakImg.src
image.onload = function () {
ctx.drawImage(image,0,0)
var data = ctx.getImageData(0,0,600,400)
}
code like above, and there is no cross-domain problem.
File protocol URIs are like this
file://[HOST]/[PATH]
that's why you often see file URLs like this (3 slashes) file:///c:\path...
So if the host is server01, you want
file://server01/folder/path....
This is according to the wikipedia page on file:// protocols and checks out with .NET's Uri.IsWellFormedUriString method.
If anyone came here trying to do this with a decimal like me:
myFloat = parseFloat(myString);
If you just need an Int, that's well covered in the other answers.
PHP's config can be set in multiple places:
php.ini
(usually in /etc somewhere)php_value
)php.ini
(use the command php -i | grep memory_limit
to check the CLI conf)php_value
)ini_set()
)In PHPinfo's output, the "Master" value is the compiled-in default value, and the "Local" value is what's actually in effect. It can be either unchanged from the default, or overridden in any of the above locations.
Also note that PHP generally has different .ini files for command-line and webserver-based operation. Checking phpinfo()
from the command line will report different values than if you'd run it in a web-based script.
You can also use reduce to merge them. Try this in the playground
let d1 = ["a":"foo","b":"bar"]
let d2 = ["c":"car","d":"door"]
let d3 = d1.reduce(d2) { (var d, p) in
d[p.0] = p.1
return d
}
From the Gnuplot documentation. To draw a vertical line from the bottom to the top of the graph at x=3, use:
set arrow from 3, graph 0 to 3, graph 1 nohead
Please check https://www.sqlite.org/lang_altertable.html#otheralter
The only schema altering commands directly supported by SQLite are the "rename table" and "add column" commands shown above. However, applications can make other arbitrary changes to the format of a table using a simple sequence of operations. The steps to make arbitrary changes to the schema design of some table X are as follows:
- If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF.
- Start a transaction.
- Remember the format of all indexes and triggers associated with table X. This information will be needed in step 8 below. One way to do this is to run a query like the following: SELECT type, sql FROM sqlite_master WHERE tbl_name='X'.
- Use CREATE TABLE to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
- Transfer content from X into new_X using a statement like: INSERT INTO new_X SELECT ... FROM X.
- Drop the old table X: DROP TABLE X.
- Change the name of new_X to X using: ALTER TABLE new_X RENAME TO X.
- Use CREATE INDEX and CREATE TRIGGER to reconstruct indexes and triggers associated with table X. Perhaps use the old format of the triggers and indexes saved from step 3 above as a guide, making changes as appropriate for the alteration.
- If any views refer to table X in a way that is affected by the schema change, then drop those views using DROP VIEW and recreate them with whatever changes are necessary to accommodate the schema change using CREATE VIEW.
- If foreign key constraints were originally enabled then run PRAGMA foreign_key_check to verify that the schema change did not break any foreign key constraints.
- Commit the transaction started in step 2.
- If foreign keys constraints were originally enabled, reenable them now.
The procedure above is completely general and will work even if the schema change causes the information stored in the table to change. So the full procedure above is appropriate for dropping a column, changing the order of columns, adding or removing a UNIQUE constraint or PRIMARY KEY, adding CHECK or FOREIGN KEY or NOT NULL constraints, or changing the datatype for a column, for example.
You can also use: finishAffinity()
Finish this activity as well as all activities immediately below it in the current task that have the same affinity.
You can use ancestor
. I find that this is easier to read because the element you are actually selecting is at the end of the path.
//span[contains(text(),'someText')]/ancestor::div[contains(@class, 'measure-tab')]
$a = "This", "Is", "a", "cat"
foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)
Write-Host $sent
A simple solution could be:
interface bar {
length: number;
}
let bars: bar[];
bars = [];
For Mountain Lion, Apple's java is up to 1.6.0_35-b10-428.jdk as of today.
It is indeed located under /Library/Java/JavaVirtualMachines .
You just download
"Java for OS X 2012-005 Developer Package" (Sept 6, 2012)
from
http://connect.apple.com/
In my view, Apple's naming is at least a bit confusing; why "-005" - is this the fifth version, or the fifth of five installers one needs?
And then run the installer; then follow the above steps inside Eclipse.
When you directly print print_r(($value['<YOUR_ARRAY>']-><YOUR_OBJECT>));
then it shows this fatal error Cannot use string offset as an object in
.
If you print like this
$var = $value['#node']-><YOU_OBJECT>;
print_r($var);
You won't get the error!!
Simple 2020 no-tricks method:
body {
display: flex;
flex-direction: column;
}
#footer {
margin-top: auto;
}
However -just for the record- this is invalid:
<address class="vcard">
<svg viewBox="0 0 800 400">
<rect width="800" height="400" fill="#000">
</svg>
</address>
And a slash here would make it valid again:
<rect width="800" height="400" fill="#000"/>