Since you return to the client just String
and its content type == 'text/plain'
, there is no any chance for default converters to determine how to convert String
response to the FFSampleResponseHttp
object.
The simple way to fix it:
expected-response-type
from <int-http:outbound-gateway>
replyChannel1
<json-to-object-transformer>
Otherwise you should write your own HttpMessageConverter
to convert the String to the appropriate object.
To make it work with MappingJackson2HttpMessageConverter
(one of default converters) and your expected-response-type
, you should send your reply with content type = 'application/json'
.
If there is a need, just add <header-enricher>
after your <service-activator>
and before sending a reply to the <int-http:inbound-gateway>
.
So, it's up to you which solution to select, but your current state doesn't work, because of inconsistency with default configuration.
UPDATE
OK. Since you changed your server to return FfSampleResponseHttp
object as HTTP response, not String, just add contentType = 'application/json'
header before sending the response for the HTTP and MappingJackson2HttpMessageConverter
will do the stuff for you - your object will be converted to JSON and with correct contentType
header.
From client side you should come back to the expected-response-type="com.mycompany.MyChannel.model.FFSampleResponseHttp"
and MappingJackson2HttpMessageConverter
should do the stuff for you again.
Of course you should remove <json-to-object-transformer>
from you message flow after <int-http:outbound-gateway>
.
I ran into a similar problem,
npm cache clean
solved it.
I use PyDev/LiClipse and haven't really figured out how to run all tests at once from the GUI. (edit: you right click the root test folder and choose Run as -> Python unit-test
This is my current workaround:
import unittest
def load_tests(loader, tests, pattern):
return loader.discover('.')
if __name__ == '__main__':
unittest.main()
I put this code in a module called all
in my test directory. If I run this module as a unittest from LiClipse then all tests are run. If I ask to only repeat specific or failed tests then only those tests are run. It doesn't interfere with my commandline test runner either (nosetests) -- it's ignored.
You may need to change the arguments to discover
based on your project setup.
I would put decimal.MaxValue.ToString()
since this is the effective ceiling for the decmial type it is equivalent to not having an upper bound.
OpenCV Specific
Opencv supports filesystem, probably through its dependency Boost.
#include <opencv2/core/utils/filesystem.hpp>
cv::utils::fs::createDirectory(outputDir);
That works fine. See this fiddle: http://jsfiddle.net/kveAL/
It is possible that you need to declare your jQuery in a $(document).ready()
handler?
Also, might you have two elements that have the same ID?
Jest's setupFiles
is the proper way to handle this, and you need not install dotenv
, nor use an .env
file at all, to make it work.
jest.config.js
:
module.exports = {
setupFiles: ["<rootDir>/.jest/setEnvVars.js"]
};
.jest/setEnvVars.js
:
process.env.MY_CUSTOM_TEST_ENV_VAR = 'foo'
That's it.
What helped me is:
Get rid of all old import paths and replace them with new ones like this:
import { Observable , BehaviorSubject } from 'rxjs';)
Delete node_modules
folder
npm cache verify
npm install
Change the content type to ms-excel in the html and browser shall open the html in the Excel as xls. If you want control over the transformation of HTML to excel use POI libraries to do so.
I would recommend wxpython. It's very easy to use and the documentation is pretty good.
You have to change delimiter before using triggers, stored procedures and so on.
delimiter //
create procedure ProG()
begin
SELECT * FROM hs_hr_employee_leave_quota;
end;//
delimiter ;
The KILL SESSION
command doesn't actually kill the session. It merely asks the session to kill itself. In some situations, like waiting for a reply from a remote database or rolling back transactions, the session will not kill itself immediately and will wait for the current operation to complete. In these cases the session will have a status of "marked for kill". It will then be killed as soon as possible.
Check the status to confirm:
SELECT sid, serial#, status, username FROM v$session;
You could also use IMMEDIATE clause:
ALTER SYSTEM KILL SESSION 'sid,serial#' IMMEDIATE;
The IMMEDIATE
clause does not affect the work performed by the command, but it returns control back to the current session immediately, rather than waiting for confirmation of the kill. Have a look at Killing Oracle Sessions.
Update If you want to kill all the sessions, you could just prepare a small script.
SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' FROM v$session;
Spool the above to a .sql
file and execute it, or, copy paste the output and run it.
Oracle doesn't have autoincrementing columns. You need a sequence and a trigger. Here's a random blog post that explains how to do it: http://www.lifeaftercoffee.com/2006/02/17/how-to-create-auto-increment-columns-in-oracle/
For completeness here is a floating-point implementation in bog-standard C.
double next_power_of_two(double value) {
int exp;
if(frexp(value, &exp) == 0.5) {
// Omit this case to round precise powers of two up to the *next* power
return value;
}
return ldexp(1.0, exp);
}
In simple terms
It is better to have more coarse-grained service operations, which are composed by fine-grained operations
Here is an other solution, largely inspired by the one by @fredoverflow.
/**
* Return hexadecimal representation of the input binary sequence
*/
std::string hexitize(const std::vector<char>& input, const char* const digits = "0123456789ABCDEF")
{
std::ostringstream output;
for (unsigned char gap = 0, beg = input[gap]; gap < input.length(); beg = input[++gap])
output << digits[beg >> 4] << digits[beg & 15];
return output.str();
}
Length was required parameter in the intended usage.
First install "Microsoft ASP.NET Web API Client" nuget package:
PM > Install-Package Microsoft.AspNet.WebApi.Client
Then use the following function to post your data:
public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
using (var httpClient = new HttpClient())
{
using (var content = new FormUrlEncodedContent(postData))
{
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
HttpResponseMessage response = await httpClient.PostAsync(url, content);
return await response.Content.ReadAsAsync<TResult>();
}
}
}
And this is how to use it:
TokenResponse tokenResponse =
await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);
or
TokenResponse tokenResponse =
(Task.Run(async ()
=> await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
.Result
or (not recommended)
TokenResponse tokenResponse =
PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;
Here are some examples of how to use Shell in VBA.
Open stackoverflow in Chrome.
Call Shell("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" & _
" -url" & " " & "www.stackoverflow.com",vbMaximizedFocus)
Open some text file.
Call Shell ("notepad C:\Users\user\Desktop\temp\TEST.txt")
Open some application.
Call Shell("C:\Temp\TestApplication.exe",vbNormalFocus)
Hope this helps!
For me I had rename from
[Database_LS].[schema].[TableView]
to
[Database_LS].[Database].[schema].[TableView]
in laravel, artisan is a file under root/protected page
for example,
c:\xampp\htdocs\my_project\protected\artisan
you can view the content of "artisan" file with any text editor, it's a php command syntax
so when we type
php artisan
we tell php to run php script in "artisan" file
for example:
php artisan change
will show the change of current laravel version
to see the other option, just type
php artisan
Check out std::isdigit()
function.
For my issue, I didn't want my images scaled to 100% when they weren't intended to be as large as the container.
For my xs container (<768px as .container), not having a fixed width drove the issue, so I put one back on to it (less the 15px col padding).
// Helps bootstrap 3.0 keep images constrained to container width when width isn't set a fixed value (below 768px), while avoiding all images at 100% width.
// NOTE: proper function relies on there being no inline styling on the element being given a defined width ( '.container' )
function setWidth() {
width_val = $( window ).width();
if( width_val < 768 ) {
$( '.container' ).width( width_val - 30 );
} else {
$( '.container' ).removeAttr( 'style' );
}
}
setWidth();
$( window ).resize( setWidth );
$(function() {
$('form button').click(function() {
var allowSubmit = true;
$.each($('form input:text'), function(index, formField) {
if($(formField).val().trim().length == 0) {
alert('field is empty!');
allowSubmit = false;
}
});
return allowSubmit;
});
});
Because textContent
is not supported in IE8 and older, here is a workaround:
var node = document.getElementById('test'),
var text = node.textContent || node.innerText;
alert(text);
innerText
does work in IE.
You could alternatively pass in the desired ASPNETCORE_ENVIRONMENT
into the dotnet publish command as an argument using:
/p:EnvironmentName=Staging
e.g.:
dotnet publish /p:Configuration=Release /p:EnvironmentName=Staging
This will generate out the web.config with the correct environment specified for your project:
<environmentVariables>
<environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" />
</environmentVariables>
If you do this a lot, NumPy is the way to go.
If for some reason you can't use NumPy:
>>> map(lambda x:sum(x)/float(len(x)), zip(*a))
[45.0, 10.5]
\b <= this is a word boundary.
Matches at a position that is followed by a word character but not preceded by a word character, or that is preceded by a word character but not followed by a word character.
\w <= stands for "word character".
It always matches the ASCII characters [A-Za-z0-9_]
Is there anything specific you are trying to match?
Some useful regex websites for beginners or just to wet your appetite.
I found this to be a very useful book:
Remember that your suggestions makes it difficult for clients to communicate with the server. They need to understand your innovative solution and encrypt the data accordingly, this model is not so good for public API (unless you are amazon\yahoo\google..).
Anyways, if you must encrypt the body content I would suggest you to check out existing standards and solutions like:
XML encryption (W3C standard)
Here JQuery plugin version of Maryan solution with handle optimization. Only with JQuery 1.7+!
(function ($) {
$.fn.heartbeat = function (options) {
var settings = $.extend({
// These are the defaults.
events: 'mousemove keydown'
, url: '/Home/KeepSessionAlive'
, every: 5*60*1000
}, options);
var keepSessionAlive = false
, $container = $(this)
, handler = function () {
keepSessionAlive = true;
$container.off(settings.events, handler)
}, reset = function () {
keepSessionAlive = false;
$container.on(settings.events, handler);
setTimeout(sessionAlive, settings.every);
}, sessionAlive = function () {
keepSessionAlive && $.ajax({
type: "POST"
, url: settings.url
,success: reset
});
};
reset();
return this;
}
})(jQuery)
and how it does import in your *.cshtml
$('body').heartbeat(); // Simple
$('body').heartbeat({url:'@Url.Action("Home", "heartbeat")'}); // different url
$('body').heartbeat({every:6*60*1000}); // different timeout
Comparing websocket and webrtc is unfair.
Websocket is based on top of TCP. Packet's boundary can be detected from header information of a websocket packet unlike tcp.
Typically, webrtc makes use of websocket. The signalling for webrtc is not defined, it is upto the service provider what kind of signalling he wants to use. It may be SIP, HTTP, JSON or any text / binary message.
The signalling messages can be send / received using websocket.
I do know that the account needs to have "Log on as a Service" privileges. Other than that, I'm not sure. A quick reference to Log on as a Service can be found here, and there is a lot of information of specific privileges here.
I am using Jupyter-notebook. And in my case, it was showing the file in the wrong format. The 'encoding' option was not working. So I save the csv in utf-8 format, and it works.
You're trying to redirect to a named route whose name is login
, but you have no routes with that name:
Route::post('login', [ 'as' => 'login', 'uses' => 'LoginController@do']);
The 'as'
portion of the second parameter defines the name of the route. The first string parameter defines its route.
Note: This works with jQuery enabled sites only
It is very simple with this cool trick. It worked for me in Google Chrome browser. Firefox wont allow you to print to PDF without a plugin.
var jqchild = document.createElement('script');
jqchild.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";
document.getElementsByTagName('body')[0].appendChild(jqchild);
$("#myDivWithStyles").print(); // Replace ID with yours
The logic is simple. We are creating a new script tag and attaching it in front of closing body tag. We injected a jQuery print extension into the HTML. Change myDivWithStyles with your own Div tag ID. Now it takes cares of preparing a printable virtual window.
Try it on any site. Only caveat is sometimes trickily written CSS can cause missing of styles. But we get the content most of times.
I have wrote my own library on Python to expand variables being loaded from directories with a hierarchy like:
/root
|
+- /proj1
|
+- config.yaml
|
+- /proj2
|
+- config.yaml
|
... and so on ...
The key difference here is that the expansion must be applied only after all the config.yaml
files is loaded, where the variables from the next file can override the variables from the previous, so the pseudocode should look like this:
env = YamlEnv()
env.load('/root/proj1/config.yaml')
env.load('/root/proj1/proj2/config.yaml')
...
env.expand()
As an additional option the xonsh
script can export the resulting variables into environment variables (see the yaml_update_global_vars
function).
The scripts:
https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.py https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.xsh
Pros:
${MYUNDEFINEDVAR}
-> *$/{MYUNDEFINEDVAR}
)${env:MYVAR}
)\\
to /
in a path variable (${env:MYVAR:path}
)Cons:
${MYSCOPE.MYVAR}
is not implemented)Add this to the stylesheet:
table {
border-collapse: collapse;
}
The reason why it behaves this way is actually described pretty well in the specification:
There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.
... and later, for collapse
setting:
In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.
Distances to the source of iBeacon-formatted advertisement packets are estimated from the signal path attenuation calculated by comparing the measured received signal strength to the claimed transmit power which the transmitter is supposed to encode in the advertising data.
A path loss based scheme like this is only approximate and is subject to variation with things like antenna angles, intervening objects, and presumably a noisy RF environment. In comparison, systems really designed for distance measurement (GPS, Radar, etc) rely on precise measurements of propagation time, in same cases even examining the phase of the signal.
As Jiaru points out, 160 ft is probably beyond the intended range, but that doesn't necessarily mean that a packet will never get through, only that one shouldn't expect it to work at that distance.
Here is the solution as described in the Doctrine2 Documentation
<?php
use Doctrine\Common\Collections\ArrayCollection;
/** @Entity */
class Order
{
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
/** @ManyToOne(targetEntity="Customer") */
private $customer;
/** @OneToMany(targetEntity="OrderItem", mappedBy="order") */
private $items;
/** @Column(type="boolean") */
private $payed = false;
/** @Column(type="boolean") */
private $shipped = false;
/** @Column(type="datetime") */
private $created;
public function __construct(Customer $customer)
{
$this->customer = $customer;
$this->items = new ArrayCollection();
$this->created = new \DateTime("now");
}
}
/** @Entity */
class Product
{
/** @Id @Column(type="integer") @GeneratedValue */
private $id;
/** @Column(type="string") */
private $name;
/** @Column(type="decimal") */
private $currentPrice;
public function getCurrentPrice()
{
return $this->currentPrice;
}
}
/** @Entity */
class OrderItem
{
/** @Id @ManyToOne(targetEntity="Order") */
private $order;
/** @Id @ManyToOne(targetEntity="Product") */
private $product;
/** @Column(type="integer") */
private $amount = 1;
/** @Column(type="decimal") */
private $offeredPrice;
public function __construct(Order $order, Product $product, $amount = 1)
{
$this->order = $order;
$this->product = $product;
$this->offeredPrice = $product->getCurrentPrice();
}
}
A moving average is a convolution, and numpy will be faster than most pure python operations. This will give you the 10 point moving average.
import numpy as np
smoothed = np.convolve(data, np.ones(10)/10)
I would also strongly suggest using the great pandas package if you are working with timeseries data. There are some nice moving average operations built in.
You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package
protected void Page_PreInit(object sender, EventArgs e)
{
if (Membership.GetUser() == null) //check the user weather user is logged in or not
this.Page.MasterPageFile = "~/General.master";
else
this.Page.MasterPageFile = "~/myMaster.master";
}
By default the route configuration follows RESTFul conventions meaning that it will accept only the Get, Post, Put and Delete action names (look at the route in global.asax => by default it doesn't allow you to specify any action name => it uses the HTTP verb to dispatch). So when you send a GET request to /api/users/authenticate
you are basically calling the Get(int id)
action and passing id=authenticate
which obviously crashes because your Get action expects an integer.
If you want to have different action names than the standard ones you could modify your route definition in global.asax
:
Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "get", id = RouteParameter.Optional }
);
Now you can navigate to /api/users/getauthenticate
to authenticate the user.
EDIT: Perhaps look at the answer currently immediately below.
This topic has been a headache for long time. I finally figured it out. There are some solutions online, but none of them really works. And of course there is no documentation. So in the chart below there are several properties that are suggested to use and the values they have for various installation scenarios:
So in my case I wanted a CA that will run only on uninstalls - not upgrades, not repairs or modifies. According to the table above I had to use
<Custom Action='CA_ID' Before='other_CA_ID'>
(NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")</Custom>
And it worked!
final static String EXTRA_MESSAGE = "edit.list.message";
Context context;
public void onClick (View view)
{
Intent intent = new Intent(this,display.class);
RelativeLayout relativeLayout = (RelativeLayout) view.getParent();
TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
String message = textView.getText().toString();
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
You can actually change the grey box around the dropdown arrow in IE:
select::-ms-expand {
width:12px;
border:none;
background:#fff;
}
The algorithm you are using, "AES", is a shorthand for "AES/ECB/NoPadding". What this means is that you are using the AES algorithm with 128-bit key size and block size, with the ECB mode of operation and no padding.
In other words: you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException
exception.
If you want to encrypt data in sizes that are not multiple of 16 bytes, you are either going to have to use some kind of padding, or a cipher-stream. For instance, you could use CBC mode (a mode of operation that effectively transforms a block cipher into a stream cipher) by specifying "AES/CBC/NoPadding" as the algorithm, or PKCS5 padding by specifying "AES/ECB/PKCS5", which will automatically add some bytes at the end of your data in a very specific format to make the size of the ciphertext multiple of 16 bytes, and in a way that the decryption algorithm will understand that it has to ignore some data.
In any case, I strongly suggest that you stop right now what you are doing and go study some very introductory material on cryptography. For instance, check Crypto I on Coursera. You should understand very well the implications of choosing one mode or another, what are their strengths and, most importantly, their weaknesses. Without this knowledge, it is very easy to build systems which are very easy to break.
Update: based on your comments on the question, don't ever encrypt passwords when storing them at a database!!!!! You should never, ever do this. You must HASH the passwords, properly salted, which is completely different from encrypting. Really, please, don't do what you are trying to do... By encrypting the passwords, they can be decrypted. What this means is that you, as the database manager and who knows the secret key, you will be able to read every password stored in your database. Either you knew this and are doing something very, very bad, or you didn't know this, and should get shocked and stop it.
User Defined Class Array List Example
import java.util.*;
public class UserDefinedClassInArrayList {
public static void main(String[] args) {
//Creating user defined class objects
Student s1=new Student(1,"AAA",13);
Student s2=new Student(2,"BBB",14);
Student s3=new Student(3,"CCC",15);
ArrayList<Student> al=new ArrayList<Student>();
al.add(s1);
al.add(s2);
al.add(s3);
Iterator itr=al.iterator();
//traverse elements of ArrayList object
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
class Student{
int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}
}
Program Output:
1 AAA 13
2 BBB 14
3 CCC 15
This is not really how you should design your Docker containers.
When designing a Docker container, you're supposed to build it such that there is only one process running (i.e. you should have one container for Nginx, and one for supervisord or the app it's running); additionally, that process should run in the foreground.
The container will "exit" when the process itself exits (in your case, that process is your bash script).
However, if you really need (or want) to run multiple service in your Docker container, consider starting from "Docker Base Image", which uses runit
as a pseudo-init process (runit
will stay online while Nginx and Supervisor run), which will stay in the foreground while your other processes do their thing.
They have substantial docs, so you should be able to achieve what you're trying to do reasonably easily.
Example for Qt use:)
QString random_string(int length=32, QString allow_symbols=QString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")) {
QString result;
qsrand(QTime::currentTime().msec());
for (int i = 0; i < length; ++i) {
result.append(allow_symbols.at(qrand() % (allow_symbols.length())));
}
return result;
}
For me the following explanatory snippet worked. Perhaps you shouldn't use '
for header name?
{
headers: {
Authorization: "Basic " + getAuthDigest(),
Accept: "text/plain"
}
}
I'm using $http.ajax()
, though I wouldn't expect that to be a game changer.
There are severals hacks available for IE
Using conditional comments with stylesheet
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="only-ie.css" />
<![endif]-->
Using conditional comments with head section css
<!--[if IE]>
<style type="text/css">
/************ css for all IE browsers ****************/
</style>
<![endif]-->
Using conditional comments with HTML elements
<!--[if IE]> <div class="ie-only"> /*content*/ </div> <![endif]-->
Using media query
IE10+
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
selector { property:value; }
}
IE6,7,9,10
@media screen and (min-width: 640px), screen\9 {
selector { property:value; }
}
IE6,7
@media screen\9 {
selector { property:value; }
}
IE8
@media \0screen {
selector { property:value; }
}
IE6,7,8
@media \0screen\,screen\9 {
selector { property:value; }
}
IE9,10
@media screen and (min-width:0\0){
selector { property:value; }
}
This code works well with very few requirements on external libraries and shows a basic use of int **array
.
This answer shows that each array is dynamically sized, as well as how to assign a dynamically sized leaf array into the dynamically sized branch array.
This program takes arguments from STDIN in the following format:
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Code for program below...
#include <iostream>
int main()
{
int **array_of_arrays;
int num_arrays, num_queries;
num_arrays = num_queries = 0;
std::cin >> num_arrays >> num_queries;
//std::cout << num_arrays << " " << num_queries;
//Process the Arrays
array_of_arrays = new int*[num_arrays];
int size_current_array = 0;
for (int i = 0; i < num_arrays; i++)
{
std::cin >> size_current_array;
int *tmp_array = new int[size_current_array];
for (int j = 0; j < size_current_array; j++)
{
int tmp = 0;
std::cin >> tmp;
tmp_array[j] = tmp;
}
array_of_arrays[i] = tmp_array;
}
//Process the Queries
int x, y;
x = y = 0;
for (int q = 0; q < num_queries; q++)
{
std::cin >> x >> y;
//std::cout << "Current x & y: " << x << ", " << y << "\n";
std::cout << array_of_arrays[x][y] << "\n";
}
return 0;
}
It's a very simple implementation of int main
and relies solely on std::cin
and std::cout
. Barebones, but good enough to show how to work with simple multidimensional arrays.
Uninstalling the IIS UrlScan Extension solved the problem for me.
In bash
, provided you files names have no spaces:
cd /home/webapps/project1/folder1
for f in *.csv
do
cp -v "$f" /home/webapps/project1/folder2/"${f%.csv}"$(date +%m%d%y).csv
done
This might help you
In most cases, the system does not relaunch apps after they are force quit by the user. One exception is location apps, which in iOS 8 and later are relaunched after being force quit by the user. In other cases, though, the user must launch the app explicitly or reboot the device before the app can be launched automatically into the background by the system. When password protection is enabled on the device, the system does not launch an app in the background before the user first unlocks the device.
You can use array_filter
to filter out elements of an array based on a callback function. The callback function takes each element of the array as an argument and you simply return false
if that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.
You can use it like this:
$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');
And if you want to re-index the array, you can pass the result to array_values
like this:
$output = array_values($output);
var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);
Datatables have a .Select method, which returns a rows array according to the criteria you specify. Something like this:
Dim oRows() As DataRow
oRows = dtCountries.Select("CountryName = '" & userinput & "'")
If oRows.Count = 0 Then
' No rows found
Else
' At least one row found. Could be more than one
End If
Of course, if userinput contains ' character, it would raise an exception (like if you query the database). You should escape the ' characters (I use a function to do that).
The \du
command return:
Role name =
postgres@implicit_files
And that command postgres=# \password postgres
return error:
ERROR: role "postgres" does not exist.
But that postgres=# \password postgres@implicit_files
run fine.
Also after sudo -u postgres createuser -s postgres
the first variant also work.
I would like to share my way of starting chrome - specificaly youtube tv - in full screen mode automatically, without the need of pressing F11. kiosk/fullscreen options doesn't seem to work (Version 41.0.2272.89). It has some steps though...
Now, whenever you click on this shortcut, chrome will start in fullscreen and at the page you defined. I guess you can put this shortcut in startup folder to run when windows starts, but I haven't tried it.
specifying the "antMatcher" before "authorizeRequests()" like below will restrict the authenticaiton to only those URLs specified in "antMatcher"
http.csrf().disable() .antMatcher("/apiurlneedsauth/**").authorizeRequests().
If you know the aspect ratio for example, if your image is square you can set either the height
or the width
to fill the container and get the other to be set by the aspectRatio
property
Here is the style if you want the height
be set automatically:
{
width: '100%',
height: undefined,
aspectRatio: 1,
}
Note: height
must be undefined
Open the /etc/mysql/mysql.conf.d/mysqld.cnf
file and comment the
following line:
#bind-address = 127.0.0.1
An email address must not exceed 254 characters.
This was accepted by the IETF following submitted erratum. A full diagnosis of any given address is available online. The original version of RFC 3696 described 320 as the maximum length, but John Klensin subsequently accepted an incorrect value, since a Path is defined as
Path = "<" [ A-d-l ":" ] Mailbox ">"
So the Mailbox element (i.e., the email address) has angle brackets around it to form a Path, which a maximum length of 254 characters to restrict the Path length to 256 characters or fewer.
The maximum length specified in RFC 5321 states:
The maximum total length of a reverse-path or forward-path is 256 characters.
RFC 3696 was corrected here.
People should be aware of the errata against RFC 3696 in particular. Three of the canonical examples are in fact invalid addresses.
I've collated a couple hundred test addresses, which you can find at http://www.dominicsayers.com/isemail
This answer also contains a standard solution using only the jstl redirect tag:
<c:redirect url="/home.html"/>
As far as I know, if an exception is not caught by your script, it will be interrupted.
Do a request with curl and see if it returns a 404 status code. Do the request using the HEAD request method so it only returns the headers without a body.
I had a similar issue and it turned out that i had to add an extra entry in cmake
to include the files.
Since i was also using the zmq library I had to add this to the included libraries as well.
Yes, here's an example:
CREATE TABLE myTable ( col1 int, createdDate datetime DEFAULT(getdate()), updatedDate datetime DEFAULT(getdate()) )
You can INSERT into the table without indicating the createdDate and updatedDate columns:
INSERT INTO myTable (col1) VALUES (1)
Or use the keyword DEFAULT:
INSERT INTO myTable (col1, createdDate, updatedDate) VALUES (1, DEFAULT, DEFAULT)
Then create a trigger for updating the updatedDate column:
CREATE TRIGGER dbo.updateMyTable
ON dbo.myTable
FOR UPDATE
AS
BEGIN
IF NOT UPDATE(updatedDate)
UPDATE dbo.myTable SET updatedDate=GETDATE()
WHERE col1 IN (SELECT col1 FROM inserted)
END
GO
If your set
command supports the /p
switch, then you can pipe input that way.
set /p VAR1=<test.txt
set /? |find "/P"
The /P switch allows you to set the value of a variable to a line of input entered by the user. Displays the specified promptString before reading the line of input. The promptString can be empty.
This has the added benefit of working for un-registered file types (which the accepted answer does not).
I was also having problem with starting MySql server but run command as mention right mark in picture . Its working fine .
In general, these answer the question: How to change your user settings file? But the question I wanted answered was how to change my local maven repository location. The answer is that you have to edit settings.xml. If the file does not exist, you have to create it. You set or change the location of the file at Window > Preferences > Maven > User Settings. It's the User Settings entry at
It's the second file input; the first with information in it.
If it's not clear, [redacted]
should be replaced with the local file path to your .m2 folder.
If you click the "open file" link, it opens the settings.xml file for editing in Eclipse.
If you have no settings.xml file yet, the following will set the local repository to the Windows 10 default value for a user named mdfst13:
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>C:\Users\mdfst13\.m2\repository</localRepository>
</settings>
You should set this to a value appropriate to your system. I haven't tested it, but I suspect that in Linux, the default value would be /home/mdfst13/.m2/repository
. And of course, you probably don't want to set it to the default value. If you are reading this, you probably want to set it to some other value. You could just delete it if you wanted the default.
Credit to this comment by @ejaenv for the name of the element in the settings file: <localRepository>
. See Maven — Settings Reference for more information.
Credit to @Ajinkya's answer for specifying the location of the User Settings value in Eclipse Photon.
If you already have a settings.xml file, you should merge this into your existing file. I.e. <settings
and <localRepository>
should only appear once in the file, and you probably want to retain any settings already there. Or to say that another way, edit any existing local repository entry if it exists or just add that line to the file if it doesn't.
I had to restart Eclipse for it to load data into the new repository. Neither "Update Settings" nor "Reindex" was sufficient.
Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:
<Router>
<Route path="/" component={App}>
<Route path="page1" component={Page1} />
<Route path="page2" component={Page2} />
</Route>
<Route path="/login" component={Login} />
</Router>
And the other components would look something like this:
var NavBar = React.createClass({
render() {
return (
<div>
<ul>
<a onClick={() => history.push('page1') }>Page 1</a>
<a onClick={() => history.push('page2') }>Page 2</a>
</ul>
</div>
)
}
});
var App = React.createClass({
render() {
return (
<div>
<NavBar />
<div>Other Content</div>
{this.props.children}
</div>
)
}
});
In your XML for the image view, where you have android:background="@drawable/thumbs_down
change this to android:src="@drawable/thumbs_down"
Currently it is placing that image as the background to the view and not the actual image in it.
Just created this:
https://gist.github.com/3854049
//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");
//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');
I used the
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ScrollView01"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
and works perfectly
A alternative solution to work with lists based on Scharron's solution
def myprint(d):
my_list = d.iteritems() if isinstance(d, dict) else enumerate(d)
for k, v in my_list:
if isinstance(v, dict) or isinstance(v, list):
myprint(v)
else:
print u"{0} : {1}".format(k, v)
You can leverage the java_home
helper binary on OS X
for what you're looking for.
To list all versions of installed JDK:
$ /usr/libexec/java_home -V
Matching Java Virtual Machines (2):
1.8.0_51, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home
1.7.0_79, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home
To request the JAVA_HOME path of a specific JDK version, you can do:
$ /usr/libexec/java_home -v 1.7
/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home
$ /usr/libexec/java_home -v 1.8
/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home
You could take advantage of the above commands in your script like this:
REQUESTED_JAVA_VERSION="1.7"
if POSSIBLE_JAVA_HOME="$(/usr/libexec/java_home -v $REQUESTED_JAVA_VERSION 2>/dev/null)"; then
# Do this if you want to export JAVA_HOME
export JAVA_HOME="$POSSIBLE_JAVA_HOME"
echo "Java SDK is installed"
else
echo "Did not find any installed JDK for version $REQUESTED_JAVA_VERSION"
fi
You might be able to do if-else and check for multiple different versions of java as well.
If you prefer XML output, java_home also has a -X option to output in XML.
$ /usr/libexec/java_home --help
Usage: java_home [options...]
Returns the path to a Java home directory from the current user's settings.
Options:
[-v/--version <version>] Filter Java versions in the "JVMVersion" form 1.X(+ or *).
[-a/--arch <architecture>] Filter JVMs matching architecture (i386, x86_64, etc).
[-d/--datamodel <datamodel>] Filter JVMs capable of -d32 or -d64
[-t/--task <task>] Use the JVM list for a specific task (Applets, WebStart, BundledApp, JNI, or CommandLine)
[-F/--failfast] Fail when filters return no JVMs, do not continue with default.
[ --exec <command> ...] Execute the $JAVA_HOME/bin/<command> with the remaining arguments.
[-R/--request] Request installation of a Java Runtime if not installed.
[-X/--xml] Print full JVM list and additional data as XML plist.
[-V/--verbose] Print full JVM list with architectures.
[-h/--help] This usage information.
update
If you use the router you can use lifecycle hooks or resolvers to delay navigation until the data arrived. https://angular.io/guide/router#milestone-5-route-guards
To load data before the initial rendering of the root component APP_INITIALIZER
can be used How to pass parameters rendered from backend to angular2 bootstrap method
original
When console.log(this.ev)
is executed after this.fetchEvent();
, this doesn't mean the fetchEvent()
call is done, this only means that it is scheduled. When console.log(this.ev)
is executed, the call to the server is not even made and of course has not yet returned a value.
Change fetchEvent()
to return a Promise
fetchEvent(){
return this._apiService.get.event(this.eventId).then(event => {
this.ev = event;
console.log(event); // Has a value
console.log(this.ev); // Has a value
});
}
change ngOnInit()
to wait for the Promise
to complete
ngOnInit() {
this.fetchEvent().then(() =>
console.log(this.ev)); // Now has value;
}
This actually won't buy you much for your use case.
My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>
and in ngOnInit()
isDataAvailable:boolean = false;
ngOnInit() {
this.fetchEvent().then(() =>
this.isDataAvailable = true); // Now has value;
}
Assume the date as milliseconds date is 1526813885836
, so you can access the date as string with this sample code:
console.log(new Date(1526813885836).toString());
For clearness see below code:
const theTime = new Date(1526813885836);
console.log(theTime.toString());
See below for my original answer - that pattern has worked well, but recently I've started using a different approach to Service/Activity communication:
Use RxJava to execute asynchronous operations.
If the Service needs to continue background operations even when no Activity is running, also start the service from the Application class so that it does not get stopped when unbound.
The advantages I have found in this approach compared to the startService()/LocalBroadcast technique are
Some example code. First the service:
public class AndroidBmService extends Service implements BmService {
private static final int PRESSURE_RATE = 500000; // microseconds between pressure updates
private SensorManager sensorManager;
private SensorEventListener pressureListener;
private ObservableEmitter<Float> pressureObserver;
private Observable<Float> pressureObservable;
public class LocalBinder extends Binder {
public AndroidBmService getService() {
return AndroidBmService.this;
}
}
private IBinder binder = new LocalBinder();
@Nullable
@Override
public IBinder onBind(Intent intent) {
logMsg("Service bound");
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
Sensor pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
if(pressureSensor != null)
sensorManager.registerListener(pressureListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if(pressureObserver != null) {
float lastPressure = event.values[0];
float lastPressureAltitude = (float)((1 - Math.pow(lastPressure / 1013.25, 0.190284)) * 145366.45);
pressureObserver.onNext(lastPressureAltitude);
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}, pressureSensor, PRESSURE_RATE);
}
@Override
public Observable<Float> observePressure() {
if(pressureObservable == null) {
pressureObservable = Observable.create(emitter -> pressureObserver = emitter);
pressureObservable = pressureObservable.share();
}
return pressureObservable;
}
@Override
public void onDestroy() {
if(pressureListener != null)
sensorManager.unregisterListener(pressureListener);
}
}
And an Activity that binds to the service and receives pressure altitude updates:
public class TestActivity extends AppCompatActivity {
private ContentTestBinding binding;
private ServiceConnection serviceConnection;
private AndroidBmService service;
private Disposable disposable;
@Override
protected void onDestroy() {
if(disposable != null)
disposable.dispose();
unbindService(serviceConnection);
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.content_test);
serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
logMsg("BlueMAX service bound");
service = ((AndroidBmService.LocalBinder)iBinder).getService();
disposable = service.observePressure()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(altitude ->
binding.altitude.setText(
String.format(Locale.US,
"Pressure Altitude %d feet",
altitude.intValue())));
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
logMsg("Service disconnected");
}
};
bindService(new Intent(
this, AndroidBmService.class),
serviceConnection, BIND_AUTO_CREATE);
}
}
The layout for this Activity is:
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.controlj.mfgtest.TestActivity">
<TextView
tools:text="Pressure"
android:id="@+id/altitude"
android:gravity="center_horizontal"
android:layout_gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</layout>
If the service needs to run in the background without a bound Activity it can be started from the Application class as well in OnCreate()
using Context#startService()
.
My Original Answer (from 2013):
In your service: (using COPA as service in example below).
Use a LocalBroadCastManager. In your service's onCreate, set up the broadcaster:
broadcaster = LocalBroadcastManager.getInstance(this);
When you want to notify the UI of something:
static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";
static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";
public void sendResult(String message) {
Intent intent = new Intent(COPA_RESULT);
if(message != null)
intent.putExtra(COPA_MESSAGE, message);
broadcaster.sendBroadcast(intent);
}
In your Activity:
Create a listener on onCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.copa);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String s = intent.getStringExtra(COPAService.COPA_MESSAGE);
// do something here.
}
};
}
and register it in onStart:
@Override
protected void onStart() {
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter(COPAService.COPA_RESULT)
);
}
@Override
protected void onStop() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}
In your entity class add @JsonInclude(JsonInclude.Include.NON_NULL)
annotation to resolve the problem
it will look like
@Entity
@JsonInclude(JsonInclude.Include.NON_NULL)
Is it useful to look beyond the exact question asked to alternatives that might better suit the need? Create your own class or struct, then make an array of those to operate on instead of being stuck with the operation of the KeyValuePair collection behavior of the Dictionary type.
Using a struct instead of a class will allow equality comparison of two different cards without implementing your own comparison code.
public struct Card
{
public string Name;
public int Value;
}
private int random()
{
// Whatever
return 1;
}
private static Card[] Cards = new Card[]
{
new Card() { Name = "7", Value = 7 },
new Card() { Name = "8", Value = 8 },
new Card() { Name = "9", Value = 9 },
new Card() { Name = "10", Value = 10 },
new Card() { Name = "J", Value = 1 },
new Card() { Name = "Q", Value = 1 },
new Card() { Name = "K", Value = 1 },
new Card() { Name = "A", Value = 1 }
};
private void CardDemo()
{
int value, maxVal;
string name;
Card card, card2;
List<Card> lowCards;
value = Cards[random()].Value;
name = Cards[random()].Name;
card = Cards[random()];
card2 = Cards[1];
// card.Equals(card2) returns true
lowCards = Cards.Where(x => x.Value == 1).ToList();
maxVal = Cards.Max(x => x.Value);
}
This error might occur when you return an object instead of a string in your __unicode__
method. For example:
class Author(models.Model):
. . .
name = models.CharField(...)
class Book(models.Model):
. . .
author = models.ForeignKey(Author, ...)
. . .
def __unicode__(self):
return self.author # <<<<<<<< this causes problems
To avoid this error you can cast the author instance to unicode:
class Book(models.Model):
. . .
def __unicode__(self):
return unicode(self.author) # <<<<<<<< this is OK
Just aggregating the answers and expanding on the basics. Here are three options:
We can include echo=FALSE
in the chunk header:
```{r echo=FALSE}
plot(cars)
```
We can change the default behaviour of knitr using the knitr::opts_chunk$set
function. We call this at the start of the document and include include=FALSE
in the chunk header to suppress any output:
---
output: html_document
---
```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```
```{r}
plot(cars)
```
For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.
---
output:
html_document:
code_folding: "hide"
---
```{r}
plot(cars)
```
Include below dependency in your pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>{spring-version}</version>
</dependency>
You can access the id after calling the persist method of the entity manager.
$widgetEntity = new WidgetEntity();
$entityManager->persist($widgetEntity);
$entityManager->flush();
$widgetEntity->getId();
You do need to flush in order to get this id.
Syntax Error Fix: Added semi-colon after $entityManager->flush() is called.
**Reading the Excel File:**
string filePath = @"d:\MyExcel.xlsx";
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook = xlApp.Workbooks.Open(filePath);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Excel.Range xlRange = xlWorkSheet.UsedRange;
int totalRows = xlRange.Rows.Count;
int totalColumns = xlRange.Columns.Count;
string firstValue, secondValue;
for (int rowCount = 1; rowCount <= totalRows; rowCount++)
{
firstValue = Convert.ToString((xlRange.Cells[rowCount, 1] as Excel.Range).Text);
secondValue = Convert.ToString((xlRange.Cells[rowCount, 2] as Excel.Range).Text);
Console.WriteLine(firstValue + "\t" + secondValue);
}
xlWorkBook.Close();
xlApp.Quit();
**Writting the Excel File:**
Excel.Application xlApp = new Excel.Application();
object misValue = System.Reflection.Missing.Value;
Excel.Workbook xlWorkBook = xlApp.Workbooks.Add(misValue);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = "ID";
xlWorkSheet.Cells[1, 2] = "Name";
xlWorkSheet.Cells[2, 1] = "100";
xlWorkSheet.Cells[2, 2] = "John";
xlWorkSheet.Cells[3, 1] = "101";
xlWorkSheet.Cells[3, 2] = "Herry";
xlWorkBook.SaveAs(filePath, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue,
Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close();
xlApp.Quit();
Python 2.x: docs.python.org/2/library/httplib.html:
Note: HTTPS support is only available if the socket module was compiled with SSL support.
Python 3.x: docs.python.org/3/library/http.client.html:
Note HTTPS support is only available if Python was compiled with SSL support (through the ssl module).
#!/usr/bin/env python
import httplib
c = httplib.HTTPSConnection("ccc.de")
c.request("GET", "/")
response = c.getresponse()
print response.status, response.reason
data = response.read()
print data
# =>
# 200 OK
# <!DOCTYPE html ....
To verify if SSL is enabled, try:
>>> import socket
>>> socket.ssl
<function ssl at 0x4038b0>
Move all that in kernel.php if just the above method didn't work for you remember you have to move all those lines in kernel.php in addition to the above solution
let me first display the way it is there in the file already..
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
now what you have to do is
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
],
'api' => [
'throttle:60,1',
],
];
i.e.;
Use the string concatenation operator:
Dim str As String = New String("") & "some other string"
Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.
This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.
See "How to: Concatenate Multiple Strings" for more information on both methods.
None, actually. The String class is mutable.
unsafe
{
string foo = string.Copy("I am immutable.");
fixed (char* pChar = foo)
{
char* pFoo = pChar;
pFoo[5] = ' ';
pFoo[6] = ' ';
}
Console.WriteLine(foo); // "I am mutable."
}
This kind of logic is done all the time in the String and StringBuilder classes, actually. They just allocate a new string each time you call Concat, Substring, etc. and use pointer arithmetic to copy over to the new string. Strings just don't mutate themselves, hence why they are considered "immutable".
By the way, do not attempt this with string literals or you will badly mess up your program:
string bar = "I am a string.";
fixed (char* pChar = bar)
{
char* pBar = pChar;
pBar[2] = ' ';
}
string baz = "I am a string.";
Console.WriteLine(baz); // "I m a string."
This is because string literals are interned in the desktop .NET Framework; in other words, bar
and baz
point to the exact same string, so mutating one will mutate the other. This is all fine and dandy though if you're using an unmanaged platform like WinRT, which lacks string interning.
I use to work with $http, when a want to get some information from a resource I do the following:
angular.module('services.value', [])
.service('Value', function($http, $q) {
var URL = "http://localhost:8080/myWeb/rest/";
var valid = false;
return {
isValid: valid,
getIsValid: function(callback){
return $http.get(URL + email+'/'+password, {cache: false})
.success(function(data){
if(data === 'true'){ valid = true; }
}).then(callback);
}}
});
And the code in the controller:
angular.module('controllers.value', ['services.value'])
.controller('ValueController', function($scope, Value) {
$scope.obtainValue = function(){
Value.getIsValid(function(){$scope.printValue();});
}
$scope.printValue = function(){
console.log("Do it, and value is " Value.isValid);
}
}
I send to the service what function have to call in the controller
I solved this problem by just removing firestore from:
import { AngularFirestore } from '@angular/fire/firestore/firestore';
in my component.ts file. as use only:
import { AngularFirestore } from '@angular/fire/firestore';
this can be also your problem.
I've had no issues committing a few files like this:
svn commit fileDir1/ fileDir2/ -m "updated!"
I'm not sure about this, but give it a shot.
In your strings.xml define:
<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>
In your layout:
<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="@array/array_name"
/>
I've heard this doesn't always work on the designer, but it compiles fine.
It sounds like you want to list all the metrics?
SELECT Criteria1, Criteria2, Metric1 As Metric
FROM Table1
UNION ALL
SELECT Criteria1, Criteria2, Metric2 As Metric
FROM Table2
ORDER BY 1, 2
If you only want one Criteria1+Criteria2 combination, group them:
SELECT Criteria1, Criteia2, SUM(Metric) AS Metric
FROM (
SELECT Criteria1, Criteria2, Metric1 As Metric
FROM Table1
UNION ALL
SELECT Criteria1, Criteria2, Metric2 As Metric
FROM Table2
)
ORDER BY Criteria1, Criteria2
Firstly this is a very good question.
e.g. The authorization header or content type header. Which is absolutely required by the server to understand the request. This can differ from server to server.
This is less severe than 400. The request has reached the server. The server has acknowledged the request has got the basic structure right. But the information in the request body can't be parsed or understood.
e.g. Content-Type: application/xml
when request body is JSON.
Here's an article listing status codes and its use in REST APIs. https://metamug.com/article/status-codes-for-rest-api.php
Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:
// All code to find the files are here and is working perfectly...
It doesn't make sense to call a API Controller from another controller on the same website.
This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...
In addition,
Not project dependent properities, Eclipse Preferences.
In Mac, Eclipse > Preferences
in Angular 2.x.x , 4, 5 ...
<form #loginForm="ngForm">
<input type="text" required>
<button type="submit" [disabled]="loginForm.form.invalid">Submit</button>
</form>
Some last version of Ubuntu installs Python 3.4 by default and the CMake version from Ubuntu (2.8) only searches up to Python 3.3.
Try to add set(Python_ADDITIONAL_VERSIONS 3.4)
before the find_package
statement.
Remember to clean CMakeCache.txt
too.
Yes you use this
<a href="#google"></a>
<div id="google"></div>
But this does not create a smooth scroll just so you know.
You can also add in your CSS
html {
scroll-behavior: smooth;
}
Top level await
is not supported. There are a few discussions by the standards committee on why this is, such as this Github issue.
There's also a thinkpiece on Github about why top level await is a bad idea. Specifically he suggests that if you have code like this:
// data.js
const data = await fetch( '/data.json' );
export default data;
Now any file that imports data.js
won't execute until the fetch completes, so all of your module loading is now blocked. This makes it very difficult to reason about app module order, since we're used to top level Javascript executing synchronously and predictably. If this were allowed, knowing when a function gets defined becomes tricky.
My perspective is that it's bad practice for your module to have side effects simply by loading it. That means any consumer of your module will get side effects simply by requiring your module. This badly limits where your module can be used. A top level await
probably means you're reading from some API or calling to some service at load time. Instead you should just export async functions that consumers can use at their own pace.
I think this is the more simpler approach:
Switching to SQL mode... Commands end with ;
Go forth and do great things! :)
I did the redistributable repair thing, but for me it worked after I installed Office365.
(for me it also was the last failing package on the list).
I still believe its to do with the props file not being located by spring. Do a quick test by passing the params as jvm params. i.e -Didm.url=....
The following code works fine:
@using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
and generates as expected:
<form action="/Upload/Upload" enctype="multipart/form-data" method="post">
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
</form>
On the other hand if you are writing this code inside the context of other server side construct such as an if
or foreach
you should remove the @
before the using
. For example:
@if (SomeCondition)
{
using (Html.BeginForm("Upload", "Upload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.ValidationSummary(true)
<fieldset>
Select a file <input type="file" name="file" />
<input type="submit" value="Upload" />
</fieldset>
}
}
As far as your server side code is concerned, here's how to proceed:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/content/pics"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Upload");
}
In newer version of windows the Certuil has [CertificateStoreName] where we can give the store name. In earlier version windows this was not possible.
Installing *.pfx certificate: certutil -f -p "" -enterprise -importpfx root ""
Installing *.cer certificate: certutil -addstore -enterprise -f -v root ""
For more details below command can be executed in windows cmd. C:>certutil -importpfx -? Usage: CertUtil [Options] -importPFX [CertificateStoreName] PFXFile [Modifiers]
Most of the time you can't - depending on the host. You can contact the support team where your hosting is subscribed to, and if they confirmed that it is really not allowed, you can just set up the composer on your dev machine, and commit and push all dependencies to your live server using Git or whatever you prefer.
Thanks,Bruno for giving me heads up on Common Name and Subject Alternative Name. As we figured out certificate was generated with CN with DNS name of network and asked for regeneration of new certificate with Subject Alternative Name entry i.e. san=ip:10.0.0.1. which is the actual solution.
But, we managed to find out a workaround with which we can able to run on development phase. Just add a static block in the class from which we are making ssl connection.
static {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier()
{
public boolean verify(String hostname, SSLSession session)
{
// ip address of the service URL(like.23.28.244.244)
if (hostname.equals("23.28.244.244"))
return true;
return false;
}
});
}
If you happen to be using Java 8, there is a much slicker way of achieving the same result:
static {
HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> hostname.equals("127.0.0.1"));
}
You often want to use wildcards with Class
. For instance, Class<? extends JComponent>
, would allow you to specify that the class is some subclass of JComponent
. If you've retrieved the Class
instance from Class.forName
, then you can use Class.asSubclass
to do the cast before attempting to, say, construct an instance.
If Data Is not Loaded From savedInstanceState
use following code.
The problem is url call is not to complete fully so, check if data is loaded then to show the instanceState value.
//suppose data is not Loaded to savedInstanceState at 1st swipe
if (savedInstanceState == null && !mAlreadyLoaded){
mAlreadyLoaded = true;
GetStoryData();//Url Call
} else {
if (listArray != null) { //Data Array From JsonArray(ListArray)
System.out.println("LocalData " + listArray);
view.findViewById(R.id.progressBar).setVisibility(View.GONE);
}else{
GetStoryData();//Url Call
}
}
You can use round function just to suppress scientific notation for specific dataframe:
df1.round(4)
or you can suppress is globally by:
pd.options.display.float_format = '{:.4f}'.format
for further investigation: print out the mssql error message:
$dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Could not connect to database: ".mssql_get_last_message());
It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:
$myServer = "10.85.80.229:1443";
or
$myServer = "10.85.80.229,1443";
A compact possibility
d1={'a':1,'b':2}
d2={'c':3,'d':4}
context={**d1, **d2}
context
{'b': 2, 'c': 3, 'd': 4, 'a': 1}
my.df <- read.table(textConnection("
v1 v2 v3 v4
a v d c
a v d d
b n p g
b d d h
c k d c
c r p g
d v d x
d v d c
e v d b
e v d c"), header = TRUE)
my.df[which(my.df$v1 != "b" & my.df$v1 != "d" & my.df$v1 != "e" ), ]
v1 v2 v3 v4
1 a v d c
2 a v d d
5 c k d c
6 c r p g
I think the solution here is not working with an update of the python version anymore, one way to do it with a new python function for it is:
extracted_data = data[['Column Name1','Column Name2']].to_numpy()
which gives you the desired outcome.
The documentation you can find here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_numpy.html#pandas.DataFrame.to_numpy
Tip for 1 website resizing the height. But you can change to 2 websites.
Here is my code to resize an iframe with an external website. You need insert a code into the parent (with iframe code) page and in the external website as well, so, this won't work with you don't have access to edit the external website.
Local:
<IFRAME STYLE="width:100%;height:1px" SRC="http://www.remote-site.com/" FRAMEBORDER="no" BORDER="0" SCROLLING="no" ID="estframe"></IFRAME>
<SCRIPT>
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
if (e.data.substring(0,3)=='frm') document.getElementById('estframe').style.height = e.data.substring(3) + 'px';
},false);
</SCRIPT>
You need this "frm" prefix to avoid problems with other embeded codes like Twitter or Facebook plugins. If you have a plain page, you can remove the "if" and the "frm" prefix on both pages (script and onload).
Remote:
You need jQuery to accomplish about "real" page height. I cannot realize how to do with pure JavaScript since you'll have problem when resize the height down (higher to lower height) using body.scrollHeight or related. For some reason, it will return always the biggest height (pre-redimensioned).
<BODY onload="parent.postMessage('frm'+$('#master').height(),'*')" STYLE="margin:0">
<SCRIPT SRC="path-to-jquery/jquery.min.js"></SCRIPT>
<DIV ID="master">
your content
</DIV>
So, parent page (iframe) has a 1px default height. The script inserts a "wait for message/event" from the iframe. When a message (post message) is received and the first 3 chars are "frm" (to avoid the mentioned problem), will get the number from 4th position and set the iframe height (style), including 'px' unit.
The external site (loaded in the iframe) will "send a message" to the parent (opener) with the "frm" and the height of the main div (in this case id "master"). The "*" in postmessage means "any source".
Hope this helps. Sorry for my english.
I won't stress much on the difference as it is already covered, but notice the below:
android:backgroundTint
android:backgroundTintMode
are only available at API 21android:background
, and you want to change its default color, then you can use android:backgroundTint
to add a shade to it.example
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="@android:drawable/ic_dialog_email" />
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:background="@android:drawable/ic_dialog_email"
android:backgroundTint="@color/colorAccent" />
Another example
If you try to change the accent color of the FloatingActionButton
using android:background
you won't notice a change, that is because it's already utilizes app:srcCompat
, so in order to do that you can use android:backgroundTint
instead
This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed. Since this feature hasn't yet been implemented by all other major browsers, authors should not assume that the script’s execution will actually be deferred. Never call document.write() from a defer script (since Gecko 1.9.2, this will blow away the document). The defer attribute shouldn't be used on scripts that don't have the src attribute. Since Gecko 1.9.2, the defer attribute is ignored on scripts that don't have the src attribute. However, in Gecko 1.9.1 even inline scripts are deferred if the defer attribute is set.
defer works with chrome , firefox , ie > 7 and Safari
ref: https://developer.mozilla.org/en-US/docs/HTML/Element/script
I think it should be "there can only be one NON-STATIC top level public class per .java file". Isn't it?
Call plt.show()
after plt.savefig(fig)
and your problem should be solved.
I had a similar problem.
I think the problem is that when you try to enclose two or more functions that deals with an array type of variable, php will return an error.
Let's say for example this one.
$data = array('key1' => 'Robert', 'key2' => 'Pedro', 'key3' => 'Jose');
// This function returns the last key of an array (in this case it's $data)
$lastKey = array_pop(array_keys($data));
// Output is "key3" which is the last array.
// But php will return “Strict Standards: Only variables should
// be passed by reference” error.
// So, In order to solve this one... is that you try to cut
// down the process one by one like this.
$data1 = array_keys($data);
$lastkey = array_pop($data1);
echo $lastkey;
There you go!
Unless your app is using some special encryption you can simply add Boolean a key to your Info.plist
with name ITSAppUsesNonExemptEncryption
and value NO
.
If your app is using custom encryption then you will need to provide extra legal documents and go through a review of your encryption before being able to select builds.
If you continue with selecting that version for testing, it will ask for the compliance information manually. Choosing "No" presents you with the plist recommendation above.
This is change has been announced in the 2015 WWDC, but I guess it has been enforced only very recently. See this and this for a transcript of the WWDC session related to the export compliance, just to a text search for "export".
There are other similar questions on SO, see:
Here's how I do it with Express.js:
1) Check if the user is authenticated: I have a middleware function named CheckAuth which I use on every route that needs the user to be authenticated:
function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.send('You are not authorized to view this page');
} else {
next();
}
}
I use this function in my routes like this:
app.get('/my_secret_page', checkAuth, function (req, res) {
res.send('if you are viewing this page it means you are logged in');
});
2) The login route:
app.post('/login', function (req, res) {
var post = req.body;
if (post.user === 'john' && post.password === 'johnspassword') {
req.session.user_id = johns_user_id_here;
res.redirect('/my_secret_page');
} else {
res.send('Bad user/pass');
}
});
3) The logout route:
app.get('/logout', function (req, res) {
delete req.session.user_id;
res.redirect('/login');
});
If you want to learn more about Express.js check their site here: expressjs.com/en/guide/routing.html If there's need for more complex stuff, checkout everyauth (it has a lot of auth methods available, for facebook, twitter etc; good tutorial on it here).
If tomorrow you decide you don't love Marry either she can be replaced as well:
today=$(</tmp/lovers.txt)
tomorrow="${today//Suzi/Sara}"
echo "${tomorrow//Marry/Jesica}" > /tmp/lovers.txt
There must be 50 ways to leave your lover.
We had this error on Oracle RAC 11g on Windows, and the solution was to create the same OS directory tree and external file on both nodes.
If you are using a virtualenvwrapper
, you can just locate it using which virtualenvwrapper.sh
, then open it using vim
or any other editor then change the following
# Locate the global Python where virtualenvwrapper is installed.
if [ "${VIRTUALENVWRAPPER_PYTHON:-}" = "" ]
then
VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
fi
Change the line VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
to VIRTUALENVWRAPPER_PYTHON="$(command \which python3)"
.
Not sure static variables are cached in thread local memory or NOT. But when I executed two threads(T1,T2) accessing same object(obj) and when update made by T1 thread to static variable it got reflected in T2.
After searching and trying multiple non working options to get my select default option working. I find a clean solution at: http://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/
<select class="ajg-stereo-fader-input-name ajg-select-left" ng-options="option.name for option in selectOptions" ng-model="inputLeft"></select>
<select class="ajg-stereo-fader-input-name ajg-select-right" ng-options="option.name for option in selectOptions" ng-model="inputRight"></select>
scope.inputLeft = scope.selectOptions[0];
scope.inputRight = scope.selectOptions[1];
For those who are getting to this question via google... this error can also happen if you try to rename a field that is acting as a foreign key.
Your CRON should look like this:
*/5 * * * *
CronWTF is really usefull when you need to test out your CRON settings.
Might be a good idea to pipe the output into a log file so you can see if your script is throwing any errors too - since you wont see them in your terminal.
Also try using a shebang at the top of your PHP file, so the system knows where to find PHP. Such as:
#!/usr/bin/php
that way you can call the whole thing like this
*/5 * * * * php /path/to/script.php > /path/to/logfile.log
try
a.slice(0,position) + b + a.slice(position)
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.slice(0,position) + b + a.slice(position);_x000D_
_x000D_
console.log(r);
_x000D_
or regexp solution
"I want apple".replace(/^(.{6})/,"$1 an")
var a = "I want apple";_x000D_
var b = " an";_x000D_
var position = 6;_x000D_
_x000D_
var r= a.replace(new RegExp(`^(.{${position}})`),"$1"+b);_x000D_
_x000D_
console.log(r);_x000D_
console.log("I want apple".replace(/^(.{6})/,"$1 an"));
_x000D_
Adding the following fixed the problem for me (Android studio 2.3.2):
build.gradle (Project)
buildscript {
repositories {
...
jcenter()
}
dependencies {
...
classpath 'me.tatarka:gradle-retrolambda:3.4.0' // DEPENDENCY
...
}
}
build.gradle (Module: app)
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda' //PLUGIN
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
} // SET JAVA VERSION
...
}
If you know the cell number, then i would recommend using getDateCellValue() method Here's an example for the same that worked for me - java.util.Date date = row.getCell().getDateCellValue(); System.out.println(date);
One way of doing it is to draw the image to a bitmap context that is backed by a given buffer for a given colorspace (in this case it is RGB): (note that this will copy the image data to that buffer, so you do want to cache it instead of doing this operation every time you need to get pixel values)
See below as a sample:
// First get the image into your data buffer
CGImageRef image = [myUIImage CGImage];
NSUInteger width = CGImageGetWidth(image);
NSUInteger height = CGImageGetHeight(image);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = malloc(height * width * 4);
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height));
CGContextRelease(context);
// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
red = rawData[byteIndex];
green = rawData[byteIndex + 1];
blue = rawData[byteIndex + 2];
alpha = rawData[byteIndex + 3];
You don't need to use regex, LIKE
is sufficient:
WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'
Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.
Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]
. [a-z]
may exclude A
or Z
. [A-Z]
may exclude a
or z
.
I tried everything mentioned in this thread and only .registerDriver() worked for me. This is how my part of code looks now:
DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
connection = DriverManager.getConnection(url, user, pass);
Notice that the problem wasn't in embedded Derby.
You can't do this no. There is one attribute selector that matches exactly or partial until a - sign, but it wouldn't work here because you have multiple attributes. If the class name you are looking for would always be first, you could do this:
<html>
<head>
<title>Test Page</title>
<style type="text/css">
div[class|=status] { background-color:red; }
</style>
</head>
<body>
<div id='A' class='status-important bar-class'>A</div>
<div id='B' class='bar-class'>B</div>
<div id='C' class='status-low-priority bar-class'>C</div>
</body>
</html>
Note that this is just to point out which CSS attribute selector is the closest, it is not recommended to assume class names will always be in front since javascript could manipulate the attribute.
#define
can lead to unexpected results:
#include <iostream>
#define x 500
#define y x + 5
int z = y * 2;
int main()
{
std::cout << "y is " << y;
std::cout << "\nz is " << z;
}
Outputs an incorrect result:
y is 505
z is 510
However, if you replace this with constants:
#include <iostream>
const int x = 500;
const int y = x + 5;
int z = y * 2;
int main()
{
std::cout << "y is " << y;
std::cout << "\nz is " << z;
}
It outputs the correct result:
y is 505
z is 1010
This is because #define
simply replaces the text. Because doing this can seriously mess up order of operations, I would recommend using a constant variable instead.
Most often you would have imported multiple eclipse projects and you have switched between Git Branch. And then, you build and import incorrect project where debugger is not expected to come!
If reset eclipse Perspective doesn't worked. Then do following things :
Delete eclipse project from disk.
Clean and Build the eclipse project (In my case I used ANT tool).
Note: Verify whether your are building the project in which the debugger is expected to come. The correct project name to be built can be found by hovering over a file where debug point is set.
Import that eclipse project again.
Also, Verify whether correct JDK is being selected at Preferences -> Installed JREs
The biggest benefit of lambda expressions and anonymous functions is the fact that they allow the client (programmer) of a library/framework to inject functionality by means of code in the given library/framework ( as it is the LINQ, ASP.NET Core and many others ) in a way that the regular methods cannot. However, their strength is not obvious for a single application programmer but to the one that creates libraries that will be later used by others who will want to configure the behaviour of the library code or the one that uses libraries. So the context of effectively using a lambda expression is the usage/creation of a library/framework.
Also since they describe one-time usage code they don't have to be members of a class where that will led to more code complexity. Imagine to have to declare a class with unclear focus every time we wanted to configure the operation of a class object.
Instance methods need to be called from an instance. Your setLoanItem
method is an instance method (it doesn't have the modifier static
), which it needs to be in order to function (because it is setting a value on the instance that it's called on (this
)).
You need to create an instance of the class before you can call the method on it:
Media media = new Media();
media.setLoanItem("Yes");
(Btw it would be better to use a boolean instead of a string containing "Yes".)
If can deviate a little from the straight path of DataTable -> SQL table, it can also be done via a list of objects:
1) DataTable -> Generic list of objects
public static DataTable ConvertTo<T>(IList<T> list)
{
DataTable table = CreateTable<T>();
Type entityType = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(entityType);
foreach (T item in list)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
{
row[prop.Name] = prop.GetValue(item);
}
table.Rows.Add(row);
}
return table;
}
Source and more details can be found here. Missing properties will remain to their default values (0 for int
s, null for reference types etc.)
2) Push the objects into the database
One way is to use EntityFramework.BulkInsert
extension. An EF datacontext is required, though.
It generates the BULK INSERT command required for fast insert (user defined table type solution is much slower than this).
Although not the straight method, it helps constructing a base of working with list of objects instead of DataTable
s which seems to be much more memory efficient.
Try this:
var jIsHasKids = $('#chkIsHasKids').attr('checked');
jIsHasKids = jIsHasKids.toString().toLowerCase();
//OR
jIsHasKids = jIsHasKids.val().toLowerCase();
Possible duplicate with: How do I use jQuery to ignore case when selecting
Run eventvwr from the command line to see if it has recorded any Application errors.
This might give you an actual error message that is more useful.
For me, my problem was I needed to navigate back and then transition to another state. So using $window.history.back()
didn't work because for some reason the transition happened before history.back() occured so I had to wrap my transition in a timeout function like so.
$window.history.back();
setTimeout(function() {
$state.transitionTo("tab.jobs"); }, 100);
This fixed my issue.
For XP: Start > Control Panel > Java > Security > (Set to Medium) http://www.java.com/en/download/help/java_update.xml
try this
#center_div
{
margin: auto;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
Change:
CONVERT(varchar(3), DATEPART(MONTH, S0.OrderDateTime) AS OrderMonth
To:
CONVERT(varchar(3), DATENAME(MONTH, S0.OrderDateTime)) AS OrderMonth
You can use Getfv.co :
To retrieve a favicon you can hotlink it at... http://g.etfv.co/[URL]
Example for this page : http://g.etfv.co/https://stackoverflow.com/questions/5119041/how-can-i-get-a-web-sites-favicon
Download content and let's go !
Edit :
Getfv.co and fvicon.com look dead. If you want I found a non free alternative : grabicon.com.
First, you can use sql command show global variables like 'innodb_buffer%';
to check the buffer size.
Solution is find your my.cnf
file and add,
[mysqld]_x000D_
innodb_buffer_pool_size=1G # depends on your data and machine
_x000D_
DO NOT forget to add [mysqld]
, otherwise, it won't work.
In my case, ubuntu 16.04, my.cnf
is located under the folder /etc/mysql/
.
This is how it should be done in typescript:
(new Date()).valueOf() - (new Date("2013-02-20T12:01:04.753Z")).valueOf()
Better readability:
var eventStartTime = new Date(event.startTime);
var eventEndTime = new Date(event.endTime);
var duration = eventEndTime.valueOf() - eventStartTime.valueOf();
I prefer doing code in pure Swift and not rely on Objective-C heritage. Because of this I wrote pure Swift solution with two advantages and two disadvantages.
Advantages:
Pure Swift code
Works on classes and completions or more specifically on Any
object
Disadvantages:
Code should call method willDeinit()
to release objects linked to specific class instance to avoid memory leaks
You cannot make extension directly to UIView for this exact example because var frame
is extension to UIView, not part of class.
import UIKit
var extensionPropertyStorage: [NSObject: [String: Any]] = [:]
var didSetFrame_ = "didSetFrame"
extension UILabel {
override public var frame: CGRect {
get {
return didSetFrame ?? CGRectNull
}
set {
didSetFrame = newValue
}
}
var didSetFrame: CGRect? {
get {
return extensionPropertyStorage[self]?[didSetFrame_] as? CGRect
}
set {
var selfDictionary = extensionPropertyStorage[self] ?? [String: Any]()
selfDictionary[didSetFrame_] = newValue
extensionPropertyStorage[self] = selfDictionary
}
}
func willDeinit() {
extensionPropertyStorage[self] = nil
}
}
Allow an analysis.
#include <iostream> // not #include "iostream"
using namespace std; // in this case okay, but never do that in header files
class A
{
public:
void f() { cout<<"f()\n"; }
};
int main()
{
/*
// A a; //this works
A *a = new A(); //this doesn't
a.f(); // "f has not been declared"
*/ // below
// system("pause"); <-- Don't do this. It is non-portable code. I guess your
// teacher told you this?
// Better: In your IDE there is prolly an option somewhere
// to not close the terminal/console-window.
// If you compile on a CLI, it is not needed at all.
}
As a general advice:
0) Prefer automatic variables
int a;
MyClass myInstance;
std::vector<int> myIntVector;
1) If you need data sharing on big objects down
the call hierarchy, prefer references:
void foo (std::vector<int> const &input) {...}
void bar () {
std::vector<int> something;
...
foo (something);
}
2) If you need data sharing up the call hierarchy, prefer smart-pointers
that automatically manage deletion and reference counting.
3) If you need an array, use std::vector<> instead in most cases.
std::vector<> is ought to be the one default container.
4) I've yet to find a good reason for blank pointers.
-> Hard to get right exception safe
class Foo {
Foo () : a(new int[512]), b(new int[512]) {}
~Foo() {
delete [] b;
delete [] a;
}
};
-> if the second new[] fails, Foo leaks memory, because the
destructor is never called. Avoid this easily by using
one of the standard containers, like std::vector, or
smart-pointers.
As a rule of thumb: If you need to manage memory on your own, there is generally a superiour manager or alternative available already, one that follows the RAII principle.
Use,
var url = $(this).attr('href');
window.open(url, '_blank');
Update:the href
is better off being retrieved with prop since it will return the full url and it's slightly faster.
var url = $(this).prop('href');
;C:\python27
to the Path
variable.You can easily add multiple classes to divs... So:
<div class="myclass myclass-one"></div>
<div class="myclass myclass-two"></div>
<div class="myclass myclass-three"></div>
Then in the CSS call to the share class to apply the same styles:
.myclass {...}
And you can still use your other classes like this:
.myclass-three {...}
Or if you want to be more specific in the CSS like this:
.myclass.myclass-three {...}
I do it the following way:
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
StringBuilder result = new StringBuilder();
for(Object item:this) {
result.append(item.toString());
result.append("\n"); //optional
}
return result.toString();
}
Mine was a TLS
version incompatible error.
Previously it was TLSv1
I changed it TLSV1.2
this solved my problem.
To use mvn deploy:deploy-file, must add ~./m2/settings.xml
<settings>
<servers>
<server>
<id>nexus-repo</id>
<username>admin</username>
<password>admin123</password>
</server>
</servers>
</settings>
command:
mvn deploy:deploy-file -DgroupId=com.example \
-DartifactId=my-app \
-Dversion=2.0.0 \
-Dpackaging=jar \
-Dfile=my-app.jar \
-DgeneratePom=true \
-DrepositoryId=nexus-repo \
-Durl=http://localhost:8081/repository/maven-releases/
My version for a directive that uses jqplot to plot the data once it becomes available:
app.directive('lineChart', function() {
$.jqplot.config.enablePlugins = true;
return function(scope, element, attrs) {
scope.$watch(attrs.lineChart, function(newValue, oldValue) {
if (newValue) {
// alert(scope.$eval(attrs.lineChart));
var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
}
});
}
});
As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.
For instance, the implementation code of the extra class should look like that:
@Entity
@Table(name = "USER_SERVICES")
public class UserService{
// example of auto-generated ID
@Id
@Column(name = "USER_SERVICES_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long userServiceID;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ID")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "SERVICE_ID")
private Service service;
// example of extra column
@Column(name="VISIBILITY")
private boolean visibility;
public long getUserServiceID() {
return userServiceID;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
public boolean getVisibility() {
return visibility;
}
public void setVisibility(boolean visibility) {
this.visibility = visibility;
}
}
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
npm i html-react-parser;
import Parser from 'html-react-parser';
<td>{Parser(this.state.archyves)}</td>
ObjectPath is a library that provides ability to query JSON and nested structures of dicts and lists. For example, you can search for all attributes called "foo" regardless how deep they are by using $..foo
.
While the documentation focuses on the command line interface, you can perform the queries programmatically by using the package's Python internals. The example below assumes you've already loaded the data into Python data structures (dicts & lists). If you're starting with a JSON file or string you just need to use load
or loads
from the json module first.
import objectpath
data = [
{'foo': 1, 'bar': 'a'},
{'foo': 2, 'bar': 'b'},
{'NoFooHere': 2, 'bar': 'c'},
{'foo': 3, 'bar': 'd'},
]
tree_obj = objectpath.Tree(data)
tuple(tree_obj.execute('$..foo'))
# returns: (1, 2, 3)
Notice that it just skipped elements that lacked a "foo" attribute, such as the third item in the list. You can also do much more complex queries, which makes ObjectPath handy for deeply nested structures (e.g. finding where x has y that has z: $.x.y.z
). I refer you to the documentation and tutorial for more information.
The accepted answer is not (entirely) correct. Sure, it makes notification icons show in color, but does so with a BIG drawback - by setting the target SDK to lower than Android Lollipop!
If you solve your white icon problem by setting your target SDK to 20, as suggested, your app will not target Android Lollipop, which means that you cannot use Lollipop-specific features.
Have a look at http://developer.android.com/design/style/iconography.html, and you'll see that the white style is how notifications are meant to be displayed in Android Lollipop.
In Lollipop, Google also suggest that you use a color that will be displayed behind the (white) notification icon - https://developer.android.com/about/versions/android-5.0-changes.html
So, I think that a better solution is to add a silhouette icon to the app and use it if the device is running Android Lollipop.
For instance:
Notification notification = new Notification.Builder(context)
.setAutoCancel(true)
.setContentTitle("My notification")
.setContentText("Look, white in Lollipop, else color!")
.setSmallIcon(getNotificationIcon())
.build();
return notification;
And, in the getNotificationIcon method:
private int getNotificationIcon() {
boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.drawable.icon_silhouette : R.drawable.ic_launcher;
}
Kevin van Zonneveld wrote a very nice detailed article on this, in his example he makes use of the System_Daemon
PEAR package (last release date on 2009-09-02).
Pattern p = Pattern.compile("(\\D+)(\\d+)(.*)");
Matcher m = p.matcher("this is your number:1234 thank you");
if (m.find()) {
String someNumberStr = m.group(2);
int someNumberInt = Integer.parseInt(someNumberStr);
}
Because of double print function. I suggest you to use return
instead of print
inside the function definition.
def lyrics():
return "The very first line"
print(lyrics())
OR
def lyrics():
print("The very first line")
lyrics()
If you want an else
you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value
as the statement instead, and remove the filter from the end:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
The answer are accepted but one thing you could also do is to define the libraries from your project structure. What you can do is :
What happens is the predefined libraries as off now now I'm taking the appcompat:26.0.0-alpha1 it uses the older version of the things when you add something new and tries to resolve it with the old stuffs. When you add it from your project structure, it'll add the same thing but with the new stuffs to resolve it. Your problem would be resolved.
For Postgres
ALTER TABLE table_name ADD field_name serial PRIMARY KEY
REFERENCE: https://www.tutorialspoint.com/postgresql/postgresql_using_autoincrement.htm
I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.
Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty()
.
The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.
Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.
I think is for prevent the browser's HTML parser from interpreting the <script>, and mainly the </script> as the closing tag of the actual script, however I don't think that using document.write is a excellent idea for evaluating script blocks, why don't use the DOM...
var newScript = document.createElement("script");
...
It's simple. You can create your own ViewModel class for Login - LoginViewModel. You can create view var dialog = new UserView(); inside your LoginViewModel. And you can set-up Command LoginCommand into button.
<Button Name="btnLogin" IsDefault="True" Content="Login" Command="{Binding LoginCommand}" />
and
<Button Name="btnCancel" IsDefault="True" Content="Login" Command="{Binding CancelCommand}" />
ViewModel class:
public class LoginViewModel
{
Window dialog;
public bool ShowLogin()
{
dialog = new UserView();
dialog.DataContext = this; // set up ViewModel into View
if (dialog.ShowDialog() == true)
{
return true;
}
return false;
}
ICommand _loginCommand
public ICommand LoginCommand
{
get
{
if (_loginCommand == null)
_loginCommand = new RelayCommand(param => this.Login());
return _loginCommand;
}
}
public void CloseLoginView()
{
if (dialog != null)
dialog.Close();
}
public void Login()
{
if(CheckLogin()==true)
{
CloseLoginView();
}
else
{
// write error message
}
}
public bool CheckLogin()
{
// ... check login code
return true;
}
}
From the docs:
_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.
So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.
Edit: Further reading led me here:
http://www.analyticsmarket.com/blog/edit-ecommerce-data
Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.
You should use $evalAsync or $timeout according to the context.
This is a link with a good explanation:
http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm
One should check if QtyToRepair
is updated at first.
ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
ON [dbo].[SCHEDULE]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE (QtyToRepair)
BEGIN
UPDATE SCHEDULE
SET modified = GETDATE()
, ModifiedUser = SUSER_NAME()
, ModifiedHost = HOST_NAME()
FROM SCHEDULE S INNER JOIN Inserted I
ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
WHERE S.QtyToRepair <> I.QtyToRepair
END
END
^
is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow
.
If you want to target a device then just write min-device-width
. For example:
@media only screen and (min-device-width: 480px){}
@media only screen and (min-device-width: 768px){}
Here are some good articles:
A modified version of @mxsb solution that allows us to define multiple files and in my case these are yml files.
In my application-dev.yml, I added this config that allows me to inject all the yml that have -dev.yml in them. This can be a list of specific files also. "classpath:/test/test.yml,classpath:/test2/test.yml"
application:
properties:
locations: "classpath*:/**/*-dev.yml"
This helps to get a properties map.
@Configuration
public class PropertiesConfig {
private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfig.class);
@Value("${application.properties.locations}")
private String[] locations;
@Autowired
private ResourceLoader rl;
@Bean
Map<String, Properties> myProperties() {
return stream(locations)
.collect(toMap(filename -> filename, this::loadProperties));
}
private Properties loadProperties(final String filename) {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
try {
final Resource[] possiblePropertiesResources = ResourcePatternUtils.getResourcePatternResolver(rl).getResources(filename);
final Properties properties = new Properties();
stream(possiblePropertiesResources)
.filter(Resource::exists)
.map(resource1 -> {
try {
return loader.load(resource1.getFilename(), resource1);
} catch (IOException e) {
throw new RuntimeException(e);
}
}).flatMap(l -> l.stream())
.forEach(propertySource -> {
Map source = ((MapPropertySource) propertySource).getSource();
properties.putAll(source);
});
return properties;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
However, if like in my case, I wanted to have to split yml files for each profile and load them and inject that directly into spring configuration before beans initialisation.
config
- application.yml
- application-dev.yml
- application-prod.yml
management
- management-dev.yml
- management-prod.yml
... you get the idea
The component is slightly different
@Component
public class PropertiesConfigurer extends PropertySourcesPlaceholderConfigurer
implements EnvironmentAware, InitializingBean {
private final static Logger LOG = LoggerFactory.getLogger(PropertiesConfigurer.class);
private String[] locations;
@Autowired
private ResourceLoader rl;
private Environment environment;
@Override
public void setEnvironment(Environment environment) {
// save off Environment for later use
this.environment = environment;
super.setEnvironment(environment);
}
@Override
public void afterPropertiesSet() throws Exception {
// Copy property sources to Environment
MutablePropertySources envPropSources = ((ConfigurableEnvironment) environment).getPropertySources();
envPropSources.forEach(propertySource -> {
if (propertySource.containsProperty("application.properties.locations")) {
locations = ((String) propertySource.getProperty("application.properties.locations")).split(",");
stream(locations).forEach(filename -> loadProperties(filename).forEach(source ->{
envPropSources.addFirst(source);
}));
}
});
}
private List<PropertySource> loadProperties(final String filename) {
YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
try {
final Resource[] possiblePropertiesResources = ResourcePatternUtils.getResourcePatternResolver(rl).getResources(filename);
final Properties properties = new Properties();
return stream(possiblePropertiesResources)
.filter(Resource::exists)
.map(resource1 -> {
try {
return loader.load(resource1.getFilename(), resource1);
} catch (IOException e) {
throw new RuntimeException(e);
}
}).flatMap(l -> l.stream())
.collect(Collectors.toList());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
In gcc, this isn't supported. In fact, this isn't supported in any existing compiler/linker i'm aware of.
By the way, the structure you're giving as an example already exist in the Java base class library as java.awt.Point
. It has x and y as public fields, check it out for yourself.
If you know what you're doing, and others in your team know about it, then it is okay to have public fields. But you shouldn't rely on it because they can cause headaches as in bugs related to developers using objects as if they were stack allocated structs (java objects are always sent to methods as references and not as copies).
The syntax of ng-style
is not quite that. It accepts a dictionary of keys (attribute names) and values (the value they should take, an empty string unsets them) rather than only a string. I think what you want is this:
<div ng-style="{ 'width' : width, 'background' : bgColor }"></div>
And then in your controller:
$scope.width = '900px';
$scope.bgColor = 'red';
This preserves the separation of template and the controller: the controller holds the semantic values while the template maps them to the correct attribute name.
In case it helps anyone setBackgroundImage
didn't work for me, but setImage
did
var select =$('#selectbox').val();
I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:
const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))
When you use a HashSet (or a HashMap) data are stored in "buckets" based on the hash of your object. This way your data is easier to access because you don't have to look for this particular data in the whole Set, you just have to look in the right bucket.
This way you can increase performances on specific points.
Each Collection implementation have its particularity to make it better to use in a certain condition. Each of those particularities have a cost. So if you don't really need it (for example the insertion order) you better use an implementation which doesn't offer it and fits better to your requirements.
you can try
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));
Document doc = db.parse(is);
refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm
After not able to find a good universal solution I made something of my own. I have not tested it for a very large list.
It takes care of nested keys,arrays or just about anything.
app.filter('xf', function() {
function keyfind(f, obj) {
if (obj === undefined)
return -1;
else {
var sf = f.split(".");
if (sf.length <= 1) {
return obj[sf[0]];
} else {
var newobj = obj[sf[0]];
sf.splice(0, 1);
return keyfind(sf.join("."), newobj)
}
}
}
return function(input, clause, fields) {
var out = [];
if (clause && clause.query && clause.query.length > 0) {
clause.query = String(clause.query).toLowerCase();
angular.forEach(input, function(cp) {
for (var i = 0; i < fields.length; i++) {
var haystack = String(keyfind(fields[i], cp)).toLowerCase();
if (haystack.indexOf(clause.query) > -1) {
out.push(cp);
break;
}
}
})
} else {
angular.forEach(input, function(cp) {
out.push(cp);
})
}
return out;
}
})
HTML
<input ng-model="search.query" type="text" placeholder="search by any property">
<div ng-repeat="product in products | xf:search:['color','name']">
...
</div>
this solution from this link helped me a lot. you can check it out.
The curl.php file with those line of instruction can work.
<?php
// Server key from Firebase Console define( 'API_ACCESS_KEY', 'AAAA----FE6F' );
$data = array("to" => "cNf2---6Vs9", "notification" => array( "title" => "Shareurcodes.com", "body" => "A Code Sharing Blog!","icon" => "icon.png", "click_action" => "http://shareurcodes.com"));
$data_string = json_encode($data);
echo "The Json Data : ".$data_string;
$headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' );
$ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_POSTFIELDS, $data_string);
$result = curl_exec($ch);
curl_close ($ch);
echo "<p> </p>";
echo "The Result : ".$result;
Remember you need to execute curl.php file using another browser ie not from the browser that is used to get the user token. You can see notification only if you are browsing another website.
Add Validate Connection=true to your connection string.
Look at this blog to find more about.
DETAILS: After OracleConnection.Close() the real database connection does not terminate. The connection object is put back in connection pool. The use of connection pool is implicit by ODP.NET. If you create a new connection you get one of the pool. If this connection is "yet open" the OracleConnection.Open() method does not really creates a new connection. If the real connection is broken (for any reason) you get a failure on first select, update, insert or delete.
With Validate Connection the real connection is validated in Open() method.
with open(csv_filename) as file:
data = file.read()
with open(xl_file_name, 'w') as file:
file.write(data)
You can turn CSV to excel like above with inbuilt packages. CSV can be handled with an inbuilt package of dictreader and dictwriter which will work the same way as python dictionary works. which makes it a ton easy I am currently unaware of any inbuilt packages for excel but I had come across openpyxl. It was also pretty straight forward and simple You can see the code snippet below hope this helps
import openpyxl
book = openpyxl.load_workbook(filename)
sheet = book.active
result =sheet['AP2']
print(result.value)
In my experience, most often this error message means that you have put an accidental closing brace somewhere, leaving the rest of your statements outside the function.
Example:
function a() {
if (global_block) //syntax error is actually here - missing opening brace
return;
} //this unintentionally ends the function
if (global_somethingelse) {
//Chrome will show the error occurring here,
//but actually the error is in the previous statement
return;
}
//do something
}
margin: 50%;
You can adjust the percentage as needed. It seems to work for me in responsive emails.
I'd add to luff's answer one more line and change the parameter name:
function requireCached(_module){
var l = module.children.length;
for (var i = 0; i < l; i++)
{
if (module.children[i].id === require.resolve(_module))
{
module.children.splice(i, 1);
break;
}
}
delete require.cache[require.resolve(_module)];
return require(_module)
}
There should not be a space after name
.
Incorrect:
{% url 'author' name = p.article_author.name.username %}
Correct:
{% url 'author' name=p.article_author.name.username %}
Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.
var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);