_id stringlengths 2 6 | text stringlengths 4 46k | title stringclasses 1 value |
|---|---|---|
d10801 | The approach you chose looks really good — you can basically combine Box with every type of row you want, provided it has a correct interface. It is called Object Composition and is a legit and well respected pattern in software engineering.
The only thing is, in React you should do it not by passing a already rendered component, but the component class, like this:
<Box rowComponent={ HouseRow } />
As you see, you don't need to use parenthesis. And inside component, you do something like this:
var RowComponent = this.props.rowComponent;
return (
<RowComponent />
);
A: <Box rowType={HouseRow} />
This is exactly how you would do it. Pass dynamic content that varies from components as props from a parent. Then in your rows function, return <{@props.rowType} /> should work | |
d10802 | It is possible that the problem is not that the class based view is returning a 403 error, but rather that the function based view is not checking the permissions correctly. This might be caused because @require_POST does not take the permissions into consideration.
Replace @require_POST in your function based view with @api_view(('POST',)). | |
d10803 | Here is how to associate custom URIs with an application.
I already have a task that generates the native bundles.
First step is to enable verbose in your ant task so you can locate the build path.
As mentioned here, in 6.3.3 enable verbose and look for <AppName>.iss file in the build directory, which is usuablly AppData/Local/Temp/fxbundler*.
Make sure you have the directory that contains package directory in the classpath. Here is an example of how you can add that to the classpath:
<taskdef resource="com/sun/javafx/tools/ant/antlib.xml" uri="javafx:com.sun.javafx.tools.ant" classpath="${build.src.dir}:${JAVA_HOME}/lib/ant-javafx.jar"/>
In my example I have package/windows with Drop-In Resources in src directory.
If you have file association, you will see something like this:
[Registry]
Root: HKCR; Subkey: ".txt"; ValueType: string; ValueName: ""; ValueData: "AppNameFile"; Flags: uninsdeletevalue
Just after this line you can add lines to add custom URI's registry entries.
If you don't have file association then you will add entries after
ArchitecturesInstallIn64BitMode=ARCHITECTURE_BIT_MODE
You can find the template of how AppName.iss file is generated at this location:
C:\Program Files (x86)\Java\jdk1.8.0_60\lib\ant-javafx.jar\com\oracle\tools\packager\windows\template.iss
Here you will find how to write lines like the one above
Here you can find what registry keys and entries that needs to be added for custom URI association. | |
d10804 | You can redirect to the same page in your CBV :
from django.http import HttpResponseRedirect
return HttpResponseRedirect(self.request.path_info)
As stated in the comment your solution require Ajax and JS, you can however redirect to the same page but that will make a new request and refresh the whole page which might no be ideal for you.
There is a tutorial to work with Django and Ajax Ajax / Django Tutorial | |
d10805 | You can try the regular expression:
// (0[1-9]|[12][0-9]|[3][01])[._-](0[1-9]|1[0-2])[._-](2[0-9]{3})
"(0[1-9]|[12][0-9]|[3][01])[._-](0[1-9]|1[0-2])[._-](2[0-9]{3})"
A: A single regex o match valid dates is awful.
I'd do:
String regexOfDate = "(?<!\\d)\\d{2}[-_.]\\d{2}[-_.]\\d{4}(?!\\d)";
to extract the potential date, then test if it is valid. | |
d10806 | Try this.
javascript:document.getElementById('name').value = 'string1'; undefined;
Tack on a 'undefined;' to any script that returns a string.
A: That is because you are using single quotes after the attribute value
value=''
and you changing it's value in javascript using
document.getElementById('name').value='string1';
so the html becomes
<input type='text' id='name' value=''string1''
you can fix it using
value=""
or using
document.getElementById('name').value="string1";
A: well i tried the following code
<html>
<body>
<form method='post'>
Name: <input type='text' id='name' value='' /><br />
Family: <input type='text' id='family' value='' /><br />
Email: <input type='text' id='email' value='' /><br />
<input type='submit' value='Submit' /><br />
</form>
<button onclick="change()">Click me</button>
<script>
function change(){
var obj=document.getElementById('name');
obj.value="string1";
}
</script>
</body>
</html>
and it works just fine the problem is in your script
do you created a function to change the value or just putted the code in a script tag like this
<script>document.getElementById('name').value="String1";<script> | |
d10807 | Decorating the service is the thing you're looking for:
bar:
public: false
class: stdClass
decorates: foo
arguments: ["@bar.inner"]
You can inject the original service in your own service, and implement the original interface to make them compatible.
http://symfony.com/doc/2.7/service_container/service_decoration.html
A: Symfony 5.1+
Symfony 5.1+ provide a simpler service decoration:
In previous Symfony versions you needed to use the syntax decorating
service ID + .inner to refer to that service. This quickly becomes
cumbersome in YAML/XML when using PHP classes as service IDs. That's
why in Symfony 5.1 we've simplified this feature to always use .inner
to refer to the original service.
@source: https://symfony.com/blog/new-in-symfony-5-1-simpler-service-decoration
# config/services.yaml
services:
App\MyService: ~
# Before
App\SpecialMyService:
decorates: App\MyService
arguments: ['@App\SpecialMyService.inner']
# After
App\SpecialMyService:
decorates: App\MyService
arguments: ['@.inner'] # <--- the service ID is no longer needed | |
d10808 | People often misunderstand the way UpdatePanel works. They mistakenly think that, there's no page reload when anything triggering postback occurs inside an UpdatePanel. This is totally wrong. In fact a full page reload is taken place. It's not a coincidence that UpdatePanel is located under category called AJAX controls of the toolbox. But it does not work the same as AJAX does, it just imitates it. What you get when you use UpdatePanel is that the page does not flicker to the top of the page, which is the normal behavior of any full page reload, so you get a feeling of partial refresh. That's why, the Google Maps you're talking about gets refreshed. Using real AJAX will help you do just what you want. Jquery library has a very convenient way of doing AJAX. Or you can just use plain javascript. | |
d10809 | The only solution I've reached is change your index.cshtml
<!-- remove this line
<app asp-prerender-module="ClientApp/dist/main-server">Loading...</app>
-->
<!-- replace with -->
<app>Loading...</app>
<script src="~/dist/vendor.js" asp-append-version="true"></script>
@section scripts {
<script src="~/dist/main-client.js" asp-append-version="true"></script>
}
A: In my case with ASP.NET Core 2 and Angular, this worked.
<app asp-ng2-prerender-module="ClientApp/dist/main-server">Loading...</app> | |
d10810 | I'm fond of using environment variables for this (which can be set system wide for example in /etc/profile amongst other places). others prefer to pass a -D definition to the JVM
A: your code is okay, detect it depend your environment, like hostname, IP arrdress, global variable etc. | |
d10811 | you are not parsing the json response in your success function,you need to use $.parseJSON(response) like below
success:function(res) {
var response=$.parseJSON(res);
if(response.status === "OK") {
$("#contactFormResponse").html("<div class='alert alert-success' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$("#contactForm")[0].reset();
$(window).scrollTop(0);
} else if (response.status === "error") {
$("#contactFormResponse").html("<div class='alert alert-danger' id='message'></div>");
$("#message").html(response.message).fadeIn("100");
$(window).scrollTop(0);
}
}, | |
d10812 | You are correct, with the error, you need to understand that the
List<List<string>> will take a List<string> and NOT A String.
Try something like this;
List<string> listOfString = new List<string>;
for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
listOfString.add(line);
}
}
}
Then,
_toLoad.add(listOfStrings);
A: Try using File.ReadAllLines(). Replace the for loop with:
foreach(var file in filesToRead) {
_toLoad.Add(File.ReadAllLines(file).ToList());
}
A: You can cut this down considerably using LINQ:
List<string> filesToRead = new List<string> {"NounSetOne.txt", "NounSetTwo.txt"};
List<List<string>> _toLoad = new List<List<string>>();
_toLoad.AddRange(filesToRead.Select(f => File.ReadAllLines (f).ToList() ));
Note that there's no extraneous variables for the filename (why have FileOne/FileTwo if their only purpose is to get added to a list?) and that we're letting the AddRange take care of creating the List<string>s for us automatically.
A: for (int i = 0; i <= filesToRead.Count; i++)
{
using (var reader = new StreamReader(filesToRead[i]))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_toLoad[i].Add(line);
}
}
} | |
d10813 | I'm no expert on these things, but try adding:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DT$
<plist version="1.0">
<dict>
<key>GNUTERM</key>
<string>aqua</string>
<key>PATH</key>
<string>/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin</string>
</dict>
</plist>
(added /opt/local/bin to PATH)
A: I reinstalled gnuplot and it suddenly worked.
A: I had the same problem. gnuplot worked from the terminal, but not from c++.
The c++ code called getenv("PATH") and searched for "gnuplot" throwing an exception when it could not be found. After copying /opt/local/bin/gnuplot into /usr/local/bin, it didn't work as in your case.
But then I decided to also copy it into /usr/bin and this seems to work.
labjunky | |
d10814 | Logged in user details are store in global variable current_user.
And Yes. You will get session id once you call login method from REST.
$proxy is the object of your rest
$credentials = array(
'user_name' => 'username',
'password' => md5('password')
);
$result = $proxy->login($credentials, 'your_application_name');
$session_id = $result['id'];
A: Sachin is right, there is a global variable for currently logged in user.
And you can access its properties straightforward :
Its an instance of the user bean.
global $current_user;
echo $current_user->id;
echo $current_user->user_name; | |
d10815 | How are you compiling this. The compiler should give you and error on the assignment:
wordList[i] = (char *)malloc(sizeof(char) );
The array wordlist is not of type char *
Also you are missing an include for malloc (stdlib.h probably) and you shouldn't be casting the return from malloc.
A: One obvious problem - you are allocating one char for wordList[i], then using it as if you had a character for each wordList[i][j].
You don't need to allocate any memory here, as you've defined wordlist as a 2 dimensional array rather than as an array of pointers or similar.
Next obvious problem - you are reading in characters and never providing an end of string, so if you ever got to the printf() at the end you are going to keep going until there happens to be a 0 somewhere in or after wordList[index] - or run off the end of memory, with a Segfault.
Next problem - do you intend to only detect EOF immediately after reading a space - AND throw away alternate characters? | |
d10816 | If you're OK with indexer running every 5 minutes, you don't need to invoke it at all - it can run on a schedule.
If you need to invoke indexer more frequently, you can run it once every 3 minutes on a free tier service, and as often as you want on any paid tier service. If an indexer is already running when you run it, the call will fail with a 409 status.
However, if you need to run indexer very frequently, usually it's in response to new data arriving and you have that data in hand. In that case, it may be more efficient to directly index that data using the push-style indexing API. See Add, update, or delete documents for REST API reference, or you can use Azure Search .NET SDK | |
d10817 | I think Newtonsoft can do this for you.
string json = @"{
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
var jsonReturn = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>( json );
Console.WriteLine( jsonReturn.Email );
Based on this link:
https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
This is the most basic explanation. Use a foreach to iterate over de nodes
A: Using @Liam's suggestion of JObject I have come up with this working solution
public class MyObject
{
public int id { get; set; }
public int qty { get; set; }
public string discount { get; set; }
public decimal price { get; set; }
}
and then after retrieving the JSON response...
var jsonObj = JsonConvert.DeserializeObject<JObject>(response);
List<MyObject> myObjects = new List<MyObject>();
foreach (var item in jsonObj.AsJEnumerable())
{
var csp = JsonConvert.DeserializeObject<List<MyObject>>(item.First.ToString());
csp.ForEach(a => { a.product_id = Convert.ToInt32(item.Path); });
myObjects.AddRange(csp);
} | |
d10818 | I believe that you are looking for testNG listener( ITestListener ). you will have to implement the ITestListener and in that you will have to override the method called as onTestFailure. Please check the below code out.
import org.testng.ITestListener;
import org.testng.ITestResult;
public class TestNGListener implements ITestListener {
public void onTestFailure(ITestResult result) {
System.out.println(result.getThrowable().getMessage());
}
}
A: You can use printStackTrace() method of the java.lang.Throwable class, which is used to print this Throwable along with other details like class name and line number where the exception occurred.
try {
testException1();
} catch (Throwable e) {
// print stack trace
e.printStackTrace();
} | |
d10819 | Rails-API looks promising, because it will be part of Rails core in Rails 5.
Rails-API
Rails-API is a subset of a normal Rails application, because API only applications don't require all functionality that a complete Rails application provides. so, it compatible well with old Rails versions. I don't know compatibility exactly, but I'm using it with Rails 3.2.x
There are another proper framework for this purpose, for example, Sinatra, Grape, but If you familiar with Rails, Rails-API will be the best choice.
A: Actionwebservice is long deprecated, in favour of REST API's. At my previous job we used a fork of actionwebservice in a rails 3 project.
Since there is no maintainer anymore for the actionwebservice gem, that fork never got merged back. If you check the fork history, a lot of people are fixing and partially updating it, but it is scattered all over the place.
Afaik none of the forks were updated to use rails 4. But using a rails 3 fork might just work.
If you really need to build a SOAP API server with Rails, imho your best option is to take a look at Wash-out, but you will have to re-write your API code. | |
d10820 | You can use Except and Intersect:
var list1 = new List<MyObject>();
var list2 = new List<MyObject>();
// initialization code
var notIn2 = list1.Except(list2);
var notIn1 = list2.Except(list1);
var both = list1.Intersect(list2);
To find objects with different values (ColumnD) you can use this (quite efficient) Linq query:
var diffValue = from o1 in list1
join o2 in list2
on new { o1.columnA, o1.columnB, o1.columnC } equals new { o2.columnA, o2.columnB, o2.columnC }
where o1.columnD != o2.columnD
select new { Object1 = o1, Object2 = o2 };
foreach (var diff in diffValue)
{
MyObject obj1 = diff.Object1;
MyObject obj2 = diff.Object2;
Console.WriteLine("Obj1-Value:{0} Obj2-Value:{1}", obj1.columnD, obj2.columnD);
}
when you override Equals and GetHashCode appropriately:
class MyObject
{
//Key combination
string columnA;
string columnB;
decimal columnC;
//The Value
decimal columnD;
//Enum for comparison, used for styling the item (value hidden from UI)
//Alternatively...this could be a string type, holding the enum.ToString()
MyComparisonEnum result;
public override bool Equals(object obj)
{
if (obj == null || !(obj is MyObject)) return false;
MyObject other = (MyObject)obj;
return columnA.Equals(other.columnA) && columnB.Equals(other.columnB) && columnC.Equals(other.columnC);
}
public override int GetHashCode()
{
int hash = 19;
hash = hash + (columnA ?? "").GetHashCode();
hash = hash + (columnB ?? "").GetHashCode();
hash = hash + columnC.GetHashCode();
return hash;
}
} | |
d10821 | Before push, you need to commit your changes. It's done locally by:
#add files to specific commit
git add file1
# commit added files
git commit -m "init commit"
# stash file2 file3
git stash
# now, when working dir is clean you can safly pull updates from remote repo
git pull
# push your changes (your commit) to remote repo
git push origin master
#return file2 file3 changes
git stash apply
A: You can selectively stage files.
For example, let's say in the first commit you only wanted to use file1 and push only that:
git add file1
git commit -m "first bit of changes"
git push
With Git, you can stage files at a very granular level which allows you craft your commits in a logical way.
As for the other part of the question...
I try to push it but git doesn't allow to push because remote hed is
ahed than my local
Yes, this is definitly a good use-case for stash.
Do this:
git stash
git pull
git stash pop | |
d10822 | This link maybe helpful or you can use this:
double roundOff = Math.round(VACATION_DAYS_GEN_DAILY * 100.0) / 100.0;
the output:
21.98 | |
d10823 | It turns out that for some reason, various Windows versions that we have installed can end up with dramatically different sets of root certificates. All the machines that worked fine had around 320 some certs installed, the machines that fail to work only had around 70. COMODO eventually issued us a replacement certificate designed to validate against a different root... That works fine on all our machines. | |
d10824 | You can filter the relevant column numbers from ddff, and set the values in those columns in the first row equal to 1 and set the values in the remaining columns to 0:
relevant_columns = ddff.loc[0]
df.loc[0,relevant_columns] = 1
df.loc[0,df.columns[~df.columns.isin(relevant_columns)]] = 0
Output:
0 1 2 3 4
0 0 1 1 1 0
1 1 0 0 1 0
2 0 1 1 0 0
A: You can use:
s = ddff.loc[0].values
df.loc[0] = np.where(df.loc[[0]].columns.isin(s),1,0)
>>> df
0 1 2 3 4
0 0 1 1 1 0
1 1 0 0 1 0
2 0 1 1 0 0
Breaking it down:
>>> np.where(df.loc[[0]].columns.isin(s),1,0)
array([0, 1, 1, 1, 0])
# Before the update
>>> df.loc[0]
0 0
1 1
2 0
3 0
4 1
# After the assignment back
0 0
1 1
2 1
3 1
4 0 | |
d10825 | The issue here isn't your printing, it's your queue. Look at your dequeue() method:
def dequeue(self):
if self.size() <= 0:
self.reset()
return("Queue Empty")
data = self.queue[self.head]
self.head += 1
return data
At no point are you removing anything from self.queue, so naturally when you try to print it it'll not have changed.
The solution here, is instead of
data = self.queue[self.head]
which is itself a logic error (what if there are only 3 elements in self.queue and self.head == 5? You'd get an error), do
data = self.queue.pop(0)
which removes the first element from self.queue and returns it. Since in enqueue() you're adding to the end of the list and in dequeue() you'll be removing from the beginning of the list, it's a valid queue. | |
d10826 | GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
The sizes and styles can be set at run-time.
E.G.
import java.awt.*;
import javax.swing.*;
public class ShowFonts {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts = ge.getAvailableFontFamilyNames();
JComboBox fontChooser = new JComboBox(fonts);
fontChooser.setRenderer(new FontCellRenderer());
JOptionPane.showMessageDialog(null, fontChooser);
});
}
}
class FontCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel)super.getListCellRendererComponent(
list,value,index,isSelected,cellHasFocus);
Font font = new Font(value.toString(), Font.PLAIN, 20);
label.setFont(font);
return label;
}
}
JavaDoc
The JDoc for GraphicsEnvironment.getAvailableFontFamilyNames() state in part..
Returns an array containing the names of all font families in this GraphicsEnvironment localized for the default locale, as returned by Locale.getDefault()..
See also:
getAllFonts().. | |
d10827 | Since you are already using bootstrap, you might aswell want to use jQuery.
There is a plugin called bootstrap-select for achieving a multi select like in your example, where the syntax is as follows:
<select class="selectpicker" multiple>
<option>Mustard</option>
<option>Ketchup</option>
<option>Relish</option>
</select>
$(function () {
$('select').selectpicker();
});
You might also want to have a look at this question.
A: I just searched google with "bootstrap multiselect" and i found this codepen
$(document).ready(function() {
$('#multiple-checkboxes').multiselect({
includeSelectAllOption: true,
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
<div class="">
<strong>Select Language:</strong>
<select id="multiple-checkboxes" multiple="multiple">
<option value="php">PHP</option>
<option value="javascript">JavaScript</option>
<option value="java">Java</option>
<option value="sql">SQL</option>
<option value="jquery">Jquery</option>
<option value=".net">.Net</option>
</select>
</div> | |
d10828 | const RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: {
book: {
type: BookType,
args: { displayall: { type: GraphQLID } },
resolve(parent, args) {
return _.find(books, { displayall: args.displayall })
}
}
books:{
type: new GraphQLList(BookType),
resolve(parent, args) {
return books
}
}
}
}) | |
d10829 | Is it possible for you to place
self.navigationItem.title = @"YourName";
in the viewDidLoad of the other view? I'd try it that way and see if it works.
A: You must set the title from within the UIViewController. Try this:
controller.navigationItem.title=@"Application";
Infact apple docs on UINavigationItem for the "title" property states that:
title
A localized string that represents the view that this controller manages.
@property(nonatomic, copy) NSString *title
Discussion
Subclasses should set the title to a human-readable string that represents the view to the user. If the receiver is a navigation controller, the default value is the top view controller’s title.
Availability
Available in iOS 2.0 and later. | |
d10830 | Your method has a return type of string. That means your method should always return some string. But you are not returning a string. instead you are Writing it to the console using WriteLine method.
So Change
Console.WriteLine("Umbrella is selected");
to
return "Umbrella is selected";
OR
You can change your method's return type to void.
public void myFunction(string Value)
{
//your current fancy stuff here
Console.WriteLine("My method dont have a return type");
}
EDIT : AS per the question edit.
return statement will take the control out from your method. that means the next line (break) won't be executed. So remove the break statement.
case "Key Chain":
return "Key Chain is selected";
A: Well... You don't return anything from your function, so change it to
public void myFunction(string Value)
A: Try this:
class AddItemOptionOne
{
//Methods that define class functionality
public string myFunction(string input)
{
string result = string.Empty;
switch (input)
{
case "Key Chain":
result = "Key Chain is selected";
break;
case "Leather Armor":
result = "Leather Armor is selected";
break;
case "Boots":
result = "Boots is selected";
break;
case "Sword":
result = "Sword is selected";
break;
default:
result = "Input not reconized, please choose another item";
break;
}
return result;
}
} | |
d10831 | If R does not generate after a build anymore. It means that you have errors in your xml files.
Try right click on your project -> click Android Tools -> Fix Project Properties | |
d10832 | I think I have managed to resolve my own problem.
I changed the code to:
import geoip2.database
import csv
read_db = geoip2.database.Reader('./GeoLite2-Country_20210330/GeoLite2-Country.mmdb') #read database
with open('SrcIP.csv', 'r') as file1:
csv_read = csv.reader(file1, delimiter=' ', quotechar='|')
for row in csv_read:
response = read_db.country(', '.join(row))
filtered_res = response.country.iso_code
print(filtered_res)
Let me know what do you think. I cross-checked the results with the given IP addresses and the country code seems to be right. | |
d10833 | This is no use case for a Lambda expression (as the discussion on Sim's answer shows), but it could be if you wanted to leverage parallel processing:
using System.Threading.Tasks;
Parallel.ForEach(headers, header =>
client.DefaultRequestHeaders.Add(header.Key, header.Value)
);
I wouldn't do that in this case though. The class might not be thread-safe and there is nothing to be gained here in terms of performance. | |
d10834 | I don't known roblox but try this:
game.Workspace[myvar].Humanoid.WalkSpeed = 100
In this sense, Lua is like JavaScript. | |
d10835 | $(this).attr('id') This will not work since the function has not been attached to any object (So this will return undefined). You can pass the desired element as an argument to the function. You could do:
$('<button type="button" onclick="adding(document.querySelector('.stock_amount')[0])" class = "btn btn-default plus_"> + </button>').insertAfter($( "#" + filename )).attr('id','plus_'+filename);
and in the adding function:
function adding(input){
raw_id = '';
raw_id = raw_id + $(input).attr('id');
...
}
A: jQuery supports dynamic elements out of the box.
There's no need for vanilla js with onclick attributes and etc...
var btn = $('<button>', {
text: ' + ',
'class':'btn btn-default plus'
});
function adding(event){
// adding...
}
btn.on('click', adding).insertAfter($('.....whatever')); | |
d10836 | This code seems completely bizarre. Why are you doing all this work in Java rather than in XPath? Why are you modifying the DOM tree as you search it?
You just need to execute the XPath expression /ex/DtTm/TxDtTm[Cd='ABCD']/dt and you're there. | |
d10837 | To handle the individual exception accordingly.
For example:
If your program is handling both database and files. If an SQLException occurs, you have to handle it database manner like closing the dbConnection/reader etc., whereas if a File handling exception then you may handle it differently like file closing, fileNotFound etc.
That is the main reason in my point of view.
For point numbers 1 and 2:
If showing error message is you main idea then you can use if..else. In case if you want to handle the exception then check the above point of my answer. The reason why I stretch the word handling is because it is entirely different from showing a simple error message.
To add some quotes I prefer Best Practices for Handling Exceptions which says
A well-designed set of error handling code blocks can make a program
more robust and less prone to crashing because the application handles
such errors.
A: This works only if all exceptions share the same base class, then you could do it this way.
But if you do need exception type specific handling, then I would prefer multiple try-catch blocks instead of one with type-depending if-else ...
A: You can also ask why do we need the Switch - Case. You can do it with If - Else.
And why do you need Else at all. You can do it with If (If not the first condition, and...).
It's a matter of writing a clean and readable code.
A: By using single catch clock you can catch Exception type - this practice is strongly discouraged by Microsoft programming guidelines. FxCop has the rule DoNotCatchGeneralExceptionTypes which is treated as CriticalError:
Catching general exception types can hide run-time problems from the library user, and can complicate debugging.
http://code.praqma.net/docs/fxcop/Rules/Design/DoNotCatchGeneralExceptionTypes.html
The program should catch only expected exception types (one ore more), leaving unexpected types unhandled. To do this, we need possibility to have multiple catch blocks. See also:
Why does FxCop warn against catch(Exception)?
http://blogs.msdn.com/b/codeanalysis/archive/2006/06/14/631923.aspx | |
d10838 | Is it possible for a HTTP request to be that big ?
Yes it's possible but it's not recommended and you could have compatibility issues depending on your web server configuration. If you need to pass large amounts of data you shouldn't use GET.
If so how do I fix the OptionParser to handle this input?
It appears that OptionParser has set its own limit well above what is considered a practical implementation. I think the only way to 'fix' this is to get the Python source code and modify it to meet your requirements. Alternatively write your own parser.
UPDATE: I possibly mis-interpreted the question and the comment from Padraic below may well be correct. If you have hit an OS limit for command line argument size then it is not an OptionParser issue but something much more fundamental to your system design that means you may have to rethink your solution. This also possibly explains why you are attempting to use GET in your application (so you can pass it on the command line?)
A: A GET request, unlike a POST request, contains all its information in the url itself. This means you have an URL of 269KB, which is extremely long.
Although there is no theoretical limit on the size allowed, many servers don't allow urls of over a couple of KB long and should return a 414 response code in that case. A safe limit is 2KB, although most modern software will allow a bit more than that.
But still, for 269KB, use POST (or PUT if that is semantically more correct), which can contain larger chunks of data as the content of a request rather than the url.
A: Typical limit is 8KB, but it can vary (like, be even less). | |
d10839 | It's a quote question. Try This
$dir = "img/";
if ($opendir = opendir($dir) ) {
while ( ($file = readdir($opendir) ) !== FALSE) {
if ($file != "." && $file != "..") {
echo '<li class="col-lg-4 col-md-4 col-sm-3 col-xs-4 col-xxs-12">
<img class="img-responsive" src="'.$dir.'/'.$file.'">
</li>';
}
}
} | |
d10840 | I'd try setting the connection string outside of the constructor to help narrow down the issue:
MySqlConnection connect = new MySqlConnection();
//Do you get the null exception in this next line?
connect.ConnectionString = "your conn string here";
connect.Open(); //-> If you get the exception here then the problem is with the connection string and not the MySqlConnection constructor.
If you do get the exception in the connect.ConnectionString = ... line, then the problem is with the driver and sounds like you need to reinstall it.
I would also try a simpler connection string, without the pooling and reset keys.
A: Can you post more code? The exception line is probably a bit off due to compiler optimization or related. Constructors must return an object or throw an exception. It is impossible to say
MyType item = new MyType();
Debug.Fail(item == null); // will never fail.
The null reference is probably on the line just above your instantiation. | |
d10841 | OK, found an answer: '-bsf:v', 'dump_extra' | |
d10842 | Percentage calculation is basic mathematics:
$total = 160000;
$current = 12345;
$percentage = $current/$total * 100;
A: Just
percentage = number/160000 * 100
A: If N is the goal, and X is the number of people that have signed so far, then the percentage is (X/N)*100.
A: ...you can't convert a number to a percentage?
$percent = ($currentNumber / 160000) * 100;
If you don't want a float answer you can just cast or round it however you'd like.
A: 160,000/160,000 = 1 = 100%
160,000/2 = 0.5 = 50%
Given this, the calculation should be easy. The numerator is the number completed and the denominator is the "goal" -- the total to complete.
So once you are 80,000 you'd be 50% complete and your progress bar would render as such.
If you need to work with smaller numbers, divide everything by 100 or 1000 and you can reduce the size of the numbers in a relevant manor.
160,000 / 1000 = 160 160 would be your denominator. So than 50% would be 80/160. Does this make sense?
A: Do it Microsoft style:
current = 12345
percentage = 100*(1-exp(-current/100000)) | |
d10843 | window.addEventListener("exit", function () {
navigator.app.exitApp();
});
seems to be working fine after upgrading to android version 4.1.1
Cordova version : 5.0.0
InappBrowser Version : 1.1.0
No code changes were needed | |
d10844 | The error you are seeing is caused because your generated protobuf file likely has an incorrect import path.
If you check your product.pb.go file, it likely has a like like:
import "catalog/pb/entities"
This means it is trying to import the go package with that specified path. As you are probably familiar with, a go package must use the absolute path, so this needs to look something like:
import "github.com/<myuser>/<myproject>/catalog/pb/entities"
protoc-gen-go fortunately supports a couple of flags to help you with this.
Step 1. Set go_package in your .proto file to specify the anticipated import path in go.
option go_package = "example.com/foo/bar";
Step 2: use the --go_opt=module=github.com/<myuser>/<project> flag of protoc to strip the module prefix from your generated code. Otherwise you would get something like this as an output (assuming you are using the current directory as your go_out path
catalog/
main/
pb/
github.com/
<myuser>/
<project>/
catalog/
pb/
entities/
I would recommend reviewing the documentation page on the protoc-gen-go go flags: | |
d10845 | An alternative way to achieve that would be this:
df <- mutate(df,
v1_recode =case_when(v1 == "1" ~ 4,
v1 == "2" ~ 3,
v1 == "3" ~ 2,
v1 == "4" ~ 1,
TRUE ~ v1)) | |
d10846 | If you do this, you risk putting bad data into your data object, but here is how to do this:
In your MyTextBox.DataBinding.Add() method, use the this overload with OnPropertyChanged for the DataSourceUpdateMode param instead of the default OnValidate
I again say that this is one of those things that sounds really easy, but will likely cause issues in the long run as you are 'binding' to data that has never been validated.
A: Just call form's ValidateChildren() in the code on the button doing the save | |
d10847 | Open Dev Tools and see where the style applied to the h1 tag is declared.
Check if the style has been overwritten.
Try as follows:
h1 {
font-size:2.6em !important;
font-weight:bold !important;
color: #848381 !important;
} | |
d10848 | The mongod is being ran as a service or daemon, which means that there is always a mongod process running listening to a port. I use ubuntu, and when I install mongodb through the package manager, it immediately starts up a mongod process and begins listening on the standard port.
Running mongo is simply a small utility that attempts to connect to the localhost at the standard ip. The data reading, writing, and querying is done by the mongod process while mongo is a small program that sends the the commands to mongod.
If mongod wasn't running, you would see an error stating "Unable to connect to mongodb server"
A: I noticed the same. I think mongoose is doing some smart things there, which I'm not sure how it works. But I have noticed such things before, like mongoose will automatically add an "s" to your database's name when you declare it, which is a very thoughtful act =)).
A: I encountered the same thing and found that in the background services if MongoDB server is running, the mongo shell will work without any error. If we stop the service, the shell will throw an error. | |
d10849 | it seems that the canvas is taking the mouse event preventing the resize. If you consider pointer-events:none on canvas it will work:
#outer {
width: 100px;
height: 100px;
overflow: hidden;
resize: both;
border: 1px solid black;
}
#inner {
width: 100%;
height: 100%;
pointer-events:none
}
<div id="outer">
<canvas id="inner"></canvas>
</div>
To better illustrate, decrease the size of the canvas a little to avoid the overlap with the resize widget and it will also work:
#outer {
width: 100px;
height: 100px;
overflow: hidden;
resize: both;
border: 1px solid black;
}
#inner {
width: 100%;
height: calc(100% - 10px);
background:red;
}
<div id="outer">
<canvas id="inner"></canvas>
</div>
You can also play with z-index:
#outer {
width: 100px;
height: 100px;
overflow: hidden;
resize: both;
border: 1px solid black;
position:relative;
z-index:0; /* mandatory to create a stacking context and keep the canvas inside */
}
#inner {
width: 100%;
height: 100%;
position:relative;
z-index:-1;
background:red;
}
<div id="outer">
<canvas id="inner"></canvas>
</div> | |
d10850 | You can simply do it like this:
<td ng-if="obj.value != ''">{{obj.value | number: obj.value % 1 === 0 ? 0 : 1}}</td>
You find a more detailed explanation about the number pipe here in this documentation and regarding checking integer there are multiple answers but you can refer this question for them. | |
d10851 | The standard technique is to use a prepared insert statement, inside a loop inside a transaction. That will give you almost optimal efficiency in most instances. It will speed things up by at least an order of magnitude.
A: I personally don't know many blackberry-specific practices, but these seem to be helpful (sorry I couldn't find code snippets):
"Top 8 SQL Best Practices"
"Best Practice: Optimizing SQLite Database Performance"
Hope these help!
A: You should do one thing is that, create different methods for database handling code.
and simply call these methods from your main code and open and close database also in each and every block. It will reduce redundancy and will be better for your future. This will also helps you in your App performance. | |
d10852 | You cannot read the eve files as this is a proprietary format. Actually there are many more files that need to be read in order to decipher the eve files. What you can do is to open a new session with your results in Analysis tool that comes with LoadRunner. It will create a database file for you from the eve files based on the database you configured in the tool. You can then try to use this database to do your own analysis. | |
d10853 | In addition to the other answers:
Essentially this question is an indirect duplicate of Changes to object made with Object.assign mutates source object.
Object.assign is safe to use for a max of 2 levels of nesting.
For example Object.assign(myObj.firstProp, myDefaultObj.firstProp);
Taken from the MDN documentation:
Warning for Deep Clone For deep cloning, we need to use other
alternatives because Object.assign() copies property values. If the
source value is a reference to an object, it only copies that
reference value. | |
d10854 | This is actually doable if your operator starts with a # character, since that character has a higher precedence than function application.
let (#%) = Printf.sprintf;;
val ( #% ) : ('a, unit, string) format -> 'a = <fun>
"Hello %s! Today's number is %d." #% "Pat" 42;;
- : string = "Hello Pat! Today's number is 42."
A: (1) I don't think there's a good way to do it that is going to be nicer than using Printf.sprintf directly. I mean, you can extend what you've already come up with:
let (%) = Printf.sprintf
let str3 = ("this: %s; that: %s; other: %s" % this_var) that_var other_var
which works, but is ugly because of the parentheses that are necessary for precedence.
(2) It's really hard to generate a format string at runtime because format strings are parsed at compile time. They may look like string literals, but they are actually a different type, which is "something format6". (it figures out whether you want a string or format string based on the inferred type) In fact, the exact type of a format string depends on what placeholders are in the format; that's the only way that it is able to type-check the number and types of format arguments. It's best not to mess with format strings because they are tied very heavily into the type system.
A: Why would one want to replace statically checked sprintf with some dynamic formatting? OCaml's Printf is both compact in usage and safe at runtime. Compare that to C printf which is compact but unsafe and C++ streams which are safe but verbose. Python's format is no way better than C printf (except that you get exception instead of crashdump).
The only imaginable use-case is format string coming from external source. And it is usually better to move it to compile-time. If it is not possible, then only one needs to fallback to manual dynamic formatting with error-handling (as already said you cannot use Printf with dynamic format string). BTW one such case - internationalization - is covered with existing libraries. Generally, if one wants to dynamically combine multiple values of different types, then one has to wrap them with variants (like ['S "hello"; 'I 20]) and pattern-match at printing side.
A: You should check out OCaml Batteries Included's extended/extensible printf. I have the feeling that you can do what you want with it.
A:
If Ocaml cannot dynamically generate
some string as format6 str and pass it
to sprintf? for code:
let s = "%s" in Printf.sprintf s "hello"
What if we bypass the typing system...
external string_to_format :
string -> ('a, 'b, 'c, 'd, 'e, 'f) format6 = "%identity"
let s = string_to_format "%s" in (Printf.sprintf s "hello" : string);;
I don't claim this to be the ultimate solution, but that's as far as I got after looking at the mailing list, http://pauillac.inria.fr/caml/FAQ/FAQ_EXPERT-eng.html#printf and ocaml's src. | |
d10855 | wthreshold and cthreshold are strings coming from the command line arguments. If you want to compare them numerically, you need to convert them to numbers:
wthreshold, cthreshold = [int(x) for x in sys.argv] | |
d10856 | Your example link is exactly what you need, but you need to get your information from a MemoryStream instead of an existing file.
You can turn a string directly into a Stream with this:
MemoryStream memStr = MemoryStream(UTF8Encoding.Default.GetBytes("asdf"));
However, you can shortcut this more by directly turning your string into a byte array, avoiding the need to make a Stream altogether:
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
Byte[] bytes = encoding.GetBytes(yourString);
//and now plug that into your example
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Close(); | |
d10857 | We use an iTouch for development (cheaper than buying iPad2's). So yes, you can definitely develop for iOS using an iTouch/iPod.
You will also need to join the Apple developer program before you can deploy to the iTouch - Apple has a $99 annual fee for an individual. Even if you purchase Unity you will need buy into the Apple dev program too.
A: same code will work in iphone,ipad ,ipod .so no problem.so that the name of IDE is xcode.but performance and image accuracy will be varied.
http://unity3d.com/company/news/iphone-press.html
A: Apple provides a SDK including a simulator. Never trust the simulator completely, but you can use it easily for day by day job, and test it on a real iphone, ipod touch or similar only from time to time. | |
d10858 | Lets start interpreting the code line-by-line:
*
*
*
*Variable initialization
*
*
import cv2
cam=cv2.VideoCapture(0)
a=0
count=0
*You load the opencv library and initialize the cam variable for webcam display. Then both a and count are intialized to 0. Now count variable is understandable, most probably count count the frames. What does a do?
*
*Display and save frames
*
*First-part
*
for a in range(0, 5):
ret,img=cam.read()
cv2.imshow("Test",img)
if not ret:
break
*variable a declared again so we don't need to intialize at the beginning. Then current web-frame is being fetched. The frame is given as an input to imshow without even the current frame returned or not. The correct logic should be:
*
for a in range(5):
ret,img=cam.read()
if ret:
cv2.imshow("Test",img)
*Second-part
*
k=cv2.waitKey(1)
print("Image"+str(count)+"saved")
file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2'+str(count)+'.jpg'
cv2.imwrite(file,img)
a+=1
*Now, the k variable is initialized as a key for quiting the program when a key is pressed. Say, when q is pressed program terminates.
*
k=cv2.waitKey(1) & 0xFF
if k == ord('q'):
break
*But if you break during the process, then you can't save the images. Therefore break should be at the end of the line.
*For the rest of the code, you can use a as a counter. If you specify the start and end values. For each value a is increased by one. Then you can use it to discriminate the frames.
Code:
# Load the library
import cv2
# Initialize webcam
cam = cv2.VideoCapture(0)
# Save the frames
for a in range(0, 5):
# Get current frame
ret, img=cam.read()
# If frame is returned
if ret:
# Set the file-name
file='C:/Users/User/Desktop/FACEREC/known_faces/img_test/ad2' + str(a) + '.jpg'
# Write the frame
cv2.imwrite(file, img)
# Inform the user
print("Image" + str(a) + "saved")
# Display the frame
cv2.imshow("Test", img)
# If q is pressed quit
k=cv2.waitKey(1) & 0xFF
if k == ord('q'):
break
# Release the object
cam.release()
# Close the window
cv2.destroyAllWindows() | |
d10859 | I don't understand exactly what you're asking - you should always provide examples of what you want to have. I'm assuming what you mean is you want to see the word "million" or "billion", as appropriate. This can be done using a separate IF field:
{ IF { MERGEFIELD AreaSales } > 999999.99 "{ IF { MERGEFIELD AreaSales } < 1000000000 "million" "billion" }" "" } | |
d10860 | Object references in Java are passed by value. Assigning just changes the value, it does not alter the original object reference.
In your example arr[0] is changed, but try arr=null and you will see it has no effect after the method has returned.
A: Method call is called by value in Java, well there is long debate about this , But I think that we should consider in terms of implementation language of Java which is C/C++. Object references just pointers to objects, and primitives are the values.. Whenever a method is called, actual arguments are copied to formal parameters. Therefore, if you change pointer to reference another object , original pointer is not affected by this change, but if you change object itself, calling party can also see the changes, because both party are referring the same object..
Well, in your example, you are changing string reference to null in called method, but you are changing object referred by array reference.. These two operations are not the same, therefore they do have different consequences.. for example, if you change the code as below, they would be semantically same operation..
arr = null;
A: You cnanot change the argument for any method, however you can do the following.
public static void main(String... args) throws IOException {
String[] strings = {"Hello "};
addWorld(strings);
System.out.println("Using an array "+Arrays.toString(strings));
StringBuilder text = new StringBuilder("Hello ");
addWorld(text);
System.out.println("Using a StringBuilder '" + text+"'");
}
private static void addWorld(String[] strings) {
for(int i=0;i<strings.length;i++)
strings[i] += "World!";
strings = null; // doesn't do anything.
}
private static void addWorld(StringBuilder text) {
text.append("World !!");
text = null; // doesn't do anything.
}
prints
Using an array [Hello World!]
Using a StringBuilder 'Hello World !!' | |
d10861 | You have an error in your second GetLeaves function. The statement root = null; sets the value of the local variable root to null, but its parent will keep the reference to the leaf.
You will have a much easier time if you add a method bool isLeaf() to TreeNode. I modified your code to something I think might work.
private bool isLeaf()
{
// This method should be in TreeNode
return left == null && right == null;
}
// Also, TreeNode should have an Add(TreeNode) method
public TreeNode getLeaves(TreeNode root)
{
if( root == null ) // check if the whole tree is empty
return null; // return something relevant here
else if( root.isLeaf() )
return root; //cannot remove this leaf, unfortunately
TreeNode leaves = new TreeNode()
getLeaves(root, leaves);
return leaves;
}
private void getLeaves(TreeNode current, TreeNode leaves)
{
// current is guaranteed to be non-null and not a leaf itself.
if( current.left.isLeaf() ) {
leaves.add(current.left);
current.left = null;
} else {
getLeaves(current.left, leaves);
}
if( current.right.isLeaf() ) {
leaves.add(current.right);
current.right = null;
} else {
getLeaves(current.right, leaves);
}
}
A: David, you are 100% right. Thank you for helping. In case anyone is wondering, here is the most elegant solution I produced so far, including David's improvement. The only thing I'm not sure about is if the addToList method should be static or maybe it's more properly/universal to call it in element's context.
public TreeNode getLeaves(TreeNode root)
{
if(root == null)
return null;
if(root.isLeaf())
return root;
TreeNode[] listEdges = {null, null};
getLeaves(root, listEdges);
return listEdges[0];
}
private void getLeaves(TreeNode root, TreeNode[] edges)
{
if(root == null)
return;
if(root.left != null && root.left.isLeaf())
{
addToList(edges, root.left);
root.left = null;
}
if(root.right != null && root.right.isLeaf())
{
addToList(edges, root.right);
root.right = null;
}
getLeaves(root.left, edges);
getLeaves(root.right, edges);
}
private static void addToList(TreeNode[] edges, TreeNode element)
{
if(edges[1] != null)
{
edges[1].right = element;
element.left = edges[1];
edges[1] = element;
}
else
{
edges[0] = element;
edges[1] = edges[0];
}
}
public boolean isLeaf()
{
return this.right == null && this.left == null;
} | |
d10862 | Do you know (or test) Java 3D API ?
Useful link : Java 3D API or Java net link
There is also another library : jmathplot (to draw diagram or others) --> it's easier than java 3d API.
It's two diferent philosophy. With the first you have to "draw point by point", with the second (jmathplot) you can use predefined elements and mathematical functions.
A: I think Java Surface Plot might be what you're looking for.
http://javasurfaceplot.sourceforge.net/
A: In order to communicate with the hardware just about any Java 3d library is going to have some dependencies.
You might try this:
http://www.mediafire.com/download/8ui3uwduw17bnx9/OpenGL.rar
There is a video tutorial set available for it. Just drawing a surface shouldn't be a problem.
http://www.youtube.com/watch?v=V1EvbHFtjCE
If you really want to get into Java 3D I would just search around for as much info on the various competing libraries and pick one for what you want to do with it.
edit:
The surface library fron other answer looks promising. I also found https://jogamp.org/jogl/www/ the JOGL or The Java API for OpenGL. | |
d10863 | When you do this:
vector<string>::const_iterator it = myObject->getList().begin();
At the end of the line, the iterator it is invalid, because the vector<string> returned by getList() is a temporary value.
However, when you store the vector<string> in a local variable, with
vector<string> myList = myObject.getList();
Then, the iterator remains valid, as long as myList is not destroyed.
A: In the frist case the code has undefined behaviour because the temporary object of type std::vector<std::string> returned by function myObject.getList() will be deleted at the end pf executing the statement. So the iterator will be invalid.
Apart from the valid code in the second example you could also write
const vector<string> &myList = myObject.getList();
vector<string>::const_iterator it = myList.begin();
cout << *it << endl;
that is you could use a constant reference to the temporary object.
A: The problem is that you are returning a copy of vector, it would go out of scope and out of existance, thus be invalid.
What you want to do is return a const reference to your list.
const vector<string>& getList(); | |
d10864 | The trick is to notice that you can calculate the Fibonacci numbers using matrix multiplication:
| 0 1 | | a | | b |
| 1 1 | * | b | = | a + b |
With this knowledge, we can calulate the n-th Fibonacci number:
| 0 1 |^n | 0 |
| 1 1 | * | 1 |
Because matrix multiplication is associative, we can efficiently calculate m^n.
*
*If n is even, m^n = m^(n/2) * m^(n/2)
*If n is odd, m^n = m^((n-1)/2)) * m^((n-1)/2)) * m
Note that we need the same thing twice, but we only have to compute it once.
This makes it possible to calculate the n-th Fibonacci number in O(log n).
I leave it to you to write the code. | |
d10865 | TRY IT
<?php
session_name("first");
session_start();
echo session_status();
session_destroy();
echo session_status();
session_name("second");
session_start();
echo session_status();
session_destroy();
echo session_status();
?>
I've tested it on xampp and it returns values 2121 meaning session is active, none exist, the session is active, none exist.
I've placed session_name() before session_start() because setting the name as you did doesn't take effect after a session has already been started. I've googled it and it has to do something with the php.ini file where session.auto_start is set to "true".
The explanation and a debate on this topic are found here: http://php.net/manual/en/function.session-name.php - check comments.
EDITED:
After reviewing your edit again, you basically don't create two sessions but only one and it starts with a random name "first" or "second". You can destroy a session but the cookie will remain. I've tested your code on xampp and it does exactly that. First, the PHP starts one session and stores a cookie with a time value of "session", after reloading the page it will load one of two options again but this time it will change the existing cookie time to "N/A". You should search for a solution to clear your cookies on your domain after page loads like so:
<?php
$session_name = rand(0,1) ? 'first' : 'second';
session_name($session_name);
session_start();
deleteCookies($session_name);
function deleteCookies($skip_this_one) {
if (isset($_SERVER['HTTP_COOKIE'])) {
$cookies = explode(';', $_SERVER['HTTP_COOKIE']);
foreach($cookies as $cookie) {
$parts = explode('=', $cookie);
$name = trim($parts[0]);
if ($name == $skip_this_one) {
//skip
}else{
setcookie($name, '', time()-1000);
setcookie($name, '', time()-1000, '/');
}
}
}
//do something inside your session
//when done, stop the session the way you want
session_destroy();
}
?>
This will delete all previous cookies and keep the current session open.
This solution is re-written from here: how to delete all cookies of my website in php
Hope this helps :)
A: Please try below code
<?php unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
?> | |
d10866 | If you are facing issues like that then you can try this :
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo 'http://'.parse_url($url, PHP_URL_HOST) . '/'; | |
d10867 | In your for-loop, in the first iteration head is set to a new node.
In the second iteration, something strange is done:
current = (seg*)malloc(sizeof(seg));
current = head;
Now you've allocated some space, but you have overwritten the pointer to it (this is a memory leak). Afterwards it goes wrong:
while(current->next != NULL){
current = current->next;
}//while
node = current->next;
node->prev = current;
Here, node is set to NULL so you're writing into the null address, hence the core dump. | |
d10868 | First, with a group by statement, you don't need the DISTINCT clause. The grouping takes care of making your records distinct.
You may want to reconsider the order of your tables. Since you are interested in the shops, start there.
Select s.username, count(v.id)
From instagram_shop s
INNER JOIN instagram_shop_picture p ON p.shop_id = s.shop_id
INNER JOIN instagram_item_viewer v ON v.item_id = p.id
AND v.created >= '2014-08-01'
WHERE s.expirydate IS NULL
AND s.isLocked = 0
GROUP BY s.username
Give thata shot.
A: As mentioned by @Lennart, if you have a sample data it would be helpful. Because otherwise there will be assumptions.
Try run this to debug (this is not the answer yet)
SELECT s.username, p.id, COUNT( v.id ) AS cnt
FROM `instagram_item_viewer` v
INNER JOIN `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN `instagram_shop` s ON p.shop_id = s.id
AND s.expirydate IS NULL
AND s.isLocked =0
AND v.created >= '2014-08-01'
GROUP BY (
s.username, p.id
)
ORDER BY cnt DESC
The problem here is the store and item viewer is too far apart (i.e. bridged via shop_picture). Thus shop_picture needs to be in the SELECT statement.
Your original query only gets the first shop_picture count for that store that is why it is less than expected
Ultimately if you still want to achieve your goal, you can expand my SQL above to
SELECT x.username, SUM(x.cnt) -- or COUNT(x.cnt) depending on what you want
FROM
(
SELECT s.username, p.id, COUNT( v.id ) AS cnt
FROM `instagram_item_viewer` v
INNER JOIN `instagram_shop_picture` p ON v.item_id = p.id
INNER JOIN `instagram_shop` s ON p.shop_id = s.id
AND s.expirydate IS NULL
AND s.isLocked =0
AND v.created >= '2014-08-01'
GROUP BY (
s.username, p.id
)
ORDER BY cnt DESC
) x
GROUP BY x.username | |
d10869 | Found the answer. I have to have an additional column to the data that has a defined color based on the grouping variable. Once that is done passing the following argument for bar label works.
barlabel= c("Title", "Color.style")
The color column must be named anytext.style for it to work properly. | |
d10870 | Culling doesn't mean that an object is drawn or not. It can be either drawn or not drawn depending on where it is. It is an optimization that tries to say something like this:
Hey, i have a really cheap check (plane/sphere intersection) that i can do and tell you if you need to attempt to draw this at all.
So you do a cheap check, and if the object is guaranteed to be entirely out of the frustum, you never issue the draw call. If it intersects, you have to issue a draw call, but you may still see nothing if none of the triangles are actually in the frustum.
If you download something like specter.js and inspect your draw calls, you will infact see that with frustumCulled = false you get a draw call for every object in your scene. Your screen may be empty. | |
d10871 | Update
Looking at the AndroidManifest.xml for the Settings app there is an Activity Settings$ZenModeSettingsActivity already from Android 5.0.
To send the user to the "Do not disturb" screen you can use the action android.settings.ZEN_MODE_SETTINGS like this:
try {
startActivity(new Intent("android.settings.ZEN_MODE_SETTINGS"));
} catch (ActivityNotFoundException e) {
// TODO: Handle activity not found
}
Original answer
It looks like there are no screens in the Settings app (at least on Android 6+7) where you can enable/disable DND. It seems like this is only available through the settings tile (and can be disabled in the dialog when changing the volume).
I have a Samsung S6 (Android 6.0.1) which has this screen, but this is probably some custom Samsung changes. The screen is represented by the class com.android.settings.Settings$ZenModeDNDSettingsActivity which can be started by any app. This might be of help for some people out there.
AndroidManifest.xml for Settings app for Android 6+7:
*
*https://android.googlesource.com/platform/packages/apps/Settings/+/android-6.0.1_r68/AndroidManifest.xml
*https://android.googlesource.com/platform/packages/apps/Settings/+/android-7.0.0_r6/AndroidManifest.xml
A: You have to use the following Intent: ACTION_VOICE_CONTROL_DO_NOT_DISTURB_MODE and then pass a boolean through EXTRA_DO_NOT_DISTURB_MODE_ENABLED.
Make note that the documentation specifies the following: This intent MUST be started using startVoiceActivity. | |
d10872 | The package that you should be adding to REQUIRED_PACKAGES list in setup.py is 'absl-py>=0.1.0'. Apart from that, download this package tar.gz file to models/research/dist . Install by running pip install absl-py . Then, when starting the job add dist/avsl-0.4.0.tar.gz to the variables passed to the --packages flag. | |
d10873 | I was waiting to see if any of the first commenters were going to answer, but they haven't so I will.
Since in the definition of c() the first argument is ..., you must completely name any arguments that follow for them to work correctly. I say arguments plural and not argument singular because there is actually a second, undocumented argument in c(). See Why does function c() accept an undocumented argument? for more on that. For arguments that come before ..., you can use partial argument matching, but for those after ... you must write the complete argument name.
What's happening in your example is that you are concatenating the numeric value of TRUE (which is 1) to the vector 1:5
as.numeric(TRUE) ## numeric value of TRUE
# [1] 1
c(1:5, TRUE) ## try no arg name, wrong result
# [1] 1 2 3 4 5 1
c(1:5, rec=TRUE) ## try partial arg matching, wrong result
# rec
# 1 2 3 4 5 1
Furthermore, recursive really does nothing in the manner that you're attempting to use it.
c(1:5)
# [1] 1 2 3 4 5
c(1:5, recursive=TRUE) ## 1:5 not recursive, same result
# [1] 1 2 3 4 5
is.recursive(c(1:5))
# [1] FALSE
It's more for concatenating list items, or any other recursive objects (see ?is.recursive).
(x <- as.list(1:5))
# [[1]]
# [1] 1
#
# [[2]]
# [1] 2
#
# [[3]]
# [1] 3
#
# [[4]]
# [1] 4
#
# [[5]]
# [1] 5
is.recursive(x)
# [1] TRUE
c(x, recursive=TRUE) ## correct usage on recursive object x
# [1] 1 2 3 4 5 | |
d10874 | Jason array format can be found here
Looking at the example in the link you can see that you have an extra brace and an extra coma.
Solution:
Move , (coma) from + '},' to ',{ "some_data":"
Remove extra curly brace: '": [{' + STUFF( -> '": [' + STUFF(
Update:
Non-varchar columns will need to be converted to (N)VARCHAR: CONVERT( NVARCHAR, [field] )
Final Query:
SELECT '{"' + t.groupId + '": [' + STUFF(
(
SELECT ',{ "some_data":"' + td.some_data + '"', ', "some_other_data":' + CONVERT( NVARCHAR, td.some_other_data ) + '}'
FROM some_table td
WHERE t.groupId = td.groupId
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '') + ']}'
FROM some_table t
GROUP BY t.groupId
P.S. looks like https://stackoverflow.com/a/45427001/6305294 simply has made a typo with the brace
A: If you are on MSSQL 2016:
SELECT t.groupId,
(
SELECT td.some_data, td.some_other_data
FROM some_table td
WHERE t.groupId = td.groupId
FOR JSON PATH
) As json_data
FROM some_table t
GROUP BY t.groupId
You can find the docs https://learn.microsoft.com/en-us/sql/relational-databases/json/json-data-sql-server | |
d10875 | I could not fully test your code however here is what you would do when needed to destroy master. Your code was a bit hard to test please in the future do not include stuff that cannot be tested like your ScoreboardController. Also I rewrote your buttons to something simpler.
import tkinter as tk
class Example(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.create_widgets()
def start_game(self):
pass
def hide_main_window(self):
self.score_button.pack_forget()
self.start_button.pack_forget()
def create_widgets(self):
self.start_button = tk.Button(self, text="Játék indítása", bg="#5E99FF", fg="#ffffff")
self.start_button.pack()
self.score_button = tk.Button(self, text="Eredmények", bg="#5E99FF", fg="#ffffff", command=self.start_game)
self.score_button.pack()
self.quit_button = tk.Button(self, text="Kilépés", bg="#5E99FF", fg="#ffffff", command=self.master.destroy) # without ()
self.quit_button.pack()
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack() # root passing to master in the Frame class
root.mainloop() | |
d10876 | Because iCantThinkOfAGoodLabelName: needs to be right before the loop.
iCantThinkOfAGoodLabelName:
for (blah; blah; blah)
..
I think what you want is a function..
function iCantThinkOfAGoodFunctionName() {
var x = genX(radius),
y = genY(radius);
for (i in circles) {
var thisCircle = circles[i];
if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) { //No overlap
continue;
} else { //Overlap
iCantThinkOfAGoodFunctionName();
}
thisCircle = [];
}
}
A: There should not be any statement between a label name and associated loop.
x = genX(radius);
y = genY(radius);
iCantThinkOfAGoodLabelName:
for(i in circles) {
fixes it.
A: The label should come immediately before the loop
x = genX(radius);
y = genY(radius);
iCantThinkOfAGoodLabelName:
for(i in circles) {
A: I recently had this issue and I resolved it by using all lowercase in the loop's label in version v0.8.x of Node.js.
Using labelname: vs. iCantThinkOfAGoodLabelName: might help you.
Others have correctly corrected you on the location of the label. It should be immediately before the for loop.
The Mozilla Developer Network on labels advises to avoid using labels, and instead prefer calling functions or throwing an error. You might rethink your strategy on using them, if possible.
Example of calling a function depending on result:
var i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (i == 1 && j == 1) {
// we want to ignore and continue
} else {
// do work with these variables from inside the doWork function
// (scoped to whatever scope `this` for loop is in)
doWork.call(this, i, j);
}
}
} | |
d10877 | According to the matrix, you can either use v2.5.0 or v2.6.0. | |
d10878 | The boost interface is much more like what got into the standard. So if you plan to go that route at some point, it might be easier to change if you're using boost.
A: Since C++11, there is a random generator engine that is in the standard library.
Nothing comparable with the old rand() function from C.
There are a bunch of random distributions, you can specify the interval ... | |
d10879 | Net::SSLeay::OPENSSL_VERSION_NUMBER() 0x009081df
This is OpenSSL 0.9.8, at least 7 years old, not supporting TLS 1.1 and TLS 1.2 and not supporting any ECDHE ciphers. Also, no support for SNI within IO::Socket::SSL for this old version of OpenSSL.
Looking at the SSLLabs report for www.themoviedb.org you'll see:
This site works only in browsers with SNI support.
Thus, you'll need to upgrade your version of OpenSSL. Note that you also need to recompile Net::SSLeay afterwards and link it to the newer OpenSSL version. | |
d10880 | Which version of beam are you using?
Thanks for bringing this issue. I tried to reproduce your case and indeed there seems to be an issue with colliding versions of guava that breaks transforms with HBaseIO. I sent a pull request to fix the shading of this, I will keep you updated once it is merged so you can test if it works.
Thanks again. | |
d10881 | Prepared statements are not worth the problems at MySQL, they are not much faster than classic SQL statements. They are not compiled as in other RDBMS.
I think in this case it would be better to use a batch insert instead of a prepared statement. | |
d10882 | You need to do it as shown below.
Note :
Wrong : regionTypeId.Contains(sites.Regions.SelectMany(x=>x.RegionTypeId).ToArray())
Correct : regionTypeId.Any(item => sites.Regions.Select(x => x.RegionTypeId).Contains(item))
Working sample :
int?[] contractsIDList = { 1, 2};
int?[] siteTypeId = { 1, 2, 3};
int?[] regionTypeId = { 1, 2, 3};
var result = (from sites in db.Set<Site>()
where contractsIDList.Contains(sites.ContractId) && siteTypeId.Contains(sites.SiteTypeId)
&& regionTypeId.Any(item => sites.Regions.Select(x => x.RegionTypeId).Contains(item))
select sites).AsNoTracking<Site>();
Result : | |
d10883 | Are you using backticks here?
$stk=$_POST[‘stock’];
They need to be quote marks
$stk=$_POST['stock'];
Also this line has an utf-8 fancy-quote
$query=mysql_query("SELECT Title FROM books WHERE Stock>`$stk”);
which should be an ascii quote
$query=mysql_query("SELECT Title FROM books WHERE Stock>$stk");
These are common errors when you copy code from blogs ;) | |
d10884 | file_get_contents() generates an E_WARNING level error (failed to open stream) which is what you'll want to suppress as you're already handling it with your exception class.
You can suppress this warning by adding PHP's error control operator @ in front of file_get_contents(), example:
<?php
$path = 'test.php';
if (@file_get_contents($path) === false) {
echo 'false';
die();
}
echo 'true';
?>
The above echoes false, without the @ operator it returns both the E_WARNING and the echoed false. It may be the case that the warning error is interfering with your throw function, but without seeing the code for that it's hard to say.
A: You have 2 solution the poor one is to hide the error like that
public function getData($path){
if(@file_get_contents($path) === false){
throw new FileNotFoundException;
}
return $file;
}
Or check maybe if the file exist (better solution i guess)
public function getData($path){
if(file_exists($path) === false){
throw new FileNotFoundException;
}
return $file;
} | |
d10885 | if a constant isn't defined, PHP will treat it as String ("HELLO_WORLD" in this case) (and throw a Notice into your Log-files).
You could do a check as follows:
function my_function($foo) {
if ($foo != 'HELLO_WORLD') {
//Do something...
}
}
but sadly, this code has two big problems:
*
*you need to know the name of the constant that gets passed
*the constand musn't contain it's own name
A better solution would be to pass the constant-name instead of the constant itself:
function my_function($const) {
if (defined($const)) {
$foo = constant($const);
//Do something...
}
}
for this, the only thing you have to change is to pass the name of a constant instead of the constant itself. the good thing: this will also prevent the notice thrown in your original code.
A: You could do it like this:
function my_function($Foo) {
if (defined($Foo)) {
// Was passed as a constant
// Do this to get the value:
$value = constant($Foo);
}
else {
// Was passed as a variable
$value = $Foo;
}
}
However you would need to quote the string to call the function:
my_function("CONSTANT_NAME");
Also, this will only work if there is no variable whose value is the same as a defined constant name:
define("FRUIT", "watermelon");
$object = "FRUIT";
my_function($object); // will execute the passed as a constant part
A: Try this:
$my_function ('HELLO_WORLD');
function my_function ($foo)
{
$constant_list = get_defined_constants(true);
if (array_key_exists ($foo, $constant_list['user']))
{
print "{$foo} is a constant.";
}
else
{
print "{$foo} is not a constant.";
}
} | |
d10886 | Quite a few issues here.
*
*Your script will spew errors if filenames include a percent sign, since printf "$file" will interpret its first argument as a format. Use printf '%s' "$file" instead.
*You haven't quoted the filename argument when you run pdftotext, which is likely why it throws its help message -- pdftext foo bar.pdf - looks like two arguments, not one filename. pdftotext "$file" instead. (As a rule, always quote your variables in bash.)
*If you want to show output only for matching files, you need to evaluate a condition before you print the filename.
I don't know how pdftotext behaves exactly, but assuming it doesn't produce a bunch of stderr, the following might work:
#!/usr/bin/env bash
line=$(printf '%032s' 0); line=${line//0/-}
for file in */*.pdf; do
output="$(pdftotext "$file" - | grep -i "$1")"
if [ -n "$output" ]; then
printf "%s\n$line\n%s\n$line\n\n" "$file" "$output"
fi
done
Note: I haven't tested this. You might want to expand the printf with the $line references for readability if this format appears complex or obtuse. | |
d10887 | Yes, sort of.... it is possible to create some very long and deep nested types, more or less automatically. The trick is you need to use generic type inference, and since constructors don't do inference, you have to use a factory method. For example:
public class MyType<TData,TChild>
{
public MyType(TData data, TChild child)
{
}
}
public class MyTypeFactory
{
public static MyType<TData,TChild> Create<TData,TChild>(TData data, TChild child)
{
return new MyType<TData,TChild>(data, child);
}
public static MyType<TData,object> Create<TData>(TData data)
{
return new MyType<TData,object>(data, null);
}
}
public static class Program
{
static public void Main()
{
var grandchild = MyTypeFactory.Create( 12 );
var child = MyTypeFactory.Create( 13D, grandchild );
var parent = MyTypeFactory.Create( 14M, child) ;
var grandparent = MyTypeFactory.Create( 15F, parent );
Console.WriteLine( grandchild.GetType().FullName );
Console.WriteLine( child.GetType().FullName );
Console.WriteLine( parent.GetType().FullName );
Console.WriteLine( grandparent.GetType().FullName );
}
}
The output:
MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
MyType'2[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
MyType'2[[System.Single, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Decimal, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Double, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[MyType'2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]], uy2zelya, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null]]
It's even type-safe, amazingly enough. If you add the necessary properties...
public class MyType<TData,TChild>
{
protected readonly TChild _child;
protected readonly TData _data;
public MyType(TData data, TChild child)
{
_data = data;
_child = child;
}
public TChild Child
{
get
{
return _child;
}
}
public TData Data
{
get
{
return _data;
}
}
}
...this will work:
var grandchildValue = grandparent.Child.Child.Child.Data;
Console.WriteLine(grandchildValue); //12
Console.WriteLine(grandchildValue.GetType().Name); //int32
And of course you can use the builder pattern:
public static class ExtensionMethods
{
static public MyType<TDataAdd,MyType<TDataIn,TResultIn>> AddColumn<TDataIn,TResultIn,TDataAdd>(this MyType<TDataIn,TResultIn> This, TDataAdd columnValue)
{
return MyTypeFactory.Create(columnValue, This);
}
}
var grandparent = MyTypeFactory.Create( 12 )
.AddColumn( 13D )
.AddColumn( 14M )
.AddColumn( 15F );
var grandchildValue = grandparent.Child.Child.Child.Data;
Console.WriteLine(grandchildValue); //12
Console.WriteLine(grandchildValue.GetType().FullName); //System.Int32
See my code on DotNetFiddle
P.S. This is a great example of why we needed the var keyword! Otherwise you'd be typing forever. | |
d10888 | You are performing integer division with (10 / (ml + 1)) / 100, which in Java must result in another int. Your ml is 10, and in Java, 10 / 11 is 0, not 0.909..., and nothing is added to s.
Use a double literal or cast to double to force floating-point computations.
double s = (perfekt + (perfekt * (10.0 / (ml + 1)) / 100));
or
double s = (perfekt + (perfekt * ( (double) 10 / (ml + 1)) / 100));
Making either change makes the output:
4005.0
A: When you multiply a double by an int you get an int back.
public class Main
{
public static void main(String[] args)
throws Exception
{
double baseMaterial = 556;
int me = 5;
int ml = 10;
int extraMaterial = 3444;
System.out.println("" + calculateMiniralTotal(baseMaterial, me, ml, extraMaterial));
}
public static double calculateMiniralTotal(double perfekt, int me, int ml, int extraMaterial)
{
double s = (perfekt + (perfekt * (10.0 / (ml + 1)) / 100.0)); // <-- changed from 10 to 10.0 and 100 to 100.0. This way they are doubles too
s = Math.round(s);
double r = s + (perfekt * (0.25 - (0.05 * me)));
r = Math.round(r);
double q = extraMaterial + (extraMaterial * (0.25 - (0.05 * me)));
q = Math.round(q);
// double r=q;
r = r + q;
return Math.round(r);
}
} | |
d10889 | All Kendo widgets inherit from Observable, which has a trigger method:
var obj = new kendo.Observable();
obj.bind("myevent", function(e) {
console.log(e.data); // outputs "data"
});
obj.trigger("myevent", { data: "data" });
You need to manually trigger the Spreadheet's change event with its correct parameters. | |
d10890 | On the library page, if you are using the package https://github.com/thinkshout/mailchimp-api-php/releases which contains everything e.g. v1.0.6-package.zip (and therefore having everything already doesn't require composer to get them), then remove /vendor from .gitignore so that all the files in /vendor - including guzzle are included in your code base so that should you deploy the code from your repo to a production server, all of it will be loaded.
CREDIT: https://www.drupal.org/node/2709615#comment-11888769
A: This fixed the issue, Guzzle needed to be installed into the MailChimp libraries folder?! Guzzle Instructions
godaddy@user [~/public_html]$ cd sites/all/libraries/mailchimp/
godaddy@user [~/public_html/sites/all/libraries/mailchimp]$ curl -sS https://getcomposer.org/installer | php
All settings correct for using Composer
Downloading 1.1.1...
Composer successfully installed to: /home/mysite/public_html/sites/all/libraries/mailchimp/composer.phar
Use it: php composer.phar
godaddy@user [~/public_html/sites/all/libraries/mailchimp]$ ./composer.phar install
Loading composer repositories with package information
Updating dependencies (including require-dev)
- Installing sebastian/version (1.0.6)
Downloading: 100%
- Installing sebastian/global-state (1.1.1)
Downloading: 100%
- Installing sebastian/recursion-context (1.0.2)
Downloading: 100%
- Installing sebastian/exporter (1.2.1)
Downloading: 100%
- Installing sebastian/environment (1.3.7)
Downloading: 100%
- Installing sebastian/diff (1.4.1)
Downloading: 100%
- Installing sebastian/comparator (1.2.0)
Downloading: 100%
- Installing symfony/yaml (v3.0.6)
Downloading: 100%
- Installing doctrine/instantiator (1.0.5)
Downloading: 100%
- Installing phpdocumentor/reflection-docblock (2.0.4)
Downloading: 100%
- Installing phpspec/prophecy (v1.6.0)
Downloading: 100%
- Installing phpunit/php-text-template (1.2.1)
Downloading: 100%
- Installing phpunit/phpunit-mock-objects (2.3.8)
Downloading: 100%
- Installing phpunit/php-timer (1.0.8)
Downloading: 100%
- Installing phpunit/php-token-stream (1.4.8)
Downloading: 100%
- Installing phpunit/php-file-iterator (1.4.1)
Downloading: 100%
- Installing phpunit/php-code-coverage (2.2.4)
Downloading: 100%
- Installing phpunit/phpunit (4.8.21)
Downloading: 100%
- Installing guzzlehttp/promises (1.2.0)
Loading from cache
- Installing psr/http-message (1.0)
Loading from cache
- Installing guzzlehttp/psr7 (1.3.0)
Loading from cache
- Installing guzzlehttp/guzzle (6.2.0)
Loading from cache
sebastian/global-state suggests installing ext-uopz (*)
phpdocumentor/reflection-docblock suggests installing dflydev/markdown (~1.0)
phpdocumentor/reflection-docblock suggests installing erusev/parsedown (~1.0)
phpunit/php-code-coverage suggests installing ext-xdebug (>=2.2.1)
phpunit/phpunit suggests installing phpunit/php-invoker (~1.1)
Writing lock file
Generating autoload files | |
d10891 | Save the certificate (as .cer file) of your website in the main bundle. Then use this URLSessionDelegate method:
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard
challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let serverTrust = challenge.protectionSpace.serverTrust,
SecTrustEvaluate(serverTrust, nil) == errSecSuccess,
let serverCert = SecTrustGetCertificateAtIndex(serverTrust, 0) else {
reject(with: completionHandler)
return
}
let serverCertData = SecCertificateCopyData(serverCert) as Data
guard
let localCertPath = Bundle.main.path(forResource: "shop.rewe.de", ofType: "cer"),
let localCertData = NSData(contentsOfFile: localCertPath) as Data?,
localCertData == serverCertData else {
reject(with: completionHandler)
return
}
accept(with: serverTrust, completionHandler)
}
...
func reject(with completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void)) {
completionHandler(.cancelAuthenticationChallenge, nil)
}
func accept(with serverTrust: SecTrust, _ completionHandler: ((URLSession.AuthChallengeDisposition, URLCredential?) -> Void)) {
completionHandler(.useCredential, URLCredential(trust: serverTrust))
}
A: Just a heads up, SecTrustEvaluate is deprecated and should be replaced with SecTrustEvaluateWithError.
So this:
var secresult = SecTrustResultType.invalid
let status = SecTrustEvaluate(serverTrust, &secresult)
if errSecSuccess == status {
// Proceed with evaluation
switch result {
case .unspecified, .proceed: return true
default: return false
}
}
The reason i wrote the // Proceed with evaluation section is because you should validate the secresult as well as this could imply that the certificate is actually invalid. You have the option to override this and add any raised issues as exceptions, preferably after prompting the user for a decision.
Should be this:
if SecTrustEvaluateWithError(server, nil) {
// Certificate is valid, proceed.
}
The second param will capture any error, but if you are not interested in the specifics, you can just pass nil.
A: Swift 3+ Update:
Just define a delegate class for NSURLSessionDelegate and implement the didReceiveChallenge function (this code is adapted from the objective-c OWASP example):
class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
// Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if let serverTrust = challenge.protectionSpace.serverTrust {
let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)
if(isServerTrusted) {
if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
let serverCertificateData = SecCertificateCopyData(serverCertificate)
let data = CFDataGetBytePtr(serverCertificateData);
let size = CFDataGetLength(serverCertificateData);
let cert1 = NSData(bytes: data, length: size)
let file_der = Bundle.main.path(forResource: "certificateFile", ofType: "der")
if let file = file_der {
if let cert2 = NSData(contentsOfFile: file) {
if cert1.isEqual(to: cert2 as Data) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))
return
}
}
}
}
}
}
}
// Pinning failed
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
}
(you can find a Gist for Swift 2 here - from the initial answer)
Then create the .der file for your website using openssl
openssl s_client -connect my-https-website.com:443 -showcerts < /dev/null | openssl x509 -outform DER > my-https-website.der
and add it to the xcode project. Double check that it's present in the Build phases tab, inside the Copy Bundle Resources list. Otherwise drag and drop it inside this list.
Finally use it in your code to make URL requests:
if let url = NSURL(string: "https://my-https-website.com") {
let session = URLSession(
configuration: URLSessionConfiguration.ephemeral,
delegate: NSURLSessionPinningDelegate(),
delegateQueue: nil)
let task = session.dataTask(with: url as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print("error: \(error!.localizedDescription): \(error!)")
} else if data != nil {
if let str = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) {
print("Received data:\n\(str)")
} else {
print("Unable to convert data to text")
}
}
})
task.resume()
} else {
print("Unable to create NSURL")
}
A: Thanks to the example found in this site: https://www.bugsee.com/blog/ssl-certificate-pinning-in-mobile-applications/ I built a version that pins the public key and not the entire certificate (more convenient if you renew your certificate periodically).
Update: Removed the forced unwrapping and replaced SecTrustEvaluate.
import Foundation
import CommonCrypto
class SessionDelegate : NSObject, URLSessionDelegate {
private static let rsa2048Asn1Header:[UInt8] = [
0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00
];
private static let google_com_pubkey = ["4xVxzbEegwDBoyoGoJlKcwGM7hyquoFg4l+9um5oPOI="];
private static let google_com_full = ["KjLxfxajzmBH0fTH1/oujb6R5fqBiLxl0zrl2xyFT2E="];
func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let serverTrust = challenge.protectionSpace.serverTrust else {
completionHandler(.cancelAuthenticationChallenge, nil);
return;
}
// Set SSL policies for domain name check
let policies = NSMutableArray();
policies.add(SecPolicyCreateSSL(true, (challenge.protectionSpace.host as CFString)));
SecTrustSetPolicies(serverTrust, policies);
var isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil);
if(isServerTrusted && challenge.protectionSpace.host == "www.google.com") {
let certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
//Compare public key
if #available(iOS 10.0, *) {
let policy = SecPolicyCreateBasicX509();
let cfCertificates = [certificate] as CFArray;
var trust: SecTrust?
SecTrustCreateWithCertificates(cfCertificates, policy, &trust);
guard trust != nil, let pubKey = SecTrustCopyPublicKey(trust!) else {
completionHandler(.cancelAuthenticationChallenge, nil);
return;
}
var error:Unmanaged<CFError>?
if let pubKeyData = SecKeyCopyExternalRepresentation(pubKey, &error) {
var keyWithHeader = Data(bytes: SessionDelegate.rsa2048Asn1Header);
keyWithHeader.append(pubKeyData as Data);
let sha256Key = sha256(keyWithHeader);
if(!SessionDelegate.google_com_pubkey.contains(sha256Key)) {
isServerTrusted = false;
}
} else {
isServerTrusted = false;
}
} else { //Compare full certificate
let remoteCertificateData = SecCertificateCopyData(certificate!) as Data;
let sha256Data = sha256(remoteCertificateData);
if(!SessionDelegate.google_com_full.contains(sha256Data)) {
isServerTrusted = false;
}
}
}
if(isServerTrusted) {
let credential = URLCredential(trust: serverTrust);
completionHandler(.useCredential, credential);
} else {
completionHandler(.cancelAuthenticationChallenge, nil);
}
}
func sha256(_ data : Data) -> String {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
data.withUnsafeBytes {
_ = CC_SHA256($0, CC_LONG(data.count), &hash)
}
return Data(bytes: hash).base64EncodedString();
}
}
A: Here's an updated version for Swift 3
import Foundation
import Security
class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
// Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if let serverTrust = challenge.protectionSpace.serverTrust {
var secresult = SecTrustResultType.invalid
let status = SecTrustEvaluate(serverTrust, &secresult)
if(errSecSuccess == status) {
if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
let serverCertificateData = SecCertificateCopyData(serverCertificate)
let data = CFDataGetBytePtr(serverCertificateData);
let size = CFDataGetLength(serverCertificateData);
let cert1 = NSData(bytes: data, length: size)
let file_der = Bundle.main.path(forResource: "name-of-cert-file", ofType: "cer")
if let file = file_der {
if let cert2 = NSData(contentsOfFile: file) {
if cert1.isEqual(to: cert2 as Data) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust:serverTrust))
return
}
}
}
}
}
}
}
// Pinning failed
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
}
A: The openssl command in @lifeisfoo's answer will give an error in OS X for certain SSL certificates that use newer ciphers like ECDSA.
If you're getting the following error when you run the openssl command in @lifeisfoo's answer:
write:errno=54
unable to load certificate
1769:error:0906D06C:PEM routines:PEM_read_bio:no start
line:/BuildRoot/Library/Caches/com.apple.xbs/Sources/OpenSSL098/OpenSSL09
8-59.60.1/src/crypto/pem/pem_lib.c:648:Expecting: TRUSTED CERTIFICATE
You're website's SSL certificate probably is using an algorithm that isn't supported in OS X's default openssl version (v0.9.X, which does NOT support ECDSA, among others).
Here's the fix:
To get the proper .der file, you'll have to first brew install openssl, and then replace the openssl command from @lifeisfoo's answer with:
/usr/local/Cellar/openssl/1.0.2h_1/bin/openssl [rest of the above command]
Homebrew install command:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
hope that helps.
A: You can try this.
import Foundation
import Security
class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {
let certFileName = "name-of-cert-file"
let certFileType = "cer"
func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if let serverTrust = challenge.protectionSpace.serverTrust {
var secresult = SecTrustResultType.invalid
let status = SecTrustEvaluate(serverTrust, &secresult)
if(errSecSuccess == status) {
if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
let serverCertificateData = SecCertificateCopyData(serverCertificate)
let data = CFDataGetBytePtr(serverCertificateData);
let size = CFDataGetLength(serverCertificateData);
let certificateOne = NSData(bytes: data, length: size)
let filePath = Bundle.main.path(forResource: self.certFileName,
ofType: self.certFileType)
if let file = filePath {
if let certificateTwo = NSData(contentsOfFile: file) {
if certificateOne.isEqual(to: certificateTwo as Data) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential,
URLCredential(trust:serverTrust))
return
}
}
}
}
}
}
}
// Pinning failed
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
}
Source: https://www.steveclarkapps.com/using-certificate-pinning-xcode/ | |
d10892 | You should enable the presences intents for your bot from the developers portal like in the image below.
discord developer portal
https://i.stack.imgur.com/cAn8m.png
A: The accepted solution didn't work for me.
I needed to change:
on_member_update to on_presence_update according to the migration guide:
https://nextcord.readthedocs.io/en/latest/migrating_2.html
"on_presence_update() replaces on_member_update() for updates to Member.status and Member.activities." | |
d10893 | You can use the database schema, something like so
Function IX_UNIQUE(strTableName As String, strFieldName As String) as Boolean
Dim c As ADODB.Connection
Dim r As ADODB.Recordset
Set c = New ADODB.Connection
c.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & "C:\TESTsb.accdb" & ";" & _
"Persist Security Info=False;"
c.Open
Set r = New ADODB.Recordset
Set r = c.OpenSchema(adSchemaIndexes, Array(Empty, Empty, strFieldName , Empty, strTableName))
If Not r.EOF Then
IX_UNIQUE = r.Fields("UNIQUE").value
Else
IX_UNIQUE = False
End If
End Function | |
d10894 | You need to use the special variable $_
This small example shows how it works:
try {
testmenow
} catch {
Write-Host $_
}
$_ is an object so you can do
$_|gm
in the catch block in order to see the methods you can call. | |
d10895 | I'm assuming you've been able to login ok and then pass the details to the API and you're user/s are registered under the APP.
On validate, this is what i have and works fine.
async validate(data) {
return data;
}
This is the example i followed to get it working - https://medium.com/adidoescode/azure-ad-for-user-authentication-with-vue-and-nestjs-4dab3e96d240 | |
d10896 | Python 2 still has the base64 module built in.
Using
base64.standard_b64encode(s)
#and
base64.standard_b64decode(s)
#Where 's' is an encoded string
Should still work. | |
d10897 | Yes. You can use AJAX request to get the manifest cache file and then read it.
However, this does not guarantee that the browser in the question has the files available.
Below is an sample code
*
*Which checks if we have cached HTML5 app or not
*If we are not in a cached state then count loaded resources in the manifest and display a progress bar according to the manifest cache entry count (total) and do a manual AJAX GET request for all URLs to warm up the cache. The browser will do this itself, but this way we can get some progress information out of the process.
*When cache is in a known good state, move forward
Disclaimer: not tested to work since 2010
/**
* HTML5 offline manifest preloader.
*
* Load all manifest cached entries, so that they are immediately available during the web app execution.
* Display some nice JQuery progress while loading.
*
* @copyright 2010 mFabrik Research Oy
*
* @author Mikko Ohtamaa, http://opensourcehacker.com
*/
/**
* Preloader class constructor.
*
* Manifest is retrieved via HTTP GET and parsed.
* All cache entries are loaded using HTTP GET.
*
* Local storage attribute "preloaded" is used to check whether loading needs to be performed,
* as it is quite taxing operation.
*
* To debug this code and force retrieving of all manifest URLs, add reloaded=true HTTP GET query parameter:
*
*
*
* @param {Function} endCallback will be called when all offline entries are loaded
*
* @param {Object} progressMonitor ProgressMonitor object for which the status of the loading is reported.
*/
function Preloader(endCallback, progressMonitor, debug) {
if(!progressMonitor) {
throw "progressMonitor must be defined";
}
this.endCallback = endCallback;
this.progressMonitor = progressMonitor;
this.logging = debug; // Flag to control console.log() output
}
Preloader.prototype = {
/**
* Load HTML5 manifest and parse its data
*
* @param data: String, manifest file data
* @return Array of cache entries
*
* @throw: Exception if parsing fails
*/
parseManifest : function(data) {
/* Declare some helper string functions
*
* http://rickyrosario.com/blog/javascript-startswith-and-endswith-implementation-for-strings/
*
*/
function startswith(str, prefix) {
return str.indexOf(prefix) === 0;
}
var entries = [];
var sections = ["NETWORK", "CACHE", "FALLBACK"];
var currentSection = "CACHE";
var lines = data.split(/\r\n|\r|\n/);
var i;
if(lines.length <= 1) {
throw "Manifest does not contain text lines";
}
var firstLine = lines[0];
if(!(startswith(firstLine, "CACHE MANIFEST"))) {
throw "Invalid cache manifest header:" + firstLine;
}
for(i=1; i<lines.length; i++) {
var line = lines[i];
this.debug("Parsing line:" + line);
// If whitespace trimmed line is empty, skip it
line = jQuery.trim(line);
if(line == "") {
continue;
}
if(line[0] == "#") {
// skip comment;
continue;
}
// Test for a new section
var s = 0;
var sectionDetected = false;
for(s=0; s<sections.length; s++) {
var section = sections[s];
if(startswith(line, section + ":")) {
currentSection = section;
sectionDetected = true;
}
}
if(sectionDetected) {
continue;
}
// Otherwise assume we can check for cached url
if(currentSection == "CACHE") {
entries.push(line);
}
}
return entries;
},
/**
* Manifest is given as an <html> attribute.
*/
extractManifestURL : function() {
var url = $("html").attr("manifest");
if(url === null) {
alert("Preloader cannot find manifest URL from <html> tag");
return null;
}
return url;
},
isPreloaded : function() {
// May be null or false
return localStorage.getItem("preloaded") == true;
},
setPreloaded : function(status) {
localStorage.setItem("preloaded", status);
},
/**
* Check whether we need to purge offline cache.
*
*/
isForcedReload : function() {
// http://www.netlobo.com/url_query_string_javascript.html
function getQueryParam(name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if (results == null) {
return "";
} else {
return results[1];
}
}
if(getQueryParam("reload") == "true") {
return true;
}
return false;
},
/**
* Do everything necessary to set-up offline application
*/
load : function() {
this.debug("Entering preloader");
if (window.applicationCache) {
this.debug("ApplicationCache status " + window.applicationCache.status);
this.debug("Please see http://www.w3.org/TR/html5/offline.html#applicationcache");
} else {
this.silentError("The browser does not support HTML5 applicationCache object");
return;
}
var cold;
if(this.isPreloaded()) {
// We have succesfully completed preloading before
// ...move forward
forceReload = this.isForcedReload();
if (forceReload == true) {
applicationCache.update();
} else {
this.endCallback();
return;
}
cold = false;
} else {
cold = true;
}
var url = this.extractManifestURL();
if(url === null) {
return;
}
this.progressMonitor.startProgress(cold);
$.get(url, {}, jQuery.proxy(manifestLoadedCallback, this));
function manifestLoadedCallback(data, textStatus, xhr) {
this.debug("Manifest retrieved");
var text = data;
manifestEntries = this.parseManifest(text);
this.debug("Parsed manifest entries:" + manifestEntries.length);
this.populateCache(manifestEntries);
}
},
/**
* Bootstrap async loading of cache entries.
*
* @param {Object} entrires
*/
populateCache : function(entries) {
this.manifestEntries = entries;
this.currentEntry = 0;
this.maxEntry = entries.length;
this.loadNextEntry();
},
/**
* Make AJAX request to next entry and update progress bar.
*
*/
loadNextEntry : function() {
if(this.currentEntry >= this.maxEntry) {
this.setPreloaded(true);
this.progressMonitor.endProgress();
this.endCallback();
}
var entryURL = this.manifestEntries[this.currentEntry];
this.debug("Loading entry: " + entryURL);
function done() {
this.currentEntry++;
this.progressMonitor.updateProgress(this.currentEntry, this.maxEntries);
this.loadNextEntry();
}
this.debug("Preloader fetching:" + entryURL + " (" + this.currentEntry + " / " + this.maxEntry + ")");
$.get(entryURL, {}, jQuery.proxy(done, this));
},
/**
* Write to debug console
*
* @param {String} msg
*/
debug : function(msg) {
if(this.logging) {
console.log(msg);
}
},
/**
* Non-end user visible error message
*
* @param {Object} msg
*/
silentError : function(msg) {
console.log(msg);
}
};
function ProgressMonitor() {
}
ProgressMonitor.prototype = {
/**
* Start progress bar... initialize as 0 / 0
*/
startProgress : function(coldVirgin) {
$("#web-app-loading-progress-monitor").show();
if(coldVirgin) {
$("#web-app-loading-progress-monitor .first-time").show();
}
},
endProgress : function() {
},
updateProgress : function(currentEntry, maxEntries) {
}
};
A: I have also been working on a solution for discovering which file is being cached, and have come up with the following.
.htaccess wrapper for the directory we are grabbing files to appcache.
#.htaccess
<FilesMatch "\.(mp4|mpg|MPG|m4a|wav|WAV|jpg|JPG|bmp|BMP|png|PNG|gif|GIF)$">
SetHandler autho
</FilesMatch>
Action autho /www/restricted_access/auth.php
then my auth.php file returns the file (in chunks) to the browser, but also logs at the same time to the server (I use a DB table) with an earlier declared APPID.
That way while the 'progress' event is detected, an AJAX call can be made to retrieve the last entry for APPID, which contains the file name and how much data has been sent.
The advantage of using this method is that its transparent to other methods accessing the files in the '.htaccess wrapped' folder, and in my case also includes authentication.
When not authorized to access a file for whatever reason I return 'Not Authorized' headers. | |
d10898 | As far I know query builders (like your second example using Query.EQ) belong to old versions of C# drivers (1.X) (see Query class). Also I suggest you to see Builder section in this link that confirm query builders is the old way to consult data.
After the release of the 2.0 version of the .NET driver, a lot of changes were made, including the way of consult the data (you can read more about that in this link). If you are using the last C# driver version you should use your first approach.
A: The first way you mentioned is quite fine. You might want to incorporate using a mongo cursor as well to allow you to iterate through results
var collection = _database.GetCollection<BsonDocument>("restaurants");
var filter = Builders<BsonDocument>.Filter.Eq("address.zipcode", "10075");
using(var _cursor = await collection.Find(filter).ToCursorAsync())
{
while(await _cursor.MoveNextAsync())
{
foreach(var _document in _cursor.Current) //gets current document
{
//you can do things like get the _id of the document
var _id = _document["_id"];
}
}
} | |
d10899 | Well how would you list the server side files if you have no access to server side ?
"I am not allowed to use platforms which require server side installation."
There are some workarounds for this problem, but these usually needs some extra enabled flags from the user side. http://www.chrome-allow-file-access-from-file.com/
A:
I am not allowed to use platforms which require server side installation.
You need some server side handler for this request. But may be you already have something. For example mod_autoindex for apache.. | |
d10900 | The problem looks your image was covered by other element, if you want to show element in the Canvas, you need to set ZIndex for element.
Canvas.ZIndex declares the draw order for the child elements of a Canvas. This matters when there is overlap between any of the bounds of the child elements. A higher z-order value will draw on top of a lower z-order value. If no value is set, the default is -1.
If you want to set image as background, you could set it's ZIndex with samll value. And other way is set Canvas Background with ImageBrush directly like the fllowing.
MyCanvas.Background = new ImageBrush { ImageSource = new BitmapImage(new Uri(this.BaseUri, "ms-appx:///Assets/enemy.png")), Stretch = Stretch.Fill }; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.