text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Media Kind in iTunes COM for Windows SDK
I recently found out about the awesomeness of the iTunes COM for Windows SDK. I am using Python with win32com to talk to my iTunes library. Needless to say, my head is in the process of exploding. This API rocks.
I have one issue though, how do I access the Media Kind attribute of the track? I looked through the help file provided in the SDK and saw no sign of it. If you go into iTunes, you can modify the track's media kind. This way if you have an audiobook that is showing up in your music library, you can set the Media Kind to Audiobook and it will appear in the Books section in iTunes. Pretty nifty.
The reason I ask is because I have a whole crap load of audiobooks that are showing up in my LibraryPlaylist.
Here is my code thus far.
import win32com.client
iTunes = win32com.client.gencache.EnsureDispatch('iTunes.Application')
track = win32com.client.CastTo(iTunes.LibraryPlaylist.Tracks.Item(1), 'IITFileOrCDTrack')
print track.Artist, '-', track.Name
print
print 'Is this track an audiobook?'
print 'How the hell should I know?'
Thanks in advance.
A:
One reason why you may not be able to find it is that the atom structure the com object references may be out of date. The most popular list of atoms from the MP4 structure is here: http://atomicparsley.sourceforge.net/mpeg-4files.html I don't see a media kind atom. I suppose you could try to parse the structure through atomicparsley but to my knowledge it only finds atoms that it knows about.
Short Answer: The COM object may not know about the MediaKind Attribute.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to avoid the inconsistency of data while inserting into table
A is a table
a1 is a primery key in A
a2 is another field in A
I have created a java web based application and deployed in wildfly server. The field a1 is a readonly field to the enduser
and it will show the maximum count of the rows in table A and a2 is an editable field. Now consider two end users are acessing
this application at same time and trying to insert data into the table A. Both these users will see the same value for field a1
and give different values in the field a2. Now both the users submit the application and will insert data into A. This will
result in inserting two rows with the same value for the field a1. But the field a1 is a primary key. So it should have distinct values.
How can I prevent this while inserting data in table A? Here do we need to apply threading concept?
A:
Use ID generator. There are different types possible, e.g. based on database sequence like in Oracle, based on auto increment in MySQL.
Here are some good examples:
https://docs.jboss.org/hibernate/orm/5.0/mappingGuide/en-US/html/ch06.html
Difference between @GeneratedValue and @GenericGenerator
How to annotate MYSQL autoincrement field with JPA annotations
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I add a certain amount of attempts to my code after asking a question?
I have a code to pick a random song with the artist but only the first letters are shown and the user has to guess the song name by the given artist, I need to add 2 attempts where if they get it wrong I end the code but if they get it right they move on to the next question.
f1 = open("Eminem.txt", "r") #Opens external notepad file and the read mode ("r")
f2 = open("UnlikePluto.txt", "r") #Opens external notepad file and the read mode ("r")
f3 = open("Marshmello.txt", "r") #Opens external notepad file and the read mode ("r")
f4 = open("Eminem1.txt", "r") #Opens external notepad file and the read mode ("r")
f5 = open("UnlikePluto1.txt", "r") #Opens external notepad file and the read mode ("r")
f6 = open("Marshmello1.txt", "r") #Opens external notepad file and the read mode ("r")
f7 = open("Eminem2.txt", "r") #Opens external notepad file and the read mode ("r")
f8 = open("UnlikePluto2.txt", "r") #Opens external notepad file and the read mode ("r")
f9 = open("Marshmello2.txt", "r") #Opens external notepad file and the read mode ("r")
I have got the artist names, song names and actual question saved in an external file but I dont know how to code the question with 2 attempts to guess the song. Thanks :D
A:
you can use a variable to count the number of tries. and add it to a while loop. something like this:
count = 0
while count<2:
answer = input('enter the song name: ')
if answer == solution:
<move on to next question>
else:
count +=1
|
{
"pile_set_name": "StackExchange"
}
|
Q:
System.QueryException: expecting a colon, found 'setids'
I keep getting the error:
System.QueryException: expecting a colon, found 'setids'
Why do I get this error? How can I fix it?
public Database.QueryLocator start(Database.BatchableContext context) {
Set<Id> setids = new Set<Id>();
for(Task t : [SELECT WhatId FROM Task WHERE Is_Precall__c = true AND Is_Created_By_Batch__c = true AND CreatedDate = TODAY]){
setids.add(t.WhatId);
}
String q = 'SELECT Id, Route_Lookup__c, Next_Delivery_Date__c,';
q += ' Market_Center_Lookup__c,';
q += ' (SELECT Id FROM Orders__r WHERE Status = \'Pending\')';
q += ' FROM ServicePoint__c WHERE Type__c = \'Active\'';
q += ' AND Is_Batch_Exec_Date__c = true';
q += ' AND Is_Precall_Customer__c = true';
q += ' AND Id NOT IN setids' ;
return Database.getQueryLocator(q);
}
A:
When you reference an apex variable in a query (standard, or dynamic as is your case), you need to prefix the variable name with a colon :. This is called expression binding. You can still use expression binding in dynamic soql. Though there are some additional considerations when using this with dynamic soql, I don't believe any of them apply in this particular case.
The line in question here is
q += ' AND Id NOT IN setids' ;
and the correct way to do this would be
// Notice the colon (:) added before setids
q += ' AND Id NOT IN :setids';
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Place an image on a image when a thumbnail is clicked
I have a code like
<a href='javascript:showImage()'><img src='/public/visit_images/img1.jpg' width=100 height=100></img></a>
<div class='orig_image' style="position:absolute; width:200px; height:181px; border:1px solid gray; margin-right: 1em; margin-bottom: 10px;display:none;">
<div style="width:200px; height:181px; background: url(/public/shift-images/indicator.gif) 50% 50% no-repeat;">
<img id="caribbean" class="shiftzoom" onLoad="shiftzoom.add(this,{showcoords:true,relativecoords:true});" src="/public/visit_images/img1.jpg" width="200" height="181" alt="large image" border="0" />
</div>
</div>
First I display the thumbnail image. When a user clicks on the thumbnail, I want the class orig_image, which is the original image, to appear over the thumb nail image. How do I do this?
A:
add z-index in your style:
<div class='orig_image' style="position:absolute; width:200px; height:181px; border:1px solid gray; margin-right: 1em; margin-bottom: 10px;display:none;z-index:999;">
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Override User afterLogin Method
How to override afterLogin method in yii2?
Where Should I write?
protected function afterLogin($identity, $cookieBased, $duration)
{
}
I'm New to yii2. Please Guide me.
A:
You need to implement the afterLogin method in your User ActiveRecord class.
So assuming you have set up your projects you'll find the User class in your models folder.
So just add the afterLogin method to that class to do whatever post-login processing you need to.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
what is the difference between ScrollView, ListView, RecyclerView and WebView?
I want to know when to use ScrollView or ListView or RecyclerView and also Can we use WebView for building an app?
A:
SCROLLVIEW
ScrollView is used to put different or same child views or layouts and the all can be scrolled.
Listview
ListView is used to put same child view or layout as multiple items. All these items are also scrollable.
Simply ScrollView is for both homogeneous and heterogeneous collection. ListView is for only homogeneous collection.
What is RecyclerView?
The RecyclerView widget is a more advanced and flexible version of ListView.
Why RecyclerView?
RecyclerView is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views.
When you should use RecyclerView?
You can use the RecyclerView widget when you have data collections whose elements
changes at runtime based on user action or network events.
WEBVIEW
WebView in Android turns the application into a web application. It comes from
android.webkit.WebView. Here, the WebView class is an extension of Android's View
class which is used to show the web pages. WebView doesn't include all the features
of Web-browser-like navigation controls or an address bar etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Lookup value in one dataframe and paste it into another dataframe
I have two dataframes in Python one big (car listings), one small (car base configuration prices). The small one looks like this:
Make Model MSRP
0 Acura ILX 27990
1 Acura MDX 43015
2 Acura MDX Sport Hybrid 51960
3 Acura NSX 156000
4 Acura RDX 35670
5 Acura RLX 54450
6 Acura TLX 31695
7 Alfa Romeo 4C 55900
8 Alfa Romeo Giulia 37995
… … … . …
391 Toyota Yaris 14895
392 Toyota Yaris iA 15950
393 Volkswagen Atlas 33500
394 Volkswagen Beetle 19795
395 Volkswagen CC 34475
396 Volkswagen GTI 24995
397 Volkswagen Golf 19575
398 Volkswagen Golf Alltrack 25850
399 Volkswagen Golf R 37895
400 Volkswagen Golf SportWagen 21580
401 Volkswagen Jetta 17680
402 Volkswagen Passat 22440
403 Volkswagen Tiguan 24890
404 Volkswagen Touareg 42705
405 Volkswagen e-Golf 28995
406 Volvo S60 33950
Now I want to paste the values from the MSRP column (far right column) based on matching the Make and Model columns into the big dataframe (car listings) that looks like the following:
makeName modelName trimName carYear mileage
0 BMW X5 sDrive35i 2017 0
1 BMW X5 sDrive35i 2017 3
2 BMW X5 sDrive35i 2017 0
3 Audi A4 Premium Plus2017 0
4 Kia Optima LX 2016 10
5 Kia Optima SX Turbo 2017 15
6 Kia Optima EX 2016 425
7 Rolls-Royce Ghost Series II 2017 15
… … … … … …
In the end I would like to have the following:
makeName modelName trimName carYear mileage MSRP
0 BMW X5 sDrive35i 2017 0 value from the other table
1 BMW X5 sDrive35i 2017 3 value from the other table
2 BMW X5 sDrive35i 2017 0 value from the other table
3 Audi A4 Premium Plus2017 0 value from the other table
4 Kia Optima LX 2016 10 value from the other table
5 Kia Optima SX Turbo 2017 15 value from the other table
6 Kia Optima EX 2016 425 value from the other table
7 Rolls-Royce Ghost Series II 2017 15 value from the other table
… … … … … …
I read the documentation regarding pd.concat, merge and join but I am not making any progress.
Can you guys help?
Thanks!
A:
You can use merge to join the two dataframes together.
car_base.merge(car_listings, left_on=['makeName','modelName'], right_on=['Make','Model'])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Vagrant: passing parameters in windows
I already found this question about how to pass parameters to the Vagrantfile environment, but it seems that it doesn't work on windows. In fact if I try to run:
SERV=client vagrant up
With this Vagrantfile:
# -*- mode: ruby -*-
# # vi: set ft=ruby :
# Specify minimum Vagrant version and Vagrant API version
Vagrant.require_version ">= 1.6.0"
VAGRANTFILE_API_VERSION = "2"
# Require YAML module
require 'yaml'
# Read YAML file with box details
servers = YAML.load_file('RaftFS/servers.yaml')
# Create boxes
Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
# Create servers
# Iterate through entries in YAML file
if ENV['SERV'] != "client"
servers.each do |key,value|
if key == ENV['SERV']
config.vm.define key do |srv|
srv.vm.box = value['box']
#srv.vm.network "private_network", ip: value['ip']
if value['ip'] != ''
srv.vm.provision "shell", inline: "echo NO IP ADDRESS"
srv.vm.network :public_network, bridge:'wlan0'
else
srv.vm.network :public_network, ip:value['ip'] ,bridge:'wlan0'
srv.vm.provision "shell", inline: "echo IP FOUND FOR"
end
srv.vm.hostname=key
srv.vm.synced_folder ".", "/vagrant" , disabled:true
srv.vm.synced_folder "ServersFS/"+key+"/", "/vagrant/ServersFS" , create: true
srv.vm.synced_folder "./RaftFS", "/vagrant/RaftFS"
srv.vm.provision :shell do |shell|
shell.path = "provision.sh"
shell.args = "'TRUE'"
end
srv.vm.provider :virtualbox do |vb|
vb.name = key
vb.memory = value['ram']
end
end
end
end
else
config.vm.define "client" do |cln|
cln.vm.box = "hashicorp/precise32"
cln.vm.network :public_network, bridge:'wlan0', ip:"192.168.1.140"
cln.vm.hostname="client"
cln.vm.provision :shell do |shell|
shell.path = "provision.sh"
shell.args = "'FALSE'"
end
end
end
end
Windows prompt doesn't recognize SERV=client as valid command. I'm sorry for the question, but I'm totally new with both Vagrant and Ruby (and I usually program on Linux)!
A:
So I stumbled on this issue as well. To pass parameters from command prompt to Vagrantfile it should pass as an environment variable, and you can do it in one line:
set "SERV=client" && vagrant up
In the Vagrantfile, you then can access the parameter as ENV['SERV']
A heads-up is that the environment variable will still exist in the environment after vagrant has finished.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Linq 2 SQL Sum using lambda and handling nulls
When using sum with lambda in Linq to SQL using the following code:
int query = (from f in odc.RDetails
where f.ticketID == int.Parse(ticket.ToString())
select f).Sum(x => x.Rate);
I get the following error:
The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value type.
A:
. You have to make sure x.Rate is an int, and not an int? (an int that accepts null as a value).
. If the query has no elements, .Sum won't do anything and will return null. Choose a default value, let's say 0.
var query = from f in odc.RDetails
where f.ticketID == int.Parse(ticket.ToString())
select f;
int result = query.Any()
? query.Sum(x => x.Rate ?? 0) // use the ?? if x.Rate is an "int?".
: 0; // default value you can choose.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
GCE Windows Instance not running startup scripts
I have been trying to apply my startup scripts to new Windows instances on Google Compute Engine as described here, however when I check the instances there is no trace of them ever being executed. Here is the gcloud command I am running:
gcloud compute instances create "my-instance"
--project "my-project"
--zone "us-central1-a"
--machine-type "g1-small"
--network "default"
--metadata "gce-initial-windows-user=my-user" "gce-initial-windows-password=my-pass"
--maintenance-policy "MIGRATE"
--scopes "storage-ro"
--tags "http-server" "https-server"
--image "https://www.googleapis.com/compute/v1/projects/windows-cloud/global/images/windows-server-2008-r2-dc-v20150110"
--boot-disk-type "pd-standard"
--boot-disk-device-name "my-instance"
--metadata-from-file sysprep-oobe-script-ps1=D:\Path\To\startup.ps1
I tried using all 3 startup types (sysprep-specialize-script-ps1, sysprep-oobe-script-ps1, windows-startup-script-ps1) but none worked. Can't see any indication in the Task Scheduler or Event Viewer either. The file on my system exists and does work when I run it manually. How can I get this working?
A:
A good way to debug Powershell scripts is to have them write to the serial console (COM1). You'll be able to see the output of the script from GCE's serial port output.
gcloud compute instances get-serial-port-output my-instance --zone
us-central1-a
If there's no script you'll see something like:
Calling oobe-script from metadata.
attributes/sysprep-oobe-script-bat value is not set or metadata server is not reachable.
attributes/sysprep-oobe-script-cmd value is not set or metadata server is not reachable.
attributes/sysprep-oobe-script-ps1 value is not set or metadata server is not reachable.
Running schtasks with arguments /run /tn GCEStartup
--> SUCCESS: Attempted to run the scheduled task "GCEStartup".
-------------------------------------------------------------
Instance setup finished. windows is ready to use.
-------------------------------------------------------------
Booting on date 01/25/2015 06:26:26
attributes/windows-startup-script-bat value is not set or metadata server is not reachable.
attributes/windows-startup-script-cmd value is not set or metadata server is not reachable.
attributes/windows-startup-script-ps1 value is not set or metadata server is not reachable.
Make sure that contents of the ps1 file is actually attached to the instance.
gcloud compute instances describe my-instance --zone us-central1-a
--format json
The JSON dump should contain the powershell script within it.
Lastly, a great way to debug Powershell startup scripts is to write the output to the serial console.
You can print log messages and see them in the Google Developer Console > Compute > Compute Engine > VM Instances > (Instance Name). Then scroll to the bottom and click the expand option for "Serial console".
Function Write-SerialPort ([string] $message) {
$port = new-Object System.IO.Ports.SerialPort COM1,9600,None,8,one
$port.open()
$port.WriteLine($message)
$port.Close()
}
Write-SerialPort ("Testing GCE Startup Script")
This command worked for me, I had to make sure that the script was written in ascii. Powershell ISE writes with a different encoding that breaks gcloud compute.
gcloud compute instances create testwin2 --zone us-central1-a
--metadata-from-file sysprep-oobe-script-ps1=testconsole.ps1 --image windows-2008-r2
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python create new column and store data in .CSV file
I have stacked in my Python script where I try to open .txt files, make list of words from that file, count how many times word appear (Counter) and put it in .csv file. My files got names from 1870.txt - 1892 (1871,1872,1873..1892.txt). Everything from there works, but I want for each file to put in next column.
def putInExcel(outputt):
i = 1790
while i < 1892:
inputt = str(i) + '.txt' #Making text file name
writefile = open(outputt)
writer = csv.writer(writefile)
with open(inputt) as file: #Separating each word and storing in list
text = file.read().lower()
text = re.sub('[^a-z\ \']+', " ", text)
words = list(text.split())
for word in words:
cnt[word] += 1
for key, count in cnt.iteritems(): #De-dent this block
writer.writerow([key,count]) #Output both the key and the count
writefile.close()
i = i+1
This script is working but it stores all in one column.
Does anybody have some idea? Thank you!
A:
If I understand you correctly, you want a single table that contains columns for each year/filename. In each column, you want a numeric frequency count. The leftmost column would be the words themselves:
____ | 1790 | 1791 | 1792 | ...
Aachen 1 1 2
aardvark 1 0 0
aardwolf 0 1 0
abacus 1 2 2
acrimony 2 2 2
:
You have a fairly simple script now, that doesn't have to worry about interactions between different data sets. When you try to deal with more than one input list, you will have to "unify" them somehow. That's why I show some entries with 0 in the example.
My suggestion would be to maintain a master set or dictionary of all the words seen. This will be the leftmost column when you are done.
For each year/input file, you can keep separate counts. You can organize them as two parallel lists: the year/filename, and the dictionary of counts:
All_words = set()
Headers = [] # 1791, 1792, ...
Word_counts = [] # {'a':1, 'baa':2}, {'a':1, 'abacus': 1}, ...
Now when you loop over the files, add the filename and an empty dictionary to the headers/counts lists:
for ... 1791 ...
Headers.append(year)
cnt = dict()
Word_counts.append(cnt)
Count your words as you do now. But when you count a word, also add it to the set of all words:
cnt[word] += 1
All_words.add(word)
Finally, when you are done, you will have to process the words in the same order. So sort the contents of All_words and use that:
row = ['Word\Year']
row.extend(Headers)
csvfile.writerow(...)
for word in sorted(All_words):
row = [word] # Left column is word
row.extend([yr.get(word, 0) for yr in Word_counts])
csvfile.writerow(...)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to show a map which is a big image?
I got a png image which is 5000x5000. This image is some sort of map. I wanted to display the image in an imageview and this gave me an outOfMemoryException(of course). So i tried to set a sampleSize, but this decreased the resolution which makes the map not very usefull.
So basically I want to show this image and be able to zoom and scroll without resolution loses. What would be the best approach?
A:
I am a fan of Dave Morrissey's SubsamplingScaleImageView, which seems to cover what you want. Quoting the project documentation, it is:
A custom image view for Android, designed for photo galleries and displaying huge images (e.g. maps and building plans) without OutOfMemoryErrors. Includes pinch to zoom, panning, rotation and animation support, and allows easy extension so you can add your own overlays and touch event detection.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Possible to reverse a permanent redirect in Azure?
I have an azure web site that I don't update anymore.
So I edited the web.config and added a rule to redirect to a new URL.
I made a type when typing the new URL and set the redirect mode to permanent.
No matter what I do, now I can not correct it because it seems it's permanently stuck this way.
The old URL now tries to redirect to some random incorrect typo location.
Is there a way to reverse this?
A:
This sounds like it may be a local issue. Your browser may have cached the 302 response. Have you tried using a different browser, or clearing your browser's cache?
Otherwise, have you restarted the web site through the Azure portal?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Webpage table updated by uploading file
I am looking to create a web page displaying football league table which can be updated by uploading a file, such as XML (preferred).
If I was to create this in java, what data store should I use for the league?
A:
You could just make a MySQL database, write your web-page using JSP/JSTL and write something to update the database by reading the XML sheet.
Some Alternatives:
You could always just use a hierarchical file scheme with each folder representing a table in the database, each file in that folder representing a column in the table.
You could store it directly in XML:
<xml>
<tableName>
<columnName>
<data1/>
<data2/>
</columnName>
<columnName2>
</columnName2>
</tableName>
</xml>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can a satellite go over the same area in different passes overtime
Can a sun-synchronous satellite (let's consider Sentinel-1) go over the same place, one time in an ascending pass and the next time (or few times after) in a descending pass?
A:
It seems to me that many satellites are programmed to go over a certain area at the same time and in the same pass.
This increase coherence between each pass's images, which facilitate operations such as change detection on the image series generated from the set of images collected from the different passes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Calculation of Power Dissipation of Memory ICs and Microcontrollers
Can someone tell me how to calculate the power dissipation of digital ICs like Nand Flash, QSPI NOR Flash and Microcontrollers?
For Microcontrollers, we can get the power dissipation for GPIO like, Vdd (Voltage domain) * Id (drive current).
But what to do in case of the SPI interface from Micro to NOR Flash IC and other memory ICs like NAND Flash and eMMC
A:
This is always something of an estimate and I am usually interested in average power.
For a memory device you need to know:
1 The amount of time you will be writing to the device as a fraction of total time (if at all but remember that you must consider the minimum time the device will be writing on each occasion).
2 The amount of time you will be reading from the device as a fraction of total time.
(The interface speed may matter for capacitive power dissipation).
Here I am assuming a single power rail (fairly typical for most memory devices).
Find the write current from the datasheet and multiply it by the device voltage and then multiply by the fraction of total time you are writing. If you are writing for 5% of the time, the write current is 20mA and the voltage is 3.3V, then you have an average write power of 3.3mW. (The peak power here is 66mW)
If you are reading for 70% of the time, find the read current and multiply it by the device voltage and then by the fraction of time you are reading; for a read current of 15mA and a device voltage of 3.3V, then the average read power is 34.65mW.
Now just add the two together for total average active power (37.95mW in this case). Now add this to the standby power multiplied by the time the device is inactive as a fraction (1 - write time - read time) and you have the answer (as an estimate - I usually add 10% to this as a margin).
This does not take into account a long sequence of writes which may cause localised self heating for a short period of time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Numpy inconsistent slicing for 3d array
When I try to slice a Numpy array (3d), something unexpected occurs.
import numpy as np
x=np.array(
[ [[1., 2., 3., 4., 5.],
[6., 7., 8., 9., 0.],
[1., 2., 3., 4., 5.],
[6., 7., 8., 9., 0.]],
[ [11., 12., 13., 14., 15.],
[16., 17., 18., 19., 10.],
[11., 12., 13., 14., 15.],
[16., 17., 18., 19., 10.]],
[ [21., 22., 23., 24., 25.],
[26., 27., 28., 29., 20.],
[21., 22., 23., 24., 25.],
[26., 27., 28., 29., 20.]]]
)
print(x.shape) #(3,4,5)
print(x[:,0,[0,1,2,3,4]].shape) #(3,5) as expected
print(x[0,:,[0,1,2,3,4]].shape) #(5,4) why not (4,5)?
The latest one swap the dimension unexpectedly. Why?
A:
You are using a combination of two array indexing methods. The method that is commonly used in Python is the so called Basic Indexing, where you use slices m:n, and ellipsis ... to define a slice of an array. The other method is called Advanced Indexing where you use a tuple or a list to specify the selection. The difference between the two methods is that the Advanced indexing method generates a copy of the data, while the Basic indexing does not.
When combining basic and advanced indexing the memory layout of the array may change.
In your first example the dimensions that are treated as advanced indices are next to each other, so the shape is preserved.
In your second example the dimensions that are treated as advanced indices are interspersed with a dimension with basic indexing. So the advanced indexed dimensions come first in the result array.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Relational algebra and indexes
How might indexes be represented in the context of relational algebra?
How would an optimizer transform a query to use indexes?
A:
Indices must not appear in relational algebra. That is because relational algebra is just a formal language which describes what you must do, but not how you must do it.
It is comparable to the multiplication and other operations of the elementary arithmetic.
There is a definition of what multiplying is but not of the way how you have to do it. There are several algorithms to multiply two numbers but the results are all equal. For further information see Wikipedia (What does it mean to multiply two natural numbers?).
Relating to your question that means that the result of an operation is the same with or without indices. The only difference is the increasing performance if you use indices.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Parsing through results in Wordpress Sql Query
I am fairly new and I am struggling with a simple Wordpress SQL query on the standard database for a plugin I am developing.
I am using the following code to echo out the titles of the first 10 posts:
global $wpdb;
$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->posts LIMIT 0, 10;"));
$i = 0;
while($i < count($results)){
echo $results->post_title;
$i++;
}
But nothing is getting echo'd out to the screen. There are a more that 10 posts in the database so not having data is not the issue.
A:
I believe instead of this:
$i = 0;
while($i < count($results)){
echo $results->post_title;
$i++;
}
(Which will always echo the same variable), what you need to do is this:
foreach ($results as $result) {
echo $result->post_title;
}
Because $results is an array.
You might be able to do this as well, but there's no benefit over foreach:
$i = 0;
while($i < count($results)){
echo $results[$i]->post_title;
$i++;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can't get Eloquent's hasManyThrough to work for a basic example
Here are my relationships:
User
id
Collection
id
UserCollection
user_id
collection_id
How can I get something like $user->collections to return all Collection objects that belongs to the user? A UserCollection simply links a User to a Collection. This allows a user to have multiple collections, but also allows a collection to belong to multiple users.
What I'm currently trying is to specify that UserCollection belongs to a User on user_id, and belongs to a Collection on collection_id.
// UserCollection
public function user()
{
return $this->belongsTo(User::class, 'user_id');
}
public function collection()
{
return $this->belongsTo(Collection::class, 'collection_id');
}
Then specifying that a User has many Collections through UserCollection.
// User
public function collections()
{
return $this->hasManyThrough(Collection::class, UserCollection::class);
}
I've also tried explicitly setting the column names of the hasManyThrough relationship, but the join tries to use an id column on the UserCollection model, which does not exist as there is no primary key:
public function collections()
{
return $this->hasManyThrough(Collection::class, UserCollection::class, 'user_id', 'collection_id');
}
A:
You're overcomplicating things here. You don't need hasManyThrough. What you need is belongsToMany() for a many-to-many relationship.
First, get rid of your UserCollection model. You don't need it.
Then change your relations to this:
public function collections(){
return $this->belongsToMany('Collection', 'user_collections');
}
public function users(){
return $this->belongsToMany('User', 'user_collections');
}
For more information take a look at the official docs on relations
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Создание очереди в с++
Помогите пожалуйста, я только начал изучать с++ и не совсем понимаю, как сделать эту задачу. Понятного материала для меня я не нашел(( Прошу не бросаться калом, я всего лишь учусь(
Суть задачи.
Записать введенные с клавиатуры числа с плавающей запятой в очередь. Вывести очередь на экран. Удалить их последовательно из очереди и вывести на экран, если соответствующий элемент - положительное число.
Если проще будет без вывода всей очереди, то пусть будет так. Спасибо за понимание, надеюсь на помощь)
A:
https://youtu.be/U4mV_MVCLuU
вот это оочень хороший канал по с++. в этом видео реализаци очереди в stl рассматривается. Если только начинаешь - канал советую всеми руками
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Retrieving row index from UIPickerView and using it in a if statement
Again forgive me if im not being clear, I have only started iOS dev yesterday.
So I have a application that is going to send information to specific email address.
I have included a pickerview and populated it with an array of information, 5 or 6 different categories. What i want to do is to be able to change the recipient's of the email based on what category is selected in the pickerview.
So far I have but selectedRowInComponent doesn't seem to work.
- (IBAction)sendFinalItem:(UIButton *)sender {
NSLog(@"send button pressed");
if ([self.pickerView selectedRowInComponent:(0)])
{
MFMailComposeViewController *mailcontroller = [[MFMailComposeViewController alloc] init];
[mailcontroller setMailComposeDelegate:self];
NSString *email =@"[email protected]";
NSArray *emailArray = [[NSArray alloc] initWithObjects:email, nil];
[mailcontroller setToRecipients:emailArray];
[mailcontroller setSubject:@"[Urgent]Potential Job, iPhone snapped"];
[self presentViewController:mailcontroller animated:YES completion:nil];
[mailcontroller setMessageBody:notesTextView.text isHTML:NO];
}
A:
selectedRowInComponent: returns the index of the selection made by the user. You can use that value to check which e-mail address you need to use.
NSInteger selectedRow = [self.pickerView selectedRowInComponent:0];
if (selectedRow == 0)
{
// E-mail person 1
}
else if (selectedRow == 1)
{
// E-mail person 2
}
// etc.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ssh key accepted by host but client disconnect
Helo,
I have a problem with SSH after fedora 23 installation.
When i wan't to connect to my remote host with private key my host find the key :
debug1: matching key found: file /home/theo/.ssh/authorized_keys, line 1 RSA {REDACTED}
debug1: restore_uid: 0/0
Postponed publickey for theo from {REDACTED} port 60351 ssh2 [preauth]
Connection closed by {REDACTED} [preauth]
debug1: do_cleanup [preauth]
debug1: monitor_read_log: child log fd closed
But as you see my client disconnect by it self
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/tbouge/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 1047
debug2: input_userauth_pk_ok: fp SHA256:{REDACTED}
debug3: sign_and_send_pubkey: RSA SHA256:{REDACTED}
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).
I can connect to my host with putty on windows using the same private key and i can connect with my phone using a different private key.
Do you have any idea ?
/etc/ssh/ssh_conf
Host *
GSSAPIAuthentication yes
# If this option is set to yes then remote X11 clients will have full access
# to the original X11 display. As virtually no X11 client supports the untrusted
# mode correctly we set this to yes.
ForwardX11Trusted yes
# Send locale-related environment variables
SendEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
SendEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
SendEnv LC_IDENTIFICATION LC_ALL LANGUAGE
SendEnv XMODIFIERS
Thank you
Edit: I can connect with a password
A:
First of all, there are numerous, very well written, detailed documentaion on how to setup or configure public key based authentication are available online. Please have a look at one of them and see if you have followed everything correctly. Here is one. So I'm not going to repeat that again.
The very basic concept is (copied from here):
Key-based authentication uses two keys, one "public" key that anyone
is allowed to see, and another "private" key that only the owner is
allowed to see. To securely communicate using key-based
authentication, one needs to create a key pair, securely store the
private key on the computer one wants to log in from, and store the
public key on the computer one wants to log in to.
Now from the debug log you have posted:
It seems there are two different user's are involved. /home/theo/.ssh/authorized_keys and /home/tbouge/.ssh/id_rsa. Are you trying to login as one user to another user's home directory?
The error Postponed publickey for theo.. means unwanted authentication
method have been tried before publick key method. SSH will try every authetication method that are enabled in config, one after another. In your case you have GSSAPIAuthentication yes enabled what you are not using. You can safely disable it by doing GSSAPIAuthentication no.
debug2: we did not send a packet, disable method is most probably that it can't process the private key file (either file permission or name problem). SSH is very sensitive about directory and file permissions in both local and remote computers. (chown user_name:user_group -R /home/user,chmod 700 /home/.ssh, chmod 600 /home/.ssh/authorized_keys ). So, make sure yours are set correctly. See this: https://unix.stackexchange.com/questions/131886/ssh-public-key-wont-send-to-server
As for the third error: Permission denied (public key)., there are a couple of things to check.
Wrong username
Wrong key-pair
Wrong target host
Here are more details: https://stackoverflow.com/questions/18551556/permission-denied-publickey-when-ssh-access-to-amazon-ec2-instance.
The following part is a little confusing:
debug2: we sent a publickey packet, wait for reply
debug1: Server accepts key: pkalg ssh-rsa blen 1047
debug2: input_userauth_pk_ok: fp SHA256:{REDACTED}
debug3: sign_and_send_pubkey: RSA SHA256:{REDACTED}
debug2: we did not send a packet, disable method
To understand it better, lets go through the authentication process step by step as described here at digitalocean:
The client begins by sending an ID for the key pair it would like to
authenticate with to the server.
The server check's the authorized_keys file of the account that the client is attempting to log into for the key ID.
If a public key with matching ID is found in the file, the server generates a random number and uses the public key to encrypt the number.
The server sends the client this encrypted message.
If the client actually has the associated private key, it will be able to decrypt the message using that key, revealing the original number.
The client combines the decrypted number with the shared session key that is being used to encrypt the communication, and calculates
the MD5 hash of this value.
The client then sends this MD5 hash back to the server as an answer to the encrypted number message.
The server uses the same shared session key and the original number that it sent to the client to calculate the MD5 value on its own. It compares its own calculation to the one that the client sent back. If these two values match, it proves that the client was in possession of the private key and the client is authenticated.
In your case, as you can see, the remote computer only accepted your public key, encrypted the packet with that key and sent it back to the client computer. Now the client computer need to prove that it has the right private key. With only the right private_key it can decrypt the recieved message and send an answer back. In this case, the client is failing to do that and the authentication process is ended without success.
I hope this helps you to understand the issues and resolves them.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python:using multiprocessing manager in process pool
i use multiprocessing.managers.BaseManager to manager a Queue at server side,i try to use this queue in another python script which uses a process pool,but i always got the error message as follow, and the main code of this python script is as follow too, and it will start with the run() method.
File "/usr/lib/python2.7/multiprocessing/connection.py", line 435, in answer_challenge
raise AuthenticationError('digest sent was rejected')
AuthenticationError: (AuthenticationError('digest sent was rejected',), <function RebuildProxy at 0x7ff8de0b8320>, (<function AutoProxy at 0x7ff8de0b7938>, Token(typeid='Queue', address=('localhost', 12345), id='7f4624039cd0'), 'pickle', {'exposed': ('cancel_join_thread', 'close', 'empty', 'full', 'get', 'get_nowait', 'join_thread', 'put', 'put_nowait', 'qsize')}))
def __init__(self, spider_count=cpu_count()):
self._spider_count = spider_count
mgr = MyManager(address=('localhost', 12345), authkey='xxxxx')
server = mgr.connect()
self._queue = mgr.Queue()
def run(self):
pool = Pool(self._spider_count)
while not self._queue.empty():
#add some control on q.get() if queue is empty
pool.apply_async(self.startCrawl, (self._queue.get(),))
pool.close()
pool.join()
but when i use it at a single thread, it works well, when use the pool, this error message raised.
A:
This sounds like the issue described in http://bugs.python.org/issue7503
In practice all processes using the manager should have current_process().authkey set to the same value.
The fix, then, would be to assign in __init__:
multiprocessing.current_process().authkey = 'xxxxx'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Structure for a MVC PHP application
I am currently developing a php application using MVC techniques. I started it without thinking about a useful directory structure.
I'm planning to deploy the application to a apache2 server now. This is how it looks right now.
I have a httpdocs folder on the server which is accessible from the web. If I copy all files into this directory some files might be accessible that shouldn't. The public folder contains the files that have to be accessible. (I might need to put my index.php there)
My question is: What is the preferred layout for such an application? Should I put all folders except public in the parent folder of httpdocs?
Thanks for your advices!
A:
http://httpd.apache.org/docs/2.1/vhosts/examples.html
You can have a look there. Setting up a virtual host is always nice so you don't mix your application. And you just give access to your public folder.
<VirtualHost *:80>
DocumentRoot /var/www/mvc_app/public
ServerName www.example.com
<Directory /var/www/mvc_app/public>
Options Indexes FollowSymLinks MultiViews
AllowOverride None
Order allow,deny
allow from all
</Directory>
</VirtualHost>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel TokenMismatchException
Right now I'm learing laravel but I keep getting the exeption:
TokenMismatchException in VerifyCsrfToken.php line 53:
I'm trying to make an object of a migration and then write it to the database but for some reason it's not working. This is my route.php:
Route::get('/post/new',array(
'uses'=> 'blog@newPost',
'as' => 'newPost'
));
Route::post('/post/new', array (
'uses' => 'blog@createPost',
'as' => 'createPost'
));
This is my controller called blog.php:
use Illuminate\Http\Request;
use App\Http\Requests;
use View;
use App\Http\Controllers\Controller;
use App\posts;
class blog extends Controller
{
public function newPost()
{
return View::make('new');
}
public function createPost()
{
$posts = new posts();
$posts->title = Input::get('title');
$posts->content = nl2br(Input::get('content'));
$posts->save();
}
}
This is the migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts',function($table) {
$table->increments('id');
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
schema::drop('posts');
}
}
And this is my main view:
@extends('master')
@section('content')
<h3>Add a blog post</h2>
<form action="{{ URL::route('createPost') }}" method="post">
<div class="form-group">
<input name="title" class="form-control" type="text" placeholder="title"/>
</div>
<div class="form-group">
<textarea name="content" class="form-control" placeholder="write here"> </textarea>
</div>
<input type="submit" class="btn btn-primary" />
</form>
@stop
What could be wrong?
A:
Add this right before </form>
{!! csrf_field() !!}
Take a look at Laravel docs for more info
A:
Add this line before the closing tag of your form:
{{ Form::token() }}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I perform these animated view transitions?
I am brand new to Core Animation, and I need to know how to do 2 animations:
I need to switch XIBs by fading through black (fully releasing the the first view controller)
I need to mimic the UINavigationController's pushViewController animation (switching XIBs and releasing the first view controller)
How can you achieve these animated view transitions?
A:
I've done both of these animations, but maybe not in the exact way you are looking for.
Fade View to black, I took this the other way an instead added a new
subview that covered the entire window that was Black and animated
the Alpha from 0.0 to 1.0. Made for a nice effect.
[UIView animateWithDuration:0.5
animations:^{ _easterEgg.alpha = 1.0; }
completion:^(BOOL finished) { [self animateIndex:0]; }];
Slide in a view like UINavigationController. I didn't do this exactly like UINavigationController since it does multiple animations, but I did have a new view slide the previous view off screen. This code sets the frame of the new view off screen to the right of the current view, builds a frame location that is off the screen to the left, and grabs the current visible frame. Finally it just animates the new view from off screen right into the visible frame, and the old view from the visible frame to off left. Then removes the old view.
CGRect offRight = CGRectMake(_contentView.frame.size.width,
0,
_contentView.frame.size.width,
_contentView.frame.size.height);
CGRect offLeft = CGRectMake(-_contentView.frame.size.width,
0,
_contentView.frame.size.width,
_contentView.frame.size.height);
CGRect visibleFrame = CGRectMake(0, 0, _contentView.frame.size.width, _contentView.frame.size.height);
[view setFrame:offRight];
UIView *currentView = [[_contentView subviews] lastObject];
[_contentView addSubview:view];
[UIView animateWithDuration:0.5
animations:^{
[currentView setFrame:offLeft];
[view setFrame:visibleFrame];
}
completion:^(BOOL finished) {
[currentView removeFromSuperview];
}];
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Flask wtforms: validate_on_submit() returns true every time
I'm new to programming and am wondering why validate_on_submit() returns True every time even if the form is not filled. I am trying to build a duplicate of a social website(facebook, twitter) and am trying to implement a way to comment, reply, and like a post. However, everytime I "like" a post or comment, a duplicate of the comment is added into the database.
Here's my code:
in forms.py:
from flask_wtf import FlaskForm
from wtforms import SubmitField, TextAreaField
from wtforms.validators import DataRequired
class PostForm(FlaskForm):
content = TextAreaField("Content", validators=[DataRequired()])
submit = SubmitField("Post")
class CommentForm(FlaskForm):
content = TextAreaField("Comment_content", validators=[DataRequired()])
submit = SubmitField("Comment")
class ReplyForm(FlaskForm):
content = TextAreaField("Reply_content", validators=[DataRequired()])
submit = SubmitField("Reply")
in routes.py:
@posts.route("/post/<int:post_id>", methods=["GET","POST"])
@login_required
def post(post_id):
comment_form = CommentForm()
reply_form = ReplyForm()
post = Post.query.get_or_404(post_id)
image_file = url_for("static", filename="profile_pic" + current_user.image_file)
comments = Post_comment.query.order_by(Post_comment.date_commented.desc()).filter_by(post_id=post_id)
print(comment_form.validate_on_submit)
if "post_like" in request.form:
user_likes_post(request.form["post_like"])
elif "comment_like" in request.form:
user_likes_comment(request.form["comment_like"])
elif "reply_like" in request.form:
user_likes_reply(request.form["reply_like"])
if comment_form.validate_on_submit:
comment = Post_comment(content=comment_form.content.data, comment_author=current_user, post=post)
db.session.add(comment)
db.session.commit()
elif reply_form.validate_on_submit:
reply = Comment_reply(content=reply_form.content.data, reply_author=current_user)
db.session.add(reply)
db.session.commit()
return render_template("post.html", post=post, comment_form=comment_form, reply_form=reply_form, image_file=image_file, comments=comments)
in post.html:
{% extends "layout.html" %}
{% block content %}
<div id="post">
<div id="post_desc">
<img src="{{ image_file }}">
<a>{{ post.author.username }}</a>
{{ post.date_posted }}
</div>
<div id="post_content">
{{ post.content }}
</div>
<div>{{ post.like_count }}</div>
<form method="POST">
<button name="post_like" type="submit" value="{{ post.id }}" >like</button>
<button name="comment" type="button" href="#" >comment</button>
</form>
</div>
<div>
<form method="POST" action="">
{{ comment_form.hidden_tag() }}
{{ comment_form.csrf_token }}
<fieldset>
<div>
{% if comment_form.content.errors %}
{{ comment_form.content() }}
<div>
{% for error in comment_form.content.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ comment_form.content() }}
{% endif %}
</div>
<div>
{{ comment_form.submit() }}
</div>
</form>
{% for comment in comments %}
<div id="comment">
<div id="comment_desc">
<img src="{{ image_file }}">
<a>{{ comment.comment_author.username }}</a>
{{ comment.date_posted }}
</div>
<div id="comment_content">
{{ comment.content }}
</div>
<div>{{ comment.like_count }}</div>
<form method="POST">
<button name="comment_like" type="submit" value="{{ comment.id }}" >like</button>
</form>
</div>
<div>
<form method="POST" action="">
{{ reply_form.hidden_tag() }}
{{ reply_form.csrf_token }}
<fieldset>
<div>
{% if reply_form.content.errors %}
{{ reply_form.content() }}
<div>
{% for error in reply_form.content.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ reply_form.content() }}
{% endif %}
</div>
<div>
{{ reply_form.submit() }}
</div>
</form>
</div>
{% for reply in comment.replies %}
<div id="reply">
<div id="reply_desc">
<img src="{{ image_file }}">
<a>{{ reply.reply_author.username }}</a>
{{ reply.date_posted }}
</div>
<div id="reply_content">
{{ reply.content }}
</div>
<div>{{ reply.like_count }}</div>
<form method="POST">
<button name="reply_like" type="submit" value="{{ reply.id }}" >like</button>
</form>
</div>
{% endfor %}
</div>
{% endfor %}
</div>
{% endblock %}
What I think is happening here is that when I "like" the post, comment, or reply, a POST request is sent but I am not sure why validate_on_submit() returns true for it to pass the if statement and add the entry to the database even when there is the Datarequired() validator.
Apologies if my code is quite messy, I'm new to programming and need some time to learn best practices.
A:
Seems like you might have syntax issues,
This is what you have:
if comment_form.validate_on_submit:
This is how the documentation says it should be used:
if comment_form.validate_on_submit():
Hope that helps! :D
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Receiving IActionResult from WebApi
I have created Web API, and my problem is reading results from it to client.
WebApi method which creating user:
[HttpPost]
public IActionResult PostNewUser([FromBody]UserDto userDto)
{
if (userDto == null)
return BadRequest(nameof(userDto));
IUsersService usersService = GetService<IUsersService>();
var id = usersService.Add(userDto);
return Created("api/users/", id.ToString());
}
And the client which want to call API code is:
public int CreateUser(UserDto dto)
{
using (HttpClient client = new HttpClient())
{
string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var postReult = client.PostAsync(endpoint, json).Result;
return 1; //??
}
}
It works, response gives 201 (Created) but I have no idea how to return correct result, which should be:
/api/users/id_of_created_user
I'm using netcore2.0 in both projects
A:
In the Web API either construct the created location URL manually
[HttpPost]
public IActionResult PostNewUser([FromBody]UserDto userDto) {
if (userDto == null)
return BadRequest(nameof(userDto));
IUsersService usersService = GetService<IUsersService>();
var id = usersService.Add(userDto);
//construct desired URL
var url = string.Format("api/users/{0}",id.ToString());
return Created(url, id.ToString());
}
Or use one of the CreateAt* overloads
//return 201 created status code along with the
//controller, action, route values and the actual object that is created
return CreatedAtAction("ActionName", "ControllerName", new { id = id }, id.ToString());
//OR
//return 201 created status code along with the
//route name, route value, and the actual object that is created
return CreatedAtRoute("RouteName", new { id = id }, id.ToString());
In the client, the location is retrieved from the header of the response.
status HttpClient client = new HttpClient();
public async Task<int> CreateUser(UserDto dto) {
string endpoint = ApiQuery.BuildAddress(Endpoints.Users);
var json = new StringContent(JsonConvert.SerializeObject(dto), Encoding.UTF8, "application/json");
var postResponse = await client.PostAsync(endpoint, json);
var location = postResponse.Headers.Location;// api/users/{id here}
var id = await postResponse.Content.ReadAsAsync<int>();
return id;
}
You also appear to be sending the id as part of the response which can be retrieved from the response content.
Note the refactoring of HttpClient to avoid creating an instance every time which can lead to socked exhaustion that can cause errors.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How would i go about creating a win count and guess count for my random number guessing game C#
Hey so i've got everything that i needed for my guessing game and everything checks out and runs without issue, the only problem is i want to have a wincount and a guess count so that the user can't get more guesses than what the program dictates. currently the program will tell you how many guesses you should be getting but it will only let you guess once because of the single if statement, so how would i go about doing this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessingGame
{
class Program
{
static void Main(string[] args)
{
// Declare variables
Int32 currentGuess, guessCount, winCount, upperLimit, randomNumber;
double maxGuesses;
bool gameOver;
char playAgain;
Random random = new Random();
// Display title
Console.WriteLine("Welcome to the high/low guessing game.");
//Request user input for upper limit
Console.WriteLine("Enter Upper range (e.g. 100):");
upperLimit = Int32.Parse(Console.ReadLine());
//Generate Random Number
randomNumber = random.Next(1, upperLimit);
maxGuesses = Math.Ceiling(Math.Log(upperLimit, 2) - 1);
// Begin game
Console.WriteLine("I picked a number between 1 and {0} you get {1} chances to guess it", upperLimit, maxGuesses);
// Begin Guessing Process
//Guess #1
{
Console.WriteLine(" Enter Guess #1: ");
currentGuess = Int32.Parse(Console.ReadLine());
if (currentGuess == randomNumber)
{
Console.WriteLine("You got it!");
}
if (currentGuess > randomNumber)
{
Console.WriteLine("Too High");
}
if (randomNumber > currentGuess)
{
Console.WriteLine("Too Low");
}
Console.ReadLine();
}
}
}
}
A:
int gessNum = 0;
do
{
if (gessNum++ == maxGuesses){
Console.WriteLine("You lost");
break;
}
Console.WriteLine(string.Format(" Enter Guess {0}: ", gessNum));
currentGuess = Int32.Parse(Console.ReadLine());
if (currentGuess == randomNumber)
{
Console.WriteLine("You got it!");
}
if (currentGuess > randomNumber)
{
Console.WriteLine("Too High");
}
if (randomNumber > currentGuess)
{
Console.WriteLine("Too Low");
}
Console.ReadLine();
} while (currentGuess != randomNumber);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
RSA - Proof for dummies
I'm understanding the basic idea behind why RSA is secure, but I'm having a hard time understanding its proof with only basic knowledge of numbers theory. so I'm hoping that somebody can help me answering a few questions:
By generating two random primes and building the product $n = p\cdot q$, we can easily get eulers totient function $\phi(n) = (p-1)\cdot(q-1) $ without having to check all relatively prime between $[1;pq]$
Question 1) Is the only reason why $p$ and $q$ have to be prime numbers that we can easily compute $\phi(n)$? Or is there another consequence of $n$ being the product of two primes? As $n$ is not necessarily a prime, I don't see any other implication.
Next we choose an $e$ so that $1 < e < \phi(n)$ and $gcd(e, \phi(n)) = 1$
Question 2) Could I also say that we just randomly choose an element of the multiplicative group $Z_{\phi(n)}^*$? I mean, all elements of this group are relatively prime to $\phi(n)$ right?
Question 3) Does the length of $e$ have an influence on the security?
Next we choose the inverse element $d$ of $e$, in other words, $e\cdot d \equiv 1 \mod \phi(n)$.
So, now we can encrypt some $c = m^e \mod n$ and decrypt by $m=c^d \mod n$
Now, by substituting $c$ in the decryption we get $m = (m^e)^d \mod n$ which is the same as $m=m^{ed} \mod n$
Now I'm not getting anywhere further because I'm seeing very different ways how people proof it (chinese remainders? We never learnt them so there should be another way). Would somebody be so kind to explain the proof with eulers theorem or fermats theorem in a way that even a dummy like me can follow it? :)
A:
The correctness of the cryptosystem (in the sense that decryption is inverse to encryption) depends on
$$m^{k\phi(n)+1}\equiv m\pmod n$$
for all $m$. Euler's theorem says that this is the case when $m$ and $n$ are coprime -- which is not enough here -- but if $n$ is known to be square-free it is actually the case for all $m$.
Constructing $n$ as the product of two different primes is an easy way to make sure it is square-free. It also seems to be a straightforward way to maximize the difficulty of computing $\phi(n)$ among other $n$s of a similar size.
Yes, you could just choose a random coprime $e$. In practice people pick smallish $e$ such as 65537 because it slightly reduces the work one needs to do to apply the public key.
$e=1$ obviously won't do. Anything larger than that is thought to be okay, as long as proper padding is used for the messages (such that you avoid having $m^e < n$).
On the other hand, $d$ (which is the the only secret essential part of the secret key) should be large. Choosing a small $e$ will automatically prevent $d$ from being so small that known key-recovery attacks for small $d$ will work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to set label text to JTextField input
I'm trying to get a user to input a name in one panel on CardLayout and for the input to then define a JLabels text in the next panel that it switches to. I used System.out.println(userName); to double check that it was picking up the text and it definitely is but I don't know how to get the 'user' text to be that of the JTextFields input.
Full working code below:
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class gameDataPanel {
private JFrame frame = new JFrame("Game Data Input");
private JPanel mainPanel, loginPanel, gameDataPanel;
private JLabel playerName, user;
private JTextField playerNameInput;
private JButton submit;
private CardLayout gameDataLayout = new CardLayout();
private String userName;
public gameDataPanel() {
mainPanel = new JPanel();
mainPanel.setLayout(gameDataLayout);
playerName = new JLabel("Enter Player Name: ");
playerNameInput = new JTextField(30);
submit = new JButton("Submit");
loginPanel = new JPanel();
loginPanel.add(playerName);
loginPanel.add(playerNameInput);
loginPanel.add(submit);
gameDataPanel = new JPanel();
user = new JLabel();
user.setText(userName);
gameDataPanel.add(user);
mainPanel.add(loginPanel, "1");
mainPanel.add(gameDataPanel, "2");
gameDataLayout.show(mainPanel, "1");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
userName = playerNameInput.getText();
gameDataLayout.show(mainPanel, "2");
System.out.println(userName);
}
});
playerNameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
userName = playerNameInput.getText();
gameDataLayout.show(mainPanel, "2");
System.out.println(userName);
}
});
frame.add(mainPanel);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
}
public static void main(String[] args) {
gameDataPanel gd = new gameDataPanel();
}
}
Thanks
A:
I am not 100% sure, whether i understood you correctly: You want to display the users name, which is entered in "playerNameInput" to be displayed in the JLabel "user" ? In this case, you have to update your JLabel object in your event listener AFTER the user entered something and pressed the push button. Try something like this:
playerNameInput.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
userName = playerNameInput.getText();
user.setText(userName);
gameDataLayout.show(mainPanel, "2");
System.out.println(userName);
}
});
I hope this helps :-)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Install go package with dependencies
I had some issues with gopath configuration. I was able to resolve the go path issue. But getting this error...
[root@localhost mysqlbeat]# go get github.com/adibendahan/mysqlbeat
# github.com/adibendahan/mysqlbeat/beater
/root/go/src/src/github.com/adibendahan/mysqlbeat/beater/mysqlbeat.go:289:7: b.Events undefined (type *beat.Beat has no field or method Events)
/root/go/src/src/github.com/adibendahan/mysqlbeat/beater/mysqlbeat.go:303:7: b.Events undefined (type *beat.Beat has no field or method Events)
/root/go/src/src/github.com/adibendahan/mysqlbeat/beater/mysqlbeat.go:326:5: b.Events undefined (type *beat.Beat has no field or method Events)
How do I correctly install go package along with all it's dependencies?
Update:
I downloaded the package and tried to run it.Different error this time...
[root@localhost mysqlbeat]# make
go build
can't load package: /root/go/src/src/github.com/adibendahan/mysqlbeat/main.go:8:2: non-standard import "github.com/adibendahan/mysqlbeat/beater" in standard package "src/github.com/adibendahan/mysqlbeat"
make: *** [build] Error 1
A:
Check out the How to Build section on README.md on mysqlbeat.
mysqlbeat uses Glide for dependency management. Check this for installing glide.
After installing Glide, clone the mysqlbeat repository and run:
$ glide update --no-recursive
$ make
If you still want to import this repository by go get, clone the repo and then run go get ./... from its root directory.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to customise the .cls file?
I have here a very specific problem but I think the way to solve it may include a general knowledge that may be of interest to other people too.
I have a .cls file which controls the style of a paper I'm writting. The style fits my needs almost perfectly but I must change a few things so it can be exactly what I need. The way things are now I can use the functions \author, \name and \ affiliation to write the authors and the universities they belong to at the top of the first page of the paper. This is done like this
\author{\name{John Doe}
\affiliation{State University of Nowhere}}
and I get as result (the title is called by other function which I have no problem with, just ignore it)
If the paper is a colaboration between several authors I can do this
\author{\name{John Doe}
\affiliation{State University of Nowhere}
\name{John Doe}
\affiliation{State University of Nowhere}
\name{John Doe}
\affiliation{State University of Nowhere}}
to obtain
and this is no good. It is not visually pleasing, it takes too much space and I don't want to repeat the name of the University if two or more of the authors come from the same institution.
What I want to do is to write the names of the authors side by side and them pass the institutions to below the names, with one institution per line. The names are no problem. I can put them in this form by writting
\name{John Doe, John Doe, John Doe}
but I could do nothing about the institutions. In the .cls files these functions are defined like this
\author{%
\hspace{-4pt}%
\begin{tabular*}{\textwidth}{@{}ll@{}}%
\@TheAuthor%
\end{tabular*}%
\\%
\hspace{-9pt}%
\HorRule%
}
%
\renewcommand{\author}[1]{\def\@TheAuthor{#1}}
\newcommand{\name}[1]{\large%
\lineskip 0.5em%
\usefont{T1}{phv}{b}{sl}%
\color{DarkRed}%
#1&%
}
\newcommand{\affiliation}[1]{%
\hskip 0.75em%
\footnotesize%
\usefont{T1}{phv}{m}{sl}%
\color{Black}%
\begin{minipage}{\linewidth}%
#1%
\end{minipage}%
\\%
}
I don't understand what is going on with these definitions. Can you give me a hand here?
Thank you very much.
A:
What \author does is (more or less) construct a tabular
\begin{tabular}{...}
name & affiliation \\
name & affiliation
\end{tabular}
The & is supplied by the \name macro and the \\ by \affiliation.
A quick and dirty solution for you is to define a \names macro that is a copy of \name with the & replaced by \\.
\newcommand{\names}[1]{\large%
\lineskip 0.5em%
\usefont{T1}{phv}{b}{sl}%
\color{DarkRed}%
#1\\%
}
and use
\author{\names{John Doe, John Doe, John Doe}
\affiliation{State University of Nowhere}}.
This still gives you the option to use the original format for single authors.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SilverStripe - Custom Faceted Search Navigation
I'm working on page for a SilverStripe that will allow users to sort through portfolio pieces based on the selected facets.
Here are the key points/requirements:
I have 2 facet categories they can search by: Media Type (i.e. Ads,
Posters, TV, Web) and Industry (Entertainment, Finance, Healthcare,
Sport, etc).
Users should be allowed to search multiple facets at once and also
across media type and industry at once.
In the SilverStripe admin, since content managers need to be able
to maintain the facet namesfor Media Type and Industry, I made it so
that there are 2 admin models where the names can be entered:
MediaTypeTagAdmin and IndustryTagAdmin. Here are the data object
classes for MediaTypeTag and IndustryTag that are used by the admin
models:
MediaTypeTag class
<?php
class MediaTypeTag extends DataObject {
private static $db = array(
'Name' => 'varchar(250)',
);
private static $summary_fields = array(
'Name' => 'Title',
);
private static $field_labels = array(
'Name'
);
private static $belongs_many_many = array(
'PortfolioItemPages' => 'PortfolioItemPage'
);
// tidy up the CMS by not showing these fields
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->removeByName("PortfolioItemPages");
return $fields;
}
static $default_sort = "Name ASC";
}
IndustryTag class
<?php
class IndustryTag extends DataObject {
private static $db = array(
'Name' => 'varchar(250)',
);
private static $summary_fields = array(
'Name' => 'Title',
);
private static $field_labels = array(
'Name'
);
private static $belongs_many_many = array(
'PortfolioItemPages' => 'PortfolioItemPage'
);
// tidy up the CMS by not showing these fields
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->removeByName("PortfolioItemPages");
return $fields;
}
static $default_sort = "Name ASC";
}
There needs to be a page for each Portfolio Item, so I made a PortfolioItemPage type, which has 2 tabs: one for Media Type and one for Industry Type. This is so content managers can associated whatever tags they want with each Portfolio Item by checking the appropriate boxes:
PortfolioItemPage.php file:
private static $db = array(
'Excerpt' => 'Text',
);
private static $has_one = array(
'Thumbnail' => 'Image',
'Logo' => 'Image'
);
private static $has_many = array(
'PortfolioChildItems' => 'PortfolioChildItem'
);
private static $many_many = array(
'MediaTypeTags' => 'MediaTypeTag',
'IndustryTags' => 'IndustryTag'
);
public function getCMSFields() {
$fields = parent::getCMSFields();
if ($this->ID) {
$fields->addFieldToTab('Root.Media Type Tags', CheckboxSetField::create(
'MediaTypeTags',
'Media Type Tags',
MediaTypeTag::get()->map()
));
}
if ($this->ID) {
$fields->addFieldToTab('Root.Industry Tags', CheckboxSetField::create(
'IndustryTags',
'Industry Tags',
IndustryTag::get()->map()
));
}
$gridFieldConfig = GridFieldConfig_RecordEditor::create();
$gridFieldConfig->addComponent(new GridFieldBulkImageUpload());
$gridFieldConfig->getComponentByType('GridFieldDataColumns')->setDisplayFields(array(
'EmbedURL' => 'YouTube or SoundCloud Embed Code',
'Thumb' => 'Thumb (135px x 135px)',
));
$gridfield = new GridField(
"ChildItems",
"Child Items",
$this->PortfolioChildItems(),
$gridFieldConfig
);
$fields->addFieldToTab('Root.Child Items', $gridfield);
$fields->addFieldToTab("Root.Main", new TextareaField("Excerpt"), "Content");
$fields->addFieldToTab("Root.Main", new UploadField('Thumbnail', "Thumbnail (400x x 400px)"), "Content");
$fields->addFieldToTab("Root.Main", new UploadField('Logo', "Logo"), "Content");
return $fields;
}
}
class PortfolioItemPage_Controller extends Page_Controller {
private static $allowed_actions = array (
);
public function init() {
parent::init();
}
}
What I thought might be a good approach would be to use jQuery and AJAX to send the ids of the selected facets to the server:
(function($) {
$(document).ready(function() {
var industry = $('.industry');
var media = $('.media');
var tag = $('.tag');
var selectedTags = "";
tag.each(function(e) {
$(this).bind('click', function(e) {
e.preventDefault();
$(this).addClass('selectedTag');
if(selectedTags.indexOf($(this).text()) < 0){
if($(this).hasClass('media')){
selectedTags += + $(this).attr("id") + "," +"media;";
}
else{
selectedTags += + $(this).attr("id") + "," +"industry;";
}
}
sendTag(selectedTags);
}.bind($(this)));
});
function sendTag(TagList){
$.ajax({
type: "POST",
url: "/home/getPortfolioItemsByTags/",
data: { tags: TagList },
dataType: "json"
}).done(function(response) {
var div = $('.portfolioItems');
div.empty();
for (var i=0; i<response.length; i++){
div.append(response[i].name + "<br />");
//return portfolio data here
}
})
.fail(function() {
alert("There was a problem processing the request.");
});
}
});
}(jQuery));
Then on Page.php, I loop through the ids and get the corresponding PortfolioItemPage information based on the facet ids:
public function getPortfolioItemsByTags(){
//remove the last comma from the list of tag ids
$IDs = $this->getRequest()->postVar('tags');
$IDSplit = substr($IDs, 0, -1);
//put the tag ids and their tag names (media or industry) into an array
$IDListPartial = explode(";",$IDSplit);
//This will hold the associative array of ids to types (i.e. 34 => media)
$IDListFinal = array();
array_walk($IDListPartial, function($val, $key) use(&$IDListFinal){
list($key, $value) = explode(',', $val);
$IDListFinal[$key] = $value;
});
//get Portfolio Items based on the tag ids and tag type
foreach($IDListFinal as $x => $x_value) {
if($x_value=='media'){
$tag = MediaTypeTag::get()->byId($x);
$portfolioItems = $tag->PortfolioItemPages();
}
else{
$tag = IndustryTag::get()->byId($x);
$portfolioItems = $tag->PortfolioItemPages();
}
$return = array();
foreach($portfolioItems as $portfolioItem){
$return[] = array(
'thumbnail' => $portfolioItem->Thumbnail()->Link(),
'name' => $portfolioItem->H1,
'logo' => $portfolioItem->Logo()->Link(),
'excerpt' => $portfolioItem->Excerpt,
'id' => $portfolioItem->ID
);
}
return json_encode($return);
}
}
However, this is where I am getting stuck. While I have found some decent examples of building a PHP/MySQL faceted search outside of a CMS, I am not sure what I can modify in order to make the search work inside a CMS. That, and the examples put the facets in one table in the MySQL database whereas I have 2 (As much as I want to have just one MySQL table for both the Media Type and Industry facets, I am not sure if this is a good idea since content managers want to maintain the facet names themselves).
Are there any tutorials out there that might provide further assistance, or possibly a plugin that I have not found yet? If there is a better way to set this faceted search up, by all means, please suggest ideas. This is pretty new to me.
A:
The most efficient way to do this is to filter based on the tag/media type IDs in one query (your example is doing one database query per tag/type, then appending the results).
You should be able to do something like this:
<?php
public function getPortfolioItemsByTags(){
$tagString = $this->getRequest()->postVar('tags');
// remove the last comma from the list of tag ids
$tagString = substr($tagString, 0, -1);
//put the tag ids and their tag names (media or industry) into an array
$tags = explode(";", $tagString);
//This will hold the associative array of ids to types (i.e. 34 => media)
$filters = array(
'media' => array(),
'industry' => array()
);
array_walk($tags, function($val, $key) use(&$filters) {
list($id, $type) = explode(',', $val);
$filters[$type][] = $id;
});
$portfolioItems = PortfolioItemPage::get()->filterAny(array(
'MediaTypeTags.ID' => $filters['media'],
'IndustryTags.ID' => $filters['industry']
));
$return = array();
foreach($portfolioItems as $portfolioItem){
$return[] = array(
'thumbnail' => $portfolioItem->Thumbnail()->Link(),
'name' => $portfolioItem->H1,
'logo' => $portfolioItem->Logo()->Link(),
'excerpt' => $portfolioItem->Excerpt,
'id' => $portfolioItem->ID
);
}
return json_encode($return);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Invalid token when using Apple Push Notifications (APN) for Passbook
I am trying to create a server-side implementation for passbook APN, but the server does not like the push token that the device is giving me. If I send the token to Apple's sandbox server, it sends me an "invalid token" response. If I send the token to Apple's production server, it returns the token in the feedback service as one that I should remove from my list. At least I know that the APN certificates and connection to the server work fine.
My iPhone 4s has been enabled for development. The APP ID is enabled for both development and production and the device is enabled in the provisioning profiles. I have verified that the 32 byte binary token data is correct with respect to the string token that is sent from the device.
One question that I have is, how does passbook in the device determine which token to use (development vs production)? I would prefer to be using the sandbox environment right now, but I'm not sure how to "select" it.
I have seen similar topics for this but none seem to have the answer for this issue. It is really frustrating as I feel that I'm so close to making this work! Thanks in advance for any advice!
A:
If you are using a pruduction certificate to connect to the APN production server, you must use a production token.
The fact that you get "invalid token" when sending the notification to the sandbox server means you are using a production token, which works only with the production server.
The fact that sending the token to the production server returns the token in the feedback service means that the application that matches the certificate (which your server is using to send the notification) is either uninstalled from the device or has push notifications disabled. Perhaps you are using a wrong certificate (perhaps a certificate that belong to a different App that was uninstalled from the device).
A:
For Passbook pushes, you need to be connecting to the production server with the Pass Type ID certificate, not the App certificate.
All Passbook pushes go through the production server, there is no way to use the sandbox.
Also, the push payload should be empty for a Passbook push. Anything you do send will be ignored.
A:
Found the root cause for this issue, it is because of bad private key. To resolve this issue just generate a .p12 certificate with .pem . For creating the p12 file with .pem file please follow the below method
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Payment methods not appearing for admin orders
We recently upgraded our 1.8 installation to 1.9.2.4 and now when we try to add a product to an order via the admin area (Admin > Sales > Orders > Create New Order) none of the set up Payment methods appear.
As far as I can see all configuration is correct. I've found a similar question here but there is no answer and the suggestions do not work either.
A:
I realise I never accepted an answer for this.
It turned out to be a clash between two modules we had installed that was causing the options in question to be hidden.
After updating the modules the problem was solved.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Precedence of RewriteRules in .htaccess file on Apache Server
I have a number of RewriteRules in my .htaccess file. However, one specific rule is only executed if I remove another specific rule, regardless of how I order the two rules.
Here's the rule which seems to have "lower" priority:
RewriteRule ^([0-9]+)$ /beta/forward.php?id=$1 [L]
And here's the rule which always takes precedence:
RewriteCond %{HTTP_HOST} ^domain1\.net$ [NC]
RewriteRule ^(.*)$ http://domain2.net/$1 [R=301,L]
Both domain1 and domain2 actually point to the same web site. So, whenever both rules are in the .htaccess file and I access
http://domain1.net/123
The second rule gets executed first and I get two redirects, first to http://domain2.net/123 and then (when the host name doesn't fit the second rule anymore) to http://domain2.net/beta/forward.php?id=123. I've tried fixing the second rule so it is never executed for urls which only contain numbers, but I must be doing something wrong, because it still gets executed:
RewriteCond %{HTTP_HOST} ^ domain1\.net$ [NC]
RewriteRule ^(.*[^0-9]+.*)$ http://domain2.net/$1 [R=301,L]
Only be removing the two lines from the .htaccess file can I get the first rule to handle the request right away.
Any help would be greatly appreciated.
A:
Your rules indicate these procedures:
If the URL is only numbers, go to the beta URL followed by those numbers and stop.
If you visit domain1, go to the same URL at domain2 and stop.
When an L is encountered or the rules are finished, the processing ends. Anything else happening is a new connection from the browser. This is probably what is confusing for you—the order matters, then the matches. The L should take care of the problem you have when they're in order:
RewriteEngine on
RewriteRule ^([0-9]+)$ /beta/forward.php?id=$1 [L] # end of processing [L] if it's only numeric
RewriteCond %{HTTP_HOST} ^domain1\.net$ [NC] # if case-insensitive match of domain1.net…
RewriteRule ^(.*)$ http://domain2.net/$1 [R=301,L] # redirect to domain2.net. End [L]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should I use dispatch on return type of action in reactjs?
I confused on using dispatch.Please see my below code.
export function getUserInfo(isDeviceinfo) {
return (dispatch) => {
dispatch({
type: REQUEST_DEVICE_MODEL_RESET,
isDeviceinfo,
});
};
}
or
export function getUserInfo(isDeviceinfo) {
return => {
type: REQUEST_DEVICE_MODEL_RESET,
isDeviceinfo,
};
}
Now which one I should use.Please suggest me.
A:
If you dont need to perform any asynchromous operation use this,
export function getUserInfo(isDeviceinfo) {
return{
type: REQUEST_DEVICE_MODEL_RESET,
isDeviceinfo,
};
}
If you need to perform asynchronous operation use dispatch.
function getUserInfo(isDeviceinfo) {
return (dispatch)=>{
//perform a async operation like this http call
return fetch(SOME_URL).then(j=>j.json()).then((d)=>{
dispatch({
type: REQUEST_DEVICE_MODEL_RESET,
isDeviceinfo,
})
})
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MySQL select ranges from query result
For a application I'm currently developing I have a little problem that needs to be fixed, it is oriented for the Dutch so I have a table of all the Dutch zip codes that I can use.
In my application I need to build regions based on cites and this is where I hit a problem, currently I select the first and last known zip code of a city, which is fine in most cases. Which is fine for most cases, but sometimes this doesn't work right because of a zip code being numbered before another city, so that means that in some cases one city matches another.
What I would like to do is get all the ranges with my city from my table. This is a little example what the table looks like (it is missing some unneeded fields for this porpuse).
Zipcode | City
--------|-------
2411 AA | Bodegraven
2411 AB | Leiden
2411 AC | Leiden
2411 AD | Bodegraven
2411 AE | Bodegraven
2411 AF | Leiden
2411 AG | Leiden
2411 AH | Bodegraven
With my current query the first zipcode in Bodegraven would be 2411 AA and the last 2411 AH, which isn't interly incorrect, since that is what is stored.
However I would like my result to be the following:
Start | End
--------|--------
2411 AA | 2411 AA
2411 AD | 2411 AE
2411 AH | 2411 AH
Is it possible with pure MySQL to generate this result?
Thank you for your time, and responses, if you have any questions please let me know :)
A:
This is very awkward in MySQL, but it is possible.
First we need a way of dynamically defining some kind of "group" identifier that increments as the city changes from row to row. We can do this with MySQL user-defined variables.
SELECT zipcode,
@groupid:=IF(city=@prev_city,@groupid,@groupid+1) AS groupid,
@prev_city:=city AS city
FROM MyTable, (SELECT @groupid:=0) AS _init
ORDER BY zipcode;
+---------+---------+------------+
| zipcode | groupid | city |
+---------+---------+------------+
| 2411 AA | 0 | Bodegraven |
| 2411 AB | 1 | Leiden |
| 2411 AC | 1 | Leiden |
| 2411 AD | 2 | Bodegraven |
| 2411 AE | 2 | Bodegraven |
| 2411 AF | 3 | Leiden |
| 2411 AG | 3 | Leiden |
| 2411 AH | 4 | Bodegraven |
+---------+---------+------------+
Now we can use this in a derived table subquery and get the MIN() and MAX() value in each group:
SELECT MIN(zipcode) AS Start, MAX(zipcode) AS End
FROM (
SELECT zipcode,
@groupid:=IF(city=@prev_city,@groupid,@groupid+1) AS groupid,
@prev_city:=city AS city
FROM MyTable, (SELECT @groupid:=0) AS _init
ORDER BY zipcode
) AS t
WHERE city = 'Bodegraven'
GROUP BY groupid;
+---------+---------+
| Start | End |
+---------+---------+
| 2411 AA | 2411 AA |
| 2411 AD | 2411 AE |
| 2411 AH | 2411 AH |
+---------+---------+
Unfortunately, the condition of WHERE city='Bodegraven' must be in the outer query. The subquery must generate the groupings by reading all rows, not just those for Bodegraven. So it must scan through a lot of rows (perhaps you could restrict it to the min and max zipcodes for Bodegraven).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is it possible to create a new Gremlin Graph DB and Graph using c# code
I have a Azure Cosmos DB account with Gremlin API. I'm using Gremlin.Net to query the db.
var gremlinServer = new GremlinServer(hostname, port, enableSsl: true, username: "/dbs/" + database + "/colls/" + collectionName, password: authKey);
username parameter takes dbname and collection name.
Just wondering how to create a new graph db and a graph under the account using c# code.
Thanks
A:
I searched the azure gremlin .Net source code , no such methods like creating database or graph could be found. There is an statement mentioned in above link:
This sample uses the open-source Gremlin.Net driver to connect to an
Azure Cosmos DB Graph API account and run some basic Create, Read,
Update, Delete Gremlin queries.
It seems that we could only execute gremlin queries, can't CRUD database itself.
I also searched Cosmos DB REST API, no such special api for CRUD cosmos db graph api. Only operations of database and collection could be found. So I tested it with below sample code with Document DB .Net SDK and it works for me.
client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]);
await client.CreateDatabaseAsync(new Database { Id = "db"});
await client.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(DatabaseId),
new DocumentCollection
{
Id = "coll"
},
new RequestOptions { OfferThroughput = 400 });
I know it is strange(there is no collection in cosmos db graph api,it supposed to be graph) but it works for me.You could try it on your side.
Hope it helps you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can Buildroot build the root filesystem without building the Linux kernel?
I tried:
git checkout 2018.05
make qemu_x86_64_defconfig
make BR2_JLEVEL="$(nproc)" "$(pwd)/output/images/rootfs.ext2"
but it still built the kernel at:
output/images/bzImage
I want to do that because:
I'm making a setup where you can pick between multiple different root filesystems, so I will need to build Linux kernel manually for the other root filesystems, and would not like Buildroot to waste time building it again
I don't want to wait 5 seconds every time for Buildroot to parse 100 Makefile configs when I want to rebuild the kernel :-)
I'm using LINUX_OVERRIDE_SRCDIR with Linux on a submodule, so Linux the headers should match the source I will use for the build.
Is there a fundamental dependency between, say, glibc and the kernel build, or is it just a weird use case never catered for?
Ah, I noticed now that any loadable kernel modules need to go on the rootfs and would require a kernel build, and that build does have some .ko in the rootfs.
A:
Well, just disable BR2_LINUX_KERNEL and Buildroot will no longer build the kernel.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Convert HH:MM Time to Decimal before_save in Ruby on Rails
I have a duration field that is a decimal data type in my database.
My form accepts decimals (e.g. 1.5 hours) but I also want to be able to accept HH:MM (e.g. 1:30 for one hour and thirty minutes).
I'd like to be able to detect HH:MM with regex on before_save in my model and convert it to decimal so that users can enter either decimal or HH:MM. This part is fine and good, but the problem I'm having is testing the regex against the value in the field.
1:30 gets interpreted as data type --- !ruby/class 'BigDecimal' and I can't test it against regex.
Doing .to_s on it converts it to 1.0
How do I get my decimal-typed field to relax and let me convert its value to a string for regex testing in my model?
Here's my code:
# --- Model ---
before_save :convert_duration
def convert_duration
if duration =~ /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/
time_pieces = duration.split(":")
hours = time_pieces[0].to_i
minutes = (time_pieces[1].to_f/60.0)
# Final value ready for database
self.duration = (hours+minutes).round(1)
end
end
Ruby 1.9.3; Rails 3.2.8
A:
Use the duration_before_type_cast attribute when you want access to the original string.
Docs: http://api.rubyonrails.org/classes/ActiveRecord/Base.html#label-Accessing+attributes+before+they+have+been+typecasted
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Change on hover properties if condition is true
So I'm making a web app using HTML, CSS, JavaScript, and AngularJS.
So far, I have a box with some content in the box. When that box is clicked, I call a javascript function to display more boxes and I did that using ng-click.
<div ng-click="!(clickEnabled)||myFunction(app)" class ="box">
*** things displyaed inside the box ***
</div>
clickEnabled's value (true or false) determines if myFunction() gets called or not and this part works perfectly. ng-click is disabled when clickEnabled is false.
Now the problem is that in my css file, I have my .box class such that the cursor is pointer when I hover over the box and background of the box also changes on hover. Is there a way to make cursor:default and make it so that it doesn't change background color of box when ng-click is disabled or when clickEnabled is false?
Here's a sample of my css code
.box {
border: 1px solid lightgray;
padding: 10px;
border-radius: 5px;
border-color: white;
box-shadow: 0 0 5px gray;
cursor: pointer;
background: #353131;
border-width: 2px;
display: inline-block;
width: 300px;
height: 150px;
}
.box:hover {
background-color: dimgrey;
border-color: grey;
}
Again, I don't want the cursor to be pointer when clickEnabled is false/ng-click is disabled.
Thanks in advance :)
A:
You can try to use ng-class
<div ng-click="!(clickEnabled)||myFunction(app)" ng-class="{no-cursor: !clickEnabled}" class="box" >
*** things displyaed inside the box ***
</div>
.box.no-cursor {
cursor: default;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to pass an int[] array into main(String []args)?
I'm trying to write a program that begins in the main method, and calls a method that contains an integer array.
Essentially, the program is a basic lift that assumes all inputs are received at the same time. The stops the lift will make are stored in an array called stoppages which is a combination of the stops of the lift going up, and the stops of the lift going down.
I want the program to start in main, and call the method that sorts all of the floors and such. However, when I run the program it changes all of the values of the final array into 0's.
Why is it doing this, and what needs to be done to allow the array values to remain unchanged when the program is run?
This is the main method:
public class user_interface {
public static void main(String[] args) {
floor_sorting.sorting_floors(args);
}
}
And this is the method I'm trying to call:
import java.util.*;
public class floor_sorting{
public static void sorting_floors(int[] args){
//bubble sort - sorts out user_up in ascending order
for (int i = 0; i < user_stops.user_up.length; i++) {
for (int x = 1; x < user_stops.user_up.length - i; x++) {
if (user_stops.user_up[x-1] > user_stops.user_up[x]){
int temp = user_stops.user_up[x-1];
user_stops.user_up[x-1] = user_stops.user_up[x];
user_stops.user_up[x] = temp;
}
}
}
//bubble sort again, but in descending order
for (int i = 0; i < user_stops.user_down.length; i++) {
for (int x = 1; x < user_stops.user_down.length - i; x++) {
if (user_stops.user_down[x-1] < user_stops.user_down[x]){
int temp = user_stops.user_down[x-1];
user_stops.user_down[x-1] = user_stops.user_down[x];
user_stops.user_down[x] = temp;
}
}
}
//merges the two separate arrays into one (user_up + user_down = stoppages)
int stoppages[] = new int[user_stops.user_up.length+user_stops.user_down.length];
System.arraycopy(user_stops.user_up, 0, stoppages,0, user_stops.user_up.length);
System.arraycopy(user_stops.user_down, 0, stoppages, user_stops.user_up.length, user_stops.user_down.length);
int c = 0;
do {
System.out.println("The lift has come to stop at floor " + stoppages[c]);
System.out.println("The lift has started moving again.");
c++;
} while (c < stoppages.length);
do {
System.out.println("This lift has stopped moving forever.");
} while (c!=stoppages.length);
}
}
The above method calls this method:
import java.util.*;
public class user_stops {
//user_up array declaration
public static int user_up[] = new int [6];{
//Initialising data in array
user_up[0] = 1;
user_up[1] = 3;
user_up[2] = 2;
user_up[3] = 7;
user_up[4] = 5;
user_up[5] = 8;
}
//user_down array declaration
public static int user_down[] = new int [6];{
//user_down data initialisation
user_down[0] = 8;
user_down[1] = 5;
user_down[2] = 4;
user_down[3] = 2;
user_down[4] = 6;
user_down[5] = 1;
}
}
A:
I want the program to start in main, and call the method that sorts all of the floors and such. However, when I run the program it changes all of the values of the final array into 0's.
The code you have shown us won't even compile. This line is invalid:
floor_sorting.sorting_floors;
We can't explain what a program does if you don't show us the real code.
If you want to make it compile you need to convert your array of String into an array of int. The simple way is to:
allocate an int[] of the right size (i.e. the same size as the String[] args array),
loop over the range of the arrays, and
use Integer.parseInt(String) to convert the values.
Read the javadocs for the Integer class ...
Finally, you need to pay a lot more attention to style:
Your code's indentation is a mess.
You are violating the style rules for identifiers. A class name should start with an uppercase letter, and should use "camel case" not underscores.
Code like the above is hard to read, and will get you endless criticism / complaints from co-workers. (And it should lose you marks if this is a marked assignment.)
A:
To force your code to run, I simply changed the call in main() :
floor_sorting.sorting_floors(new int[]{1,2,3});
The input array is ignored as I mentioned in my comments. However, it does print out nothing but zeros when it runs. (How did you figure that out?)
The reason is your use of static members in user_stops. These being static means they are not being instantiated at any point. This is not obvious unless you realise that even static members of a class will not always be instantiated.
I added the following statement at the top of sorting_floors():
user_stops user_stops_1 = new user_stops();
The program now runs as expected. (Go ahead... try it.) Another thing that might have worked, though I didn't try it, is to initiate the static arrays in the declaration:
public static int user_up[] = new int [] {1, 3, 2, 7, 5, 8};
public static int user_down[] = new int [] {8, 5, 4, 2, 6, 1};
However, I think you should re-think your use of the key-word static if you ever want this program to work properly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unconditional Variance of Normal RV with mean being a NRV
I am trying to find the variance of $X$ which is defined like this:
$$X \sim N(Y,e)$$
where $Y$ is a normal random variable with the distribution $Y \sim N(a,b)$. $a$,$b$, and $e$ are known constants.
How can I go about doing this? I set up an integral like this to get the pdf of $X$:
$$\int_{-\infty}^{\infty}f_{X}(x)f_{Y}(y)\text{ d}y$$
but have no idea how to solve the integral. please help!
A:
Answered my question!
The conditional variance formula:
Var(X) = E[Var(X|Y)] + Var(E[X|Y]) = e + b.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add embedded plugin jar file to a project
I need to add some jar libraries to a project with my plugin by modifying classpath entry. But i can't find a way to do that. I tried to nested jar lib inside the lib folder of my plugin but i can't access them when the plugin is packaged as Jar and deploy on an eclipse IDE.
Any Solution?
What is the right way to do this?
This is the code that add lib to the target project :
private void addLocalLibrary(IProject parent, String name, boolean source, boolean javadoc)
throws CoreException, URISyntaxException, IOException {
IClasspathEntry[] oldEntries = this.javaProject.getRawClasspath();
// +1 for our src/main/java entry
IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
String pluginDir = new File(Activator.getPluginDir()).getAbsolutePath().replace("file:", "");
IPackageFragmentRoot lib = this.javaProject.getPackageFragmentRoot(pluginDir + "/" + name);
IPackageFragmentRoot src = null;
if (source) {
src = this.javaProject.getPackageFragmentRoot((pluginDir + "/" + name).replace(".jar", "-sources.jar"));
}
IClasspathAttribute atts[] = null;
if (javadoc) {
IPackageFragmentRoot doc = this.javaProject
.getPackageFragmentRoot((pluginDir + "/" + name).replace(".jar", "-javadoc.jar"));
atts = new IClasspathAttribute[] {
JavaCore.newClasspathAttribute("javadoc_location", doc.getPath().toString()), };
}
IPath srcPath = src == null ? null : src.getPath();
newEntries[oldEntries.length] = JavaCore.newLibraryEntry(lib.getPath(), srcPath, null, null, atts, true);
this.javaProject.setRawClasspath(newEntries, null);
}
A:
You can create a plugin from the existing library jar and add it to the dependencies of the plugin where you want to use the library code.
To do so, use the Plug-in from existing JAR archives wizard, which is available under File > New > Project... > Plug-in Development > Plug-in from existing JAR archive.
This way you can wrap existing jars in a plugin project. You can also use this plugin as the base for your own code. If you want to package as a single jar, make sure to unzip the library jar into the plugin.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Method doesn't update variable globally?
So, in the beginning of my java class I define globally:
static long world;.
Then I have several functions using world as an argument. One of theses, called setCell does not work as intended, and I can't figure out why. I have tried error searching with println commands, so now my code looks like this:
public static long setCell(long world, int col, int row, boolean newval){
if(col>= 0 && col<8 && row>=0 && row<8){
int bitPosition = col + 8*row;
long newWorld = PackedLong.set(world, bitPosition, newval);
System.out.println(newWorld);
world = newWorld;
System.out.println(world);
return world;
}
else{
return world;
}
}
The main idea of the code is, that it should update world by changing one of its bits with the PackedLong.set method (which is working well) and then return the new updated world.
If we now run:
world =0x20A0600000000000L;
System.out.println(world);
setCell(world, 1, 1, true);
System.out.println(world);
in the main method, we get the following output:
2350984558603665408
2350984558603665920
2350984558603665920
2350984558603665408
From this I have concluded that the commands inside the setCell method works as intended, but that the method does not change world "globally" through the whole code. How can I solve this issue?
Many Thanks! :)
A:
You have the parameter world
public static long setCell(long world, int col, int row, boolean newval)
This will hide the global variable and instead update the parameter. You should avoid names the hide other variables that are present in the same scope. Instead choose a different name for the parameter.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is the sound of the alphabet "j" different in Spanish, English, German and French?
The alphabet "j" is pronounced differently in the following major European languages:
Spanish: justo /ˈxusto/
English: just /d͡ʒʌst/
German: junge /ˈjʊŋə/
French: juste /ʒyst/
How is the sound so varied in these languages?
A:
The reason why the pronunciation is so different is because a phenomenon called phoneme change.
The term is used to design the process from which a language changes their phonetic system over time. It is a universal and inevitable process whereby the languages chance over time and whereby the stages of the language of different periods can develop
intelligibility among them.
Types of changes:
Assimilation: Process where a sound acquires phonetic features which make them more similar to an adjacent
phoneme or a close
phoneme, the
phoneme is "assimilated"
Metathesis: It is the change of place of one or more sounds in the interior of a word. It responds to the need of making the pronunciation easier, like crocodilo ->cocodrilo.
Therefore, the languages you mentioned and asked about have changed over time because of the reasons above.
Note: Language has evolved vastly over time, Spanish of 200 years isn't the same as current Spanish. So if a language in a single country can change so much, imagine how could languages that have the same roots can also vastly evolve; specially when there is a far location among them.
(Bibliography: https://es.wikipedia.org/wiki/Cambio_fon%C3%A9tico , https://prezi.com/2dwuqb5kxl58/cambios-foneticos-morfologicos-y-semanticos/)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I write a function that checks to see if an input is actually an integer? (Javascript)
I recently asked a question titled 'Why is my alert always showing the wrong information? (addition)', in which I was grateful that someone asked my question. However, now, I have another question concerning my calculator Javascript program.
JS:
function activeButton()
{
if (document.getElementById("radioAdd").checked === true)
{
var valueOne = Number(document.getElementById("number1".value));
var valueTwo = Number(document.getElementById("number2".value));
var result = valueOne + valueTwo;
alert("Your Result Is " + result);
}
}
HTML:
<div id="wrapper">
<div id="form-move">
<form name = "calculator" id="calculator">
<div id="numberInput">
<input type="number" name="inputNumber1" id="number1" placeholder="Type or Select Your First Number" />
<input type="number" name="inputNumber2" id="number2" placeholder="Type or Select Your Second Number" />
</div>
<div id="radio-input">
<span class="title">Operators:</span>
<input type="radio" name="radioInputAdd" id="radioAdd" value="Addition" />
<label for="radioAdd">Addition</label>
<input type="radio" name="radioInputAdd" id="radioDivision" value="Division" />
<label for="radioDivision">Division</label>
<input type="radio" name="radioInputAdd" id="radioMultiply" value="Multiplication" />
<label for="radioMultiply">Multiply</label>
<input type="radio" name="radioInputAdd" id="radioSubtract" value="Subtraction" />
<label for="radioSubtract">Subtract</label>
</div>
<div class="submit">
<input type="submit" value="Enter" id="submit" onclick="activeButton()" />
</div>
</form>
</div>
</div>
For the input types named 'inputNumber1' and 'inputNumber2', I want to write a function that allows Javascript to check and see if the input that the user has given is an integer or not. If it is not, the user will be given an alert box and will be told that their input is not an integer and he/she will have to resubmit integers instead into the calculator. If the user has given an integer, it will continue and check and see which radio button has been clicked (as shown in the function above.) Can someone help me how? I've been stuck for ages finding a solution!
A:
ECMA 6 has a proposal for Number.isInteger, which is supported in FireFox 16 and above. Otherwise it can be polyfilled as given on the MDN page
if (!Number.isInteger) {
Number.isInteger = function isInteger (nVal) {
return typeof nVal === "number" && isFinite(nVal) && nVal > -9007199254740992 && nVal < 9007199254740992 && Math.floor(nVal) === nVal;
};
}
This is not the solution though, but it is important information to help you decide about input limits and how to go about validating.
-9007199254740991 and -9007199254740991 are the minimum and maximum safe integers that Javascript can handle. These limits are 16 significant figures, it is usual to limit the input to 15 significant figures to make your check, a RegExp, easy. The user input comes as a string from the DOM.
So: (/^[\-+]?\d{1, 15)$/).test(userInputString)
(can start with a '-' or a '+' (or neither) followed by 1 to 15 digits)
If that is TRUE then you are working with an integer that can be handled by Javascript and so you can safely coerce it to a number (+userInputString or Number(userInputString), or even use parseInt or parseFloat or a Math function)
Anything else and things become more complicated, and could even require the use of an Arbitrary Arithmatic Library like bignumber.js unless you are not working with the number on the client and are sending it as a string to a server to do some work with.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to read 2 lines of integer input in C?
I'm doing a project for my algorithms class and I'm having a lot of trouble with inputs. I'm trying to read an input like this:
6 0 2 3 1 3
5 9 2 1 3
The integers will need to go to
int num1; // num1 = 6
int num2; // num2 = 5
int array1[100]; // array1 = {0, 2, 3, 1, 3, 0, 0, ...}
int array2[100]; // array2 = {9, 2, 1, 3, 0, 0, ...}
The input will come from standard input, in the form of a file. So in terminal running the program would look like this:
cat input.txt | ./a.out
Where input.txt contains the two lines of integers.
Here is my flawed attempt so far:
while(scanf("%d%c", &temp, &ch) > 1){
if (ch != '\n'){
one[count] = temp;
}
else if (ch == '\n'){
count = 0;
two[count] = temp;
}
one[count] = temp;
count++;
if (ch != ' ')
{
printf("Invalid input. Please do int + space.\n");
return -1;
}
if ((temp >= 100) || (temp <= -100))
{
printf("Input is too big, must be between -100, 100.\n");
return -1;
}
if (one[0] < 1){
printf("Input for n cannot be smaller than one!");
return -1;
}
}
I think the main issue is that I'm just not sure how to deal with multiple lines of input. One line of input is fine by me but multiple lines is what trips me over.
A:
You could fetch an entire line of input using the getline function and then iterate over that line, scanning one number at a time using the strtol function.
From the example in your question I assume that you want all remaining entries in the two arrays to be zero so don't forget to zero them out (either manually or using the memset function.).
And also don't forget to free() the buffer getline gave you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to execute a shell script in C?
I'm trying to create a .sh file, write the script to it and then execute it using exec*
So far, I managed to create the file and write the code to it, but the execl doesn't execute the script
int main( int argc, char * argv[] ){
char str[] = "#!/bin/bash \n echo 'Hello World!'";
FILE *fp = fopen("script.sh", "w+");
fwrite(str , 1 , sizeof(str) , fp );
fclose(fp);
execl ("/usr/bin/chmod", "chmod", "+x", "script.sh", (char *)0);
execl ("/export/home/redpal/lab4", "script.sh", (char *)0);
return 0;
}
Should I put each execl in the child proccess?
A:
The execl function (like all exec(3) functions and the execve(2) system call) don't return on success. It would return only on failure.
So your first call:
execl ("/usr/bin/chmod", "chmod", "+x", "script.sh", (char *)0);
is very likely to succeed. Then your current program is gone, and your process is running the /usr/bin/chmod program. Once that program finished (in a few milliseconds), your process exits (and your invoking shell gives a new prompt).
Instead of using the /usr/bin/chmod program you should consider using the chmod(2) system call.
The rest of your program is also wrong. You might want to exec the generated script (but then, you need to give its entire path).
You need to understand how to run processes using fork(2), execve(2), waitpid(2) and friend system calls. We cannot explain how to do that (it is too long), but you should read several chapters of the Advanced Linux Programming book (freely downloadable).
Perhaps you should consider embedding an interpreter like Lua or Guile in your real program (so your question looks like some XY problem)
And you might just use system(3) or popen(3) to run some command.... Perhaps using something like FILE* cmd = popen("/bin/sh", "w"); might be enough .... Then you'll write shell commands to cmd and you need to pclose(cmd)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Changing my array definitions to Vectors or Lists?
According to that question, I'm more and more worried about the management of the memory in my project, and my program would crash when there is somewhere a conflict in one of the array memories.
The different answers to this posted question have converged to the fact that I would change my arrays to Vectors and some of my arrays are defined as below:
#define Nb 50
int position[Nb];
double indication[Nb];
double sum[Nb];
how to change each one of them to
std::vector
std::list?
Can we manipulate / process them when changing their declaration (organizing them in ascending order for example or overwriting one of the values) ?
A:
You are using fixed size arrays,
#define Nb 50
int position[Nb];
the modern C++ alternative to these is std::array, not std::vector:
std::array<int, 50> position;
std::vector is a dynamically sized array, whose size can be determined at runtime and can change after construction.
int n;
std::cin >> n;
std::vector<int> v(n); // vector has n value constructed ints
v.push_back(42); // v has n+1 ints now.
C++14 offers std::dynarray, which is a dynamically sized array, whose size can be determined at runtime but cannot be changed after construction.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I raise an event in a PerlNet module?
I’m using PDK 7.3 as a development tool for developing an application using both .NET and Perl.
I want to build Perl into an .NET compatible dll and this module can raise an event that a .NET GUI application can handle.
I can't find any documentation about it. As far as I know PDK 7.3 does not support implementing delegates.
Is this true? Do I have any options?
A:
I wrote an email to Jan Dubois from ActiveState company. He suggested a way to implement the callback mechanism for it.
Hope this help.
===========================================
Hi Minh,
You can implement a delegate just fine in PerlNET, you just cannot declare new delegate types in it.
I've attached some sample code that defines a delegate in Perl and later passes it to C#. You'll need to separate the pieces into individual files and compile them manually; the code is ripped out of some regression tests and you won't have the rest of the test harness to run it as is. (Looks like the formatting also got chopped a little, but the intend of the code should still be clear).
Cheers,
-Jan
#!./perl -w
# Define some properties and fields in perl and try to access them.
print "1..1\n";
require 'setup.pl';
csc("-target:library DB.cs");
cleanup("DB.dll");
plc(-target => "library", -out => "P.dll", -r => "DB.dll", "P.pm");
csc("test.cs -r:DB.dll -r:P.dll");
cleanup("./test.exe");
my $res = `./test.exe`;
print "----\n$res----\n";
print "not " unless $res eq <<'EOT';
XXX 65
XXX 66
XXX 67
XXX 68
XXX 69
XXX 70
XXX 71
XXX 4.2
XXX 4.30000019073486
XXX 4.4
XXX a
XXX 1
XXX ""
XXX Hi
XXX <undef>
EOT
print "ok 1\n";
__END__
======================= test.cs =====================
using System;
class main : IPrint
{
public static void Main(string[] args)
{
P p = new P(new main());
DataBase db = new DataBase();
db.Add((byte)65);
db.Add((short)66);
db.Add((int)67);
db.Add((long)68);
db.Add((uint)69);
db.Add((ushort)70);
db.Add((ulong)71);
db.Add(4.2D);
db.Add(4.3F);
db.Add(4.4M);
db.Add('a');
db.Add(true);
db.Add(false);
db.Add("Hi");
db.Add(null);
db.Scan(p.handler);
}
main() {}
public void print(string s) {
Console.WriteLine(s);
}
}
======================= DB.cs =====================
using System;
using System.Collections;
public delegate void ProcessItem(Object i);
public class DataBase : ArrayList {
public DataBase() {}
public void Scan(ProcessItem handler) {
foreach (object o in this) {
handler(o);
}
}
}
public interface IPrint {
void print(string s);
}
======================= P.pm =====================
package P;
=for interface
interface ProcessItem; # a delegate type
interface IPrint;
interface System.Object;
interface P {
static P P(IPrint ip);
readonly ProcessItem handler;
void x(System.Object y);
private field IPrint ip;
}
=cut
sub P {
my($self, $ip) = @_;
$self->{ip} = $ip;
}
sub handler {
my $self = shift;
return ProcessItem->new($self, "x");
}
sub x {
my($self, $obj) = @_;
$obj = "<undef>" unless defined $obj;
$obj = '""' unless length $obj;
$self->{ip}->print("XXX $obj");
}
1;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does it anyway matter where you place your global variable in java?
It may be a basic question, but I would like to clear some confusion that I have. Does it in any way matter where you place your global variable? for example;
int globalVariable = 3;
//Some Method here which DOES NOT use the globalVariable
different from:
//Some methods here which don't use the globalVariable
int globalVariable = 3
//Some methods here which use the globalVariable
A:
Relative placement of field declarations inside a class is relevant in two situations:
The field is referenced inside initialization expressions of other fields - in this situation the field being referenced must be declared before the field that references it; otherwise, the code would not compile with "illegal forward reference" error. The above is also true for fields referenced from anonymous initialization blocks placed in front of field's declaration (demo).
Field initializer has side effects - in this situation placing the initializer before or after other initializers changes the order of side effects.
Here is an illustration of the second point:
class Test {
int a = foo("hello");
int b = foo("world");
static int foo(String s) {
System.out.println(s);
return 3;
}
}
The above prints
hello
world
each time a Test object is constructed. If you move the declaration of a to after the declaration of b, the printout would change to
world
hello
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Executor service stop thread waiting for IO
I'm using Apache common library to download page from web
here is the simplified version of the program
public static void main(String[] args) throws InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor(r -> new Thread(r,"second"));
final ExecutorService service = Executors.newFixedThreadPool(2, r -> new Thread(r,"first"));
final Future<Object> submit = executorService.submit(() -> {
final Future<Object> create = service.submit(() -> {
System.out.println("Start");
org.apache.commons.io.IOUtils.copy(new URL("ny_url").openStream(), new FileWriter(new File("create")));
System.out.println("End");
return null;
});
try {
return create.get();
} catch (InterruptedException exc) {
System.out.println("Interrupted");
create.cancel(true);
return null;
}
});
try {
submit.get(3000, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
System.out.println("Timeout");
submit.cancel(true);
System.out.println("HERE2");
}
executorService.shutdown();
service.shutdownNow();
}
As you can see I have two executors , first one download web page and second one is waiting for completion three seconds , if job wasn't able to download page in 3 seconds then main thread sends Interrupt , my second executor catch this exception and call future.cancel(true); finally I shutdown both executors, however , first executor is still working this is the thread dump for it
first" #11 prio=5 os_prio=0 tid=0x00007f18b0002000 nid=0x527d runnable [0x00007f18de08a000]
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
at java.net.SocketInputStream.read(SocketInputStream.java:171)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
at sun.security.ssl.InputRecord.read(InputRecord.java:503)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:975)
- locked <0x00000000d9004a60> (a java.lang.Object)
at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:933)
at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
- locked <0x00000000d9004b20> (a sun.security.ssl.AppInputStream)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:284)
at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
- locked <0x00000000d9006b60> (a java.io.BufferedInputStream)
at sun.net.www.MeteredStream.read(MeteredStream.java:134)
- locked <0x00000000d9006b88> (a sun.net.www.http.KeepAliveStream)
at java.io.FilterInputStream.read(FilterInputStream.java:133)
at sun.net.www.protocol.http.HttpURLConnection$HttpInputStream.read(HttpURLConnection.java:3444)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
- locked <0x00000000d902a040> (a java.io.InputStreamReader)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.Reader.read(Reader.java:140)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:2001)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1980)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1957)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1907)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1886)
at com.devadmin.nma.downloader.TestExecutor.lambda$null$2(TestExecutor.java:17)
So I assume that first executor's job doesn't know anything about interrupt because it's waiting for IO, the question is , Apache commons doesn't check for Thread.isInterrupted while copying stream , is it possible to stop this thread without changing the library , thank you
A:
I read this blog https://techblog.bozho.net/interrupting-executor-tasks/
which gave my an idea how to do it
Here is how my program looks now
ExecutorService executorService = Executors.newSingleThreadExecutor(r -> new Thread(r, "second"));
final ExecutorService service = Executors.newFixedThreadPool(2, r -> new Thread(r, "first"));
final InputStream inputStream = new URL("https://ep.t8cdn.com/201804/17/47295201/mp4_ultra_47295201.mp4?validfrom=1586656571&validto=1586663771&rate=94k&burst=1600k&ip=66.183.216.58&hash=FXdFmkw14K1PuL9lc8GzOjzcaeI%3D").openStream();
final Future<Object> submit = executorService.submit(() -> {
final Future<Object> create = service.submit(() -> {
System.out.println("Start");
IOUtils.copy(inputStream, new FileWriter(new File("create")));
System.out.println("End");
return null;
});
try {
return create.get();
} catch (InterruptedException exc) {
System.out.println("Interrupted");
create.cancel(true);
inputStream.close();
return null;
}
});
try {
submit.get(3000, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} catch (TimeoutException e) {
System.out.println("Timeout");
submit.cancel(true);
System.out.println("HERE2");
}
executorService.shutdownNow();
service.shutdownNow();
What I did is I created stream before submitting it to the first executor and I closed in in the second executor
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Asp.NET entity Framework. How to automatically generate primary key?
Problem :
If I make STOREGENERATED PATTERN = NONE Record is inserted in my database once with ID =0. After that it gives error so I change it to identity
I wanted to automatically generate primary key. I created a new project made it Identity
public partial class USER
{
[key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string NAME { get; set; }
}
Controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(USER obj)
{
using( var db = new Entities() )
{
var u = new USER();
u.NAME = obj.NAME;
db.USERS.Add(u);
db.SaveChanges();
}
return View();
}
ERROR!
I search on the internet but could not make it work.
--> I want my project to automatically create Primary key of tables. I am using Oracle SQL database and Entity framework 5.0.0
A:
You've changed the EDMX, but that's just a model of your database. It doesn't change the database by itself.
Configure the column so it actually is generated by the server: How to create id with AUTO_INCREMENT on Oracle?.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Running into an error when trying to implement Keras
I'm using Python 2.7, Windows 7, and Keras 1.2.1 (Keras2 seems to be having a lot of compatibility issues with different PC/Python configs, so I was recommened to use 1.2.1)
I'm using a script from Practical Deep Learning For Coders, Part 1 Course
import utils; reload(utils)
from utils import plots
The error I"m getting is as below
Problem occurred during compilation with the command line below:
"g++" -shared -g -DNPY_NO_DEPRECATED_API=NPY_1_7_API_VERSION -m64 -DMS_WIN64 -I"c:\python27\lib\site-packages\numpy\core\include" -I"c:\python27\include" -I"c:\python27\lib\site-packages\theano\gof" -L"c:\python27\libs" -L"c:\python27" -o C:\Users\Moondra\AppData\Local\Theano\compiledir_Windows-7-6.1.7601-SP1-Intel64_Family_6_Model_94_Stepping_3_GenuineIntel-2.7.12-64\lazylinker_ext\lazylinker_ext.pyd C:\Users\Moondra\AppData\Local\Theano\compiledir_Windows-7-6.1.7601-SP1-Intel64_Family_6_Model_94_Stepping_3_GenuineIntel-2.7.12-64\lazylinker_ext\mod.cpp -lpython27
I can't decipher what this means. Google search brought up a Chinese message board.
It seems to be a g++ problem as the previous warning I got was as follows:
WARNING (theano.configdefaults): g++ not available, if using conda:conda install m2w64-toolchain``. Despite installing m2w64-toolchain afterwards, I was continuing to get the same warning.
A:
I solved the problem.
I reinstalled Anaconda.
And then via command line I wrote conda install m2w64-toolchain
This time I didn't get a message stating that m2w64 was already installed. I'm assuming it was a path issue and this time reinstalling everything from the start also created a new path?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Global variable is not updating in python
I have 3 files.
globalVar.py
global m_pTest
m_pTest = None
FileOne.py
import globalVar
import fileTwo
m_pTest = Class.getOutput() # Value is assigne
fileTwo.fun()
#Do anything
fileTwo.py
import globalVar
def fun():
intVal = m_pTest.getInt() # int value from m_pTest object
print intVal
This is my short program sample when i run this it gives error in fileTwo.py in fun()
AttributeError: 'NoneType' object has no attribute 'getInt'
Can someone explain what is wrong in this code ?
Thank you!
A:
global m_pTest doesn’t make a variable magically global; instead it sets the name m_pTest in the current scope to refer to a global variable (from outer scope). So placing it in globalVar.py does basically nothing.
If you wanted to import only the variable, you could use the following:
from globalVar import m_pTest
However, when setting m_pTest to a different value, you will not affect the original object that was created in globalVar.py so the change isn’t seen elsewhere.
Instead, you have to import globalVar as normal, and then refer to m_pTest as a member of that module:
import globalVar
# reading
print(globalVar.m_pTest)
# setting
globalVar.m_pTest = 123
A:
Why using a global at all ?
# FileOne.py
import fileTwo
value = Class.getOutput()
fileTwo.fun(value)
#Do anything
# fileTwo.py
def fun(value):
intVal = value.getInt()
print intVal
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Modern Traditionalist Scholars Combatting Critical Approaches to the Tanach
I know that Shadal, David Hoffman, and many others tried very hard to combat the claims of scholars that criticized the Torah (both in terms of Higher and Lower Criticism). Can anyone help me find other modern scholars that did similar work for my Bible class? We are specifically studying the 5 Megillot, and thus we are studying: Solomon's authorship of Kohelet, a literal reading of Shir HaShirim, and more. Therefore I am seeking your help for finding:
1) modern traditionalist scholars that combat Biblical Criticism of the 5 Megillot (it would be great if I could also be pointed to where they talk about this in their works)
2) issues that Biblical Critics deal with in the 5 Megillot
A:
For Megillas Esther specifically, R. Y.I. Halevi (Doros Harishonim, Tekufas Hamikra, pp. 262ff) offers several proofs that it was indeed written in the Persian era and not later. (He also discusses the relationship of the end of ch. 9, which describes the writing of the Megillah and the establishment of the holiday of Purim, to the rest of the book.)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I trim the display of text and expand with "more" link?
On my user profile page I have a "about me" text field that can get pretty long.
I would like to only show about 200 characters of text with a "more" link.
When you click more it would show the rest of the text, ideally on the same page.
A:
Look, up in the sky. It's a bird. It's a plane. It's...... sorry. This is a job for jQuery. A quick google of "jquery more less toggle" (without the quotes lol) will show lots of examples.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Single-boot vs dual-boot
Will a single-boot install run any better than a dual-boot?
Running Ubuntu-mate (16.04 beta 64bit) alongside Vista. 2GB ram, Athlon 64 x2 5200+. Ubuntu is running fine. (Better than Vista, actually.) But only using a sliver of disk space thanks to years of running Vista.
A:
A Single boot install is not going to affect the performance of the currently running instance of OS. While running your OS, the other partitions are read as storage like it would read a usb stick.
p.s. Vista is known for heavy RAM memory usage (1-1.5Gb OS alone) so you are right, you should be experiencing better performance on Ubuntu as it it less demanding.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Save data in JSON file
I am missing something in below code, not able to save in correct format, Can you please guide where I'm going wrong...
Python Code
str_next_thursday_expiry = 23JUL2020
f = open("data/expiry.json","r")
with open("data/expiry.json", "w") as f:
json.dump(str_next_thursday_expiry, f)
Output in expiy.json
"23JUL2020"
I want to store this in below format, not getting what needs to be corrected..
{"expirydate": "23JUL2020"}
A:
str_next_thursday_expiry = "23JUL2020"
with open("data/expiry.json", "w") as f:
data = {"expirydate":str_next_thursday_expiry}
json.dump(data, f)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Quick question about Arrow operators
Say I've got f :: u -> v -> w and g :: x -> y -> z. What I want is h :: (u,x) -> (v,y) -> (w,z).
So I could go about this manually:
h (u,x) (v,y) = (f u v, g x y)
But where's the fun in that?
Using (***) I can get partway there:
(f *** g) :: (u,x) -> (v -> w, y -> z)
But I can't figure out how to get that final mile.
A:
(***) :: (Arrow a) => a b c -> a b' c' -> a (b, b') (c, c')
So specialize a to -> and we get:
(***) :: (Arrow a) => (b -> c) -> (b' -> c') -> (b, b') -> (c, c')
And that's great, except we want to, for whatever reason, take the first two arguments as a single pair instead. But that's easy, we just uncurry.
Prelude Control.Arrow> :t uncurry (***)
uncurry (***) :: (Arrow a) => (a b c, a b' c') -> a (b, b') (c, c')
And if you specialize the a again, you should see the type signature you were looking for.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Когда надо использовать use для namespace?
Заметил что Шторм выдаёт информацию что use не имеет эффекта никакого:
Почитал доку http://php.net/manual/ru/language.namespaces.importing.php но так и не понять в каком случае ничего не нбудет работать без use как алиас понятно его можно использовать что бы сократить длинное имя. В обычном случае когда делаю $obj - new \Model\MyClass(); непонятно
A:
Допустим у вас есть класс
namespace Model;
class MyClass{
.....
Тогда в другом пространстве имен для использования этого класса вам придется либо использовать полное имя класса(с его пространством имен), либо можно использовать use Model\MyClass; и после этого, при обращении к классу, пространство имен не писать.
Т.е. или так
use Model\MyClass;
$myClass = new MyClass();
или так
$myClass = mew \Model\MyClass();
Эти два варианта использования абсолютно равнозначны.
UPD если у вас в двух пространствах имен присутствуют классы с одинаковым именем, то при попытке использовать и тот и тот PHP выдаст fatal error.
sandbox
UPD Обратите внимание, что при использовании полного имени класса, если перед пространством имен не поставить \("корневое" пространство имен), то имя будет считаться относительно текущего пространства имен.
Т.е. вот тут
namespace C;
$a = new B\A();
Будет считаться, что вы написали так:
namespace C;
$a = new \C\B\A();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to do recursive select in PostgreSQL with array as an argument
I am trying to implement easy recursive function in PostgreSQL but I cannot finish it...
I have got table MyTable which includes columns Col1 and Col2. Data inside is like this:
Col1 | Col2
1 | 2
2 | 5
2 | 6
3 | 7
4 | 5
4 | 2
5 | 3
I would like to write a function which takes as a parameter array of Col1 f.e. (1,2) and gives me back values from Col2 like this :
1 | 2
2 | 5
2 | 6
and after that, does it again with results : (2, 5, 6)
so:
1 | 2
2 | 5
2 | 6
5 | 3
(2 is already in, and key '6' does not exist)
and again (3):
1 | 2
2 | 5
2 | 6
5 | 3
3 | 7
and for (7) nothing because value '7' does not exist in Col1.
It is an easy recursion but I have no idea how to implement it. I have got so far something like this:
with recursive aaa(params) as (
select Col1, Col2
from MyTable
where Col1 = params -- I need an array here
union all
select Col1, Col2
from aaa
)
select * from aaa;
But it of course does not work
Thanks in advance
A:
The basic pattern for recursion is to have your base case as the first part of the union and in the second part join the recursion result to what you need to produce the next level of results. In your case it would look like this:
WITH RECURSIVE aaa(col1, col2) AS (
SELECT col1, col2 FROM mytable
WHERE col1 = ANY (ARRAY[1,2]) -- initial case based on an array
UNION -- regular union because we only want new values
SELECT child.col1, child.col2
FROM aaa, mytable AS child -- join the source table to the result
WHERE aaa.col2 = child.col1 -- the recursion condition
)
SELECT * FROM aaa;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why curl can't expand variable inside the loop, but echo can?
I need to include variable inside curl
for fname in "assets/*.drx"; do
echo $fname
curl -F file=@"$fname" "http://someurl.com/"
echo $fnamename
done
Result:
assets/5baa5caa414f1d7786e86d03_1545903119.11.drx
curl: (26) couldn't open file "assets/*.drx"
assets/5baa5caa414f1d7786e86d03_1545903119.11.drx
It seems curl uses glob expression, but echo uses actual filename. Why does curl behave like this? Why does echo see the actual variable and how can I use the filename inside curl?
A:
You've quoted the * wildcard, preventing the shell from expanding it.
for fname in assets/*.drx; do
printf '%s\n' "$fname"
curl -F file=@"$fname" "http://someurl.com/"
done
The fname variable was assigned the literal text assets/*.drx. When you used it unquoted in the echo, the shell dutifully expanded it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to iterate list inside hashtable key with javascript
I have a list of strings (List) that I populated with pictures(in my code-behind). Then I store it in a Hashtable with a key of "sbPrints" which then gets returned to the ajax call.
However I don't know how to iterate the list inside that specific key in javascript.
the hastable containing the list in javascript looks like this : h['sbPrints'].
the reason I'm asking about this is because if I just do
$('#prints').val(h['sbPrints']);
then I end up with unwanted commas in between each picture.
EDIT:how the hashtable gets populated
iny my code-behind:
[WebMethod]
public static Hashtable getPersonInfo(int personID)
{
Hashtable h = new Hashtable();
SqlDataReader drThumbs;
drThumbs = comGetThumbs.ExecuteReader();
List<string> fingerPrints = new List<string>();
while(drThumbs.Read())
{
fingerPrints.Add("<div class=\"fingerprints\"><img alt='prints' src='../ShowThumbnail.ashx?BFID=" + drThumbs["BinaryFileID"].ToString() + "'/><div><label><a class=\"finger\" href='../DownloadFile.aspx?id=" + drThumbs["BinaryFileID"].ToString() + "'>" + drThumbs["FileName"].ToString() + "</label></div></div>");
}
}
Then in my javascript file I make an ajax call to the the method and populate my
asp controls with the data from the hashtable.
A:
I don't quite understand what you mean, but how about this:
$.each(h['sbPrints'], function(i, v) {
$('#prints').val(v);
});
This will iterate through every item in h['sbPrints'] and pass them to your prints selector's jQuery value function. I don't really know why you would want to do this, as $.each will replace the value in each iteration.
Perhaps what you mean is that h['sbPrints'] is an array and when it's stringified, your browser will insert commas between the items. If you just want the list without commas, then you can do this:
$('#prints').val(h['sbPrints'].join(''));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Aurelia - value converter using promise
I need to format Date using format returned by promise. I tried returning promise from toView(value). But that doesn't work.
@autoinject
export class DateTimeValueConverter {
constructor(private formatService:FormatService) {
}
toView(value) {
return this.formatService.getFormat().then(format=>
moment(value).format(format)
);
}
}
Here's FormatService's code, which works properly
export class FormatService {
private format;
constructor(private http:AppHttp) {
this.format= null;
}
public getFormat() : Promise<string>{
if (this.format){
var promise = new Promise<string>((resolve, reject)=>{
resolve(this.format);
});
return promise;
}
return this.http.get('format')
.then((format) => {
if (format){
this.format= format;
}
return format;
});
}
}
A:
As far as I know, you cannot use async functionality within value converters. One solution I see, is to pass the format as a parameter from the viewmodel to the value converter (through the view). But this means you need to fetch the format within the viewmodel, which kind of destroys the whole point of value converters...
Another solution I see, is to adjust FormatService so that it caches the format (assuming that 'format' doesn't change often). This way, the getFormat function will be synchronous and you can use it within the value converter. Of course, you will need to find a way to initialize format within FormatService before any value converters are called.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to add two float fields with different currency sign?
We have already Amount field on invoice lines which shows the amount in the currency selected on invoice. I want to convert the same amount to base currency and also show the base currency amount on invoice lines with base currency symbol.
A:
For this purpose I have added new many2one field for base currency as show below:
base_currency_id = fields.Many2one('res.currency', default=lambda self: self.invoice_id.company_id.currency_id.id)
Then I added new float field for computing the amount in base currency like this:
@api.onchange('price_subtotal', 'invoice_id.currency_id')
def compute_amount_in_base_currency(self):
company_currency = self.invoice_id.company_id.currency_id
for l in self:
amount_in_base = l.currency_id.compute(l.price_subtotal, company_currency)
l.amount_in_base = amount_in_base
amount_in_base = fields.Float('Base Amount', readonly=True, compute='compute_amount_in_base_currency')
In xml file I have added base_currency_id field and made it invisible. Then added amount_in_base field to the view with widget='monetary' and options="{'currency_field': 'base_currency_id'}". My xml file looks like this:
<xpath expr="//field[@name='invoice_line_ids']/tree/field[@name='price_subtotal']" position="after">
<field name="base_currency_id" invisible="True"/>
<field name="amount_in_base" widget="monetary" options="{'currency_field': 'base_currency_id'}"/>
</xpath>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using gSoap in Qt/Windows
I followed the steps on gSoap's page and tried to run the example code in Qt/Windows with Mingw32 Compiler. However, I can't add lgsoap++ to linker, as stated in the documentation, since it is not in the source package
To complete the build, compile and
link the generated soapC.cpp,
soapcalcProxy.cpp, and the run-time
gSOAP engine -lgsoap++ (or use source
stdsoap2.cpp in case libgsoap++.a is
not installed) with your code.
Then I tried adding stdsoap2.cpp to SOURCES and this is the compile output as a result. So my question is how I will run this example code snippet in Qt with Mingw32 compiler or how I will generate that lgsoap++. Followings are my pro and source files:
QT -= gui
TARGET = SoapCalc
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
../Console/gsoap/stdsoap2.cpp
OTHER_FILES += ../../../../../gsoap/gsoap-2.7/gsoap/calc.nsmap
HEADERS += ../../../../../gsoap/gsoap-2.7/gsoap/soapcalcProxy.h
#include"C:/gsoap/gsoap-2.7/gsoap/soapcalcProxy.h"
#include"C:/gsoap/gsoap-2.7/gsoap/calc.nsmap"
int main(int argc, char *argv[])
{
calcProxy service;
return 0;
}
A:
Finally, I have resolved it.
Follow the guidelines on the gSoap's page. Add the following files to your project: generated *.cpp, *.h, *.nsmap, service definition file - the name of which you type on command line e.g. calc.h in the guideline - and stdsoap2.h/cpp files in the gsoap directory of the downloaded zip file. After including proxy file -e.g. soapcalcProxy.h - and *.nsmap to your main file there remains one thing that
I forgot to realize before:
add LIBS += C:\MinGW\lib\libws2_32.a to your *.pro file. libws32_a is the current version of the deprecated libwsock32.a file.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Infinite Sum without using $\sin\pi$
What's a purely algebraic way to prove that $\pi-\frac{\pi^3}{3!}+\frac{\pi^5}{5!}-\dots=0$? I'm sure that the first step is to write $\pi=4-\frac43+\frac45-\dots$, but I haven't been bold enough to complete the algebra, nor do I think it is feasible. :(
I guess in general, what's the algebraic way to prove that the Taylor series of $\sin x$ converges to the geometric definition of $\sin x$?
A:
Not sure about an "algebraic proof." A direct power series substitution using the power series for $\arctan$ would need to give you:
$$\sin(4\arctan(x))=\frac{4x(1-x^2)}{(1+x^2)^2}=\frac{8x}{(1+x^2)^2}-\frac{4x}{1+x^2}=4\sum_{n=0}^{\infty}(-1)^n(2n+1)x^{2n+1}$$
That's gonna be messy but not necessarily impossible to show. Note the series does not converge when $x=1$, but arguments can be made as $x\to 1-$.
The key to the second part is to prove that $\exp(ix)=\cos x + i\sin x$, where $\exp(z)=\sum_k z^k/k!$. One way to prove this is to show that $f(x)=1+ix$ is "close enough" to $\mathrm{cis}(x)=\cos x + i\sin x$ when $x$ is near zero so that $\lim f(x/n)^n = \lim \mathrm{cis}(x/n)^n$. But you can prove that $\mathrm{cis}(x/n)^n=\mathrm{cis}(x)$ by induction, and to show that $\lim_{n\to\infty} f(x/n)^n = \exp(ix)$.
The "close enough" part of the proof - that $\mathrm{cis}(x)=1+xi + o(x)$ - can be made geometric.
Here's an answer to another question that covers how close "close enough" needs to be to get this result.
Outline of the geometric part of the proof
First show that $\sin x<x$ for $x$ positive, since $\sin x$ is the shortest distance from a point $(\cos x,\sin x)$ to the $x$-axis, and $x$ is the distance from the same point along the circle.
Then show that $1-\cos x =\frac{\sin ^2 x}{1+\cos x}<\sin^2 x<x^2$.
The last step is harder - showing that $x-\sin x$ is "small enough." It requires a theorem about convex sets - the shortest path between two points on the surface of a convex set which never enters the interior must lie entirely on that convex set. This is sort of intuitive.
From that geometric result, you can show that $\tan x > x$, and hence that $x-\sin x < \tan x - \sin x < \sin x\frac{1-\cos x}{\cos x} = o(x)$ when $x$ near zero.
More on algebraic approach
The power series approach is going to be brutal. Let's just try the case $\sin 2\arctan x = \frac{2x}{1+x^2}=2\sum_{n} (-1)^n x^{2n+1}$.
Now, for $k$ odd, the contribution of $\arctan^k x$ to the coefficient $x^n$ in $\sin 2\arctan x$ is in terms of the set $P_{n,k}=\{(n_1,\dots,n_k)\mid n_i\text{ odd, } \sum n_i=n\}$. The contribution of $(n_1,\dots,n_k)$ is $$\frac{(-1)^{(k-1)/2}4^k}{k!}\prod_i \frac{(-1)^{(n_i-1)/2}}{n_i} = \frac{(-1)^{(n-1)/2}4^k}{k!\prod n_i}$$
Basically, you need that:
$$\sum_{n_1+\cdots + n_k=n} \frac{4^{k-1}}{k!n_1n_2\cdots n_k} = n$$
where the $n$ is odd and the sum is over partitions under the condition that each $n_i$ is odd.
It's not at all clear how summing these is even going to be an integer.
It's easy to verify for small $n$. $n=1$ is trivial. For $n=3$, the partitions are $(3)$ and $(1,1,1)$ which gives $\frac{1}{3}+\frac{4^2}{6}=3$. For $n=5$, the partitions are $(5),(3,1,1),(1,3,1),(1,1,3),(1,1,1,1,1)$ and you get:
$$\frac{1}{5} + 3\cdot \frac{4^2}{3!\cdot 3} + \frac{4^4}{5!}=5$$
An interesting fact is that this equality seems to be true for $n$ even, as well (still with the condition that the $n_i$ are odd.) I wonder if there is a probability explanation for this - some process for choosing partitions of $n$ into odd integers where the probability of getting $(n_1,\dots,n_k)$ is $\frac{4^{k}}{n k!n_1\dots n_k}$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to find all words that match a regex?
This might have been asked before, but, I am unable to find a solution. Suppose my text is 'C:\\Windows\\system32\\cmd.exe /v /c hello cmd.exe' and I want to find and remove all words that has the regex r'cmd.exe'. The result must be: '/v /c hello'.
This is what I tried: First, I tried to find the indices of the words-boundaries so that I can remove them. But, the indices I got was for the exact regular-expression...not for the whole matching word.
In [41]: [(m.start(0), m.end(0)) for m in re.finditer(r'\b\w*cmd.exe\w*\b', cmd)]
Out[41]: [(20, 27), (40, 47)]
In [42]: [(m.start(0), m.end(0)) for m in re.finditer(r'cmd.exe', cmd)]
Out[42]: [(20, 27), (40, 47)]
In [44]: result = re.findall(r'cmd.exe', cmd, re.I)
In [45]: result
Out[45]: ['cmd.exe', 'cmd.exe']. <-- I wanted ['C:\\Windows\\system32\\cmd.exe', 'cmd.exe']
In [48]: result = re.findall(r'cmd.exe|\bcmd.exe\b', cmd, re.I)
In [49]: result
Out[49]: ['cmd.exe', 'cmd.exe']
In short, how to get the whole word(s) that contains the substring/regex?
A:
Not saying regex is bad*, but why not simply:
txt = 'C:\\Windows\\system32\\cmd.exe /v /c hello cmd.exe'
outcome = ' '.join([part for part in txt.split(' ') if not 'cmd.exe' in part])
which gives:
'/v /c hello'
*Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Google Earth Questions: Making Outside Pages Appear in Google Earth and A Button That Follows
Good morning, eveyrone
I'm working on an application using Google Earth and I had two questions.
The first question involves the pop up window. I want to get an external website to appear in this bubble. I can either hardcode the website into the description of the placemark or use an iFrame. Are there any other options I can use to get a website into Google Earth?
Second question: I want to ensure that the user, at all times while using my kml, has access to certain buttons. Is there a way without querying web application every few seconds to ensure that the button remains available to the user?
Thank you for your time.
A:
The answer to you first question is no - other than loading the html directly or using an IFRAME there is no way to display markup in the content balloons.
I am not sure what you mean in you second question, are you developing a web-based application using the Google Earth Plugin - or a kml layer for use in the google earth application. Either way you should not have to query anything to make sure a button is visible.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL One-To-Many join issue
Let's say I have two tables in Access. TableLetters and TableNumbers. TableLetters has one column TheLetter and 4 records, A, B, C, & D. TheNumbers is many for one TableLetters record. Say we have two columns in TheNumbersTable [TheLetter][TheNumber]. See below:
TheLetters
[TheLetter]
A
B
C
D
TheNumbers
[TheLetter][TheNumber]
A 1
A 2
A 3
B 1
B 2
How do I write a query that returns one record for each "TheLetters" record and the MAX "TheNumber" from TheNumbers table or blank if there's no match for TheLetter in TheNumbers table? So I want my result set to be:
[TheLetters.TheLetter][TheNumbers.TheNumber]
A 3
B 2
C <NULL>
D <NULL>
I can get A,3 - B,2 but it cuts out C & D because there's not a match in TheNumbers. I've tried switching my joins all around. I've tried putting an IF in the WHERE clause that says if we have a match return the record from TheNumbers or else give me blank. I can't seem to get the syntax right. Thanks for any help!
A:
The key is to use a LEFT JOIN:
SELECT l.TheLetter, MAX(n.TheNumber)
FROM TheLetters l
LEFT JOIN TheNumbers n ON l.TheLetter = n.TheLetter
GROUP BY l.TheLetter
A left outer join returns all rows in the left table, returning data for any correlated rows in the right table, or a single row with the right table's columns set to NULL if there are no correlated rows.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Running multiple map tasks in parallel
I am using hadoop 2.0. When I alter the number of map tasks using job.setNumMapTasks, the number is as expected (in the number of sequence files in the output folder and the number of containers), but they do not run in parallel, but only 2 at a time. For instance, when I set the number of map tasks to 5, its like 2 of them executed first, followed by 2 more, followed by 1. I have an 8-core system and would like to utilize it to the fullest. A bit of online hunting (including StackOverflow) seemed to suggest a few things and I tried the following:
Adjusted the parameter "mapred.tasktracker.map.tasks.maximum" in mapred-site.xml to set the number of tasks running in parallel. I set it to 8.
Reduced the parameter, "mapred.max.split.size". My input sequence file size is 8448509 or approximately 8 MB. Hence I set it to 2097152 (2 MB).
Lowered the DFS block size, "dfs.block.size in dfs-site.xml. I learnt that the block size by default is 64MB. I lowered it to 2097152 (2 MB).
In spite of all this, I do not see any change in performance. Its still 2 map tasks at a time. I did not format my hdfs and reload the sequence file after 3. Not sure if that is the reason though.
You can access my configuration files at https://www.dropbox.com/sh/jnxsm5m2ic1evn4/zPVcdk8GTp. Am I missing something here?
Also, I had another question. Some posts seem to mention that job.setNumMapTasks is just an indicator to the environment and the actual number is decided by the environment. However, I always find the number of tasks as whatever I specify. Is that expected?
Thanks and Regards,
Samudra
A:
In classic mapreduce framework(MR1) you can set the number of map slots by using the propertymapred.tasktracker.map.tasks.maximum. But in YARN, things are different. See the below discussion on map/reduce slots in YARN
https://groups.google.com/a/cloudera.org/forum/#!topic/cdh-user/J564g9A8tPE
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how can i have a right alignment menu fill top in WPF
I’m new in WPF. I want a right alignment menu. But when set horizontalalignment property to right, it don’t fill the whole width of row. I use horizontalcontentalignment as stretch but it does’nt work. This is my code:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition Height="*" />
<RowDefinition />
</Grid.RowDefinitions>
<DockPanel Grid.Row="0" Grid.Column="0" HorizontalAlignment="Right">
<Menu DockPanel.Dock="Top" >
<MenuItem Header="_File"/>
<MenuItem Header="_Edit"/>
<MenuItem Header="_Help"/>
</Menu>
</DockPanel>
</Grid>
What is displayed is as below:
-----------------------------
File edit help |
-----------------------------
But I want to be:
---------------------------------
Help edit file|
--------------------------------
How can I get menu fill top and set it’s alignment to right?
A:
You can do something like that:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="60" />
<RowDefinition Height="*" />
<RowDefinition />
</Grid.RowDefinitions>
<Menu Grid.Row="0" Grid.Column="0" HorizontalAlignment="Stretch">
<Menu.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel HorizontalAlignment="Right" Orientation="Horizontal" VerticalAlignment="Top" />
</ItemsPanelTemplate>
</Menu.ItemsPanel>
<MenuItem Header="_File" />
<MenuItem Header="_Edit"/>
<MenuItem Header="_Help"/>
</Menu>
</Grid>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
JQuery Looping Hide/Show
I'm creating a dashboard site with drill down capabilities using +/- icons to hide/show categories/subcategories/subsubcategories etc.
I'm trying to make the site dynamically driven so that regardless of the number of categories/subcategories, the script will function without knowing its exact ID.
I know just enough about JQuery to be dangerous and I'm unfortunately under a time crunch and was hoping an expert may be able to point me in the right direction.
I have X Categories, each with X Subcategories, each with X SubSubCategories. The Categories and Subcategories need to have the ability to be toggled on/off to hide/show whatever is under them.
I'd like to be able to use the following code to handle any Category/Subcatery hide/show functionality dynamically. All of my data to populate the dashboard will be coming from a database and new categories/subcategories could be added at any time.
Any Ideas?
$(document).ready(function(){
$(".subsub").hide();
$(".subsubsub").hide();
$("#togglecat1").click(function(e)
{
e.preventDefault();
if($("#HScat1").attr("src") == "filter_hide.gif"){
$("#HScat1").attr("src", "filter_reveal.gif"); }
else{ $("#HScat1").attr("src", "filter_hide.gif"); }
$(".cat1").toggle();
$(".subsubsub").hide();
$("#HScat1sub1").attr("src", "filter_hide.gif");
$("#HScat1sub2").attr("src", "filter_hide.gif");
$("#HScat1sub3").attr("src", "filter_hide.gif");
});
$("#togglecat1sub1").click(function(e)
{
e.preventDefault();
if($("#HScat1sub1").attr("src") == "filter_hide.gif"){
$("#HScat1sub1").attr("src", "filter_reveal.gif"); }
else{ $("#HScat1sub1").attr("src", "filter_hide.gif"); }
$(".cat1sub1").toggle();
});
$("#togglecat1sub2").click(function(e)
{
e.preventDefault();
if($("#HScat1sub2").attr("src") == "filter_hide.gif"){
$("#HScat1sub2").attr("src", "filter_reveal.gif"); }
else{ $("#HScat1sub2").attr("src", "filter_hide.gif"); }
$(".cat1sub2").toggle();
});
$("#togglecat1sub3").click(function(e)
{
e.preventDefault();
if($("#HScat1sub3").attr("src") == "filter_hide.gif"){
$("#HScat1sub3").attr("src", "filter_reveal.gif"); }
else{ $("#HScat1sub3").attr("src", "filter_hide.gif"); }
$(".cat1sub3").toggle();
});
$("#togglecat2").click(function(e)
{
e.preventDefault();
if($("#HScat2").attr("src") == "filter_hide.gif"){
$("#HScat2").attr("src", "filter_reveal.gif"); }
else{ $("#HScat2").attr("src", "filter_hide.gif"); }
$(".cat2").toggle();
});
});
JsFiddle
A:
Using a combination of classes, data attributes, and jQuery selectors, this below code can dynamically create sublevels automagically (even though they are in actuality siblings) and functions to enable them to be manually expanded/contracted.
I put together this demo (jsFiddle). Here is the js:
$(function () {
var hide_src = "http://www.synchronizeddesigns.com/filter_hide.gif",
reveal_src = "http://www.synchronizeddesigns.com/filter_reveal.gif";
$('[class^="sub"]').hide();
$('.category, .sub').each(function () {
if ($(this).next('[class^="sub"]').length > 0) {
$(this).addClass("expandable")
.find('td:first')
.prepend('<img class="pre plus" src="' + hide_src + '" />');
}
});
$('.expandable').on('click', function (e) {
e.stopImmediatePropagation();
var $t = $("#" + e.delegateTarget.id),
$i = $($t).find('img');
var $s = $i.attr('src') == hide_src ? reveal_src : hide_src;
$i.attr("src", $s);
var $l = $t.parent()
.find("[data-parent='" + e.delegateTarget.id + "']")
.fadeToggle();
var subs = $('#' + e.delegateTarget.id +
'~ tr[data-parent^="' + e.delegateTarget.id + '_"]');
if (subs.is(':visible')) {
subs.fadeOut();
$i = $($l).find('img');
$s = $i.attr('src') == hide_src ? reveal_src : hide_src;
$i.attr("src", $s);
}
});
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Allow Java method arguments to accept constructor paramaters
I'm trying to optimize a section of my code which requires an object array with constructor parameters in it. Is there a way to add that to the arguments of a method?
I have an array of objects called SongList in that array there are objects from the Song Class with constructor parameters:
songs[] songList = new songs[1];
songList[0] = new songs("Danger Zone", "danger zone.mp3", "Kenny Loggins", 3.33);
I also have a method that searches the array based on the category and the search query:
//Method
public static songs[] search(songs SearchCategory , String Quarry){}
//Calling of method
search = AudioPlayer.search("aName", "Kenny Loggins");
Songs class:
public class songs {
String sName;
String fPath;
String aName;
double sLength;
public songs(String songName,
String filePath,
String Artist,
double songLength) {
sName = songName;
fPath = filePath;
aName = Artist;
sLength = songLength;
}
}
Is there a way I could make the first argument of the code accept a constructor parameter like Name? This would allow me to cut down the overall length of my code as I wouldn't need to use a switch statement.
Search method:
public static songs[] search(String SearchCategory , String Quarry){
//Returned array value
songs[] ReturnedResult = new songs[0];
// Method only list
List<songs> SearchResult = new ArrayList<songs>();
switch (SearchCategory) {
case "aName":
//for loop looks through all objects with the SearchCategory and places any found values into the list
for (songs songs : AudioListing) {
if (songs.aName.equals(Quarry)) {
SearchResult.add(songs);
}
}
case "sName":
for (songs songs : AudioListing) {
if (songs.sName.equals(Quarry)) {
SearchResult.add(songs);
}
}
case "fPath":
for (songs songs : AudioListing) {
if (songs.fPath.equals(Quarry)) {
SearchResult.add(songs);
}
}
case "sLength":
//Since the given quarry is a string and the length is a double the quarry is converted
double QuarryDoubleTypeC = Double.parseDouble(Quarry);
for (songs songs : AudioListing) {
if (songs.sLength == QuarryDoubleTypeC) {
SearchResult.add(songs);
}
}
}
// Conversion of list to array for ease of use
ReturnedResult = SearchResult.toArray(ReturnedResult);
return ReturnedResult;
}
A:
There is a concept of reflection in Java that you can use here.
You can use the SearchCategory to get the field value from the object
Then you can use it to compare with Quarry
The working code is as below
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Songs {
String sName;
String fPath;
String aName;
double sLength;
static Songs[] AudioListing = new Songs[1];
static {
AudioListing[0] = new Songs("Danger Zone", "danger zone.mp3", "Kenny Loggins", 3.33);
}
public Songs(String songName, String filePath, String Artist, double songLength) {
sName = songName;
fPath = filePath;
aName = Artist;
sLength = songLength;
}
public static Songs[] search(String SearchCategory, String Quarry) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
// Returned array value
Songs[] ReturnedResult = new Songs[0];
// Method only list
List<Songs> SearchResult = new ArrayList<Songs>();
for (Songs song : AudioListing) {
Field field = Songs.class.getDeclaredField(SearchCategory);
String fieldValue = (String) field.get(song);
if (fieldValue.equals(Quarry)) {
SearchResult.add(song);
}
}
// Conversion of list to array for ease of use
ReturnedResult = SearchResult.toArray(ReturnedResult);
return ReturnedResult;
}
@Override
public String toString() {
return "Songs [sName=" + sName + ", fPath=" + fPath + ", aName=" + aName + ", sLength=" + sLength + "]";
}
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
//Calling of method
Songs[] results = Songs.search("aName", "Kenny Loggins");
System.out.println(Arrays.toString(results));
}
}
This explains how it can be achieved you can further enhance your code after further exploring in this direction.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is $(f(A))^c=f(A^c)$?
Is $(f(A))^c=f(A^c)$ for any function?
I can only prove the forward direction:
$y\in(f(A))^c\implies y\notin f(A)\implies A$ has no $x$ such that $f(x)=y \implies f^{-1}(y)\notin A \implies f^{-1}(y)\in A^c$. But we know that $y\in f(f^{-1}(y))\in f(A^c)$ hence $y\in f(A^c)$ finally.
Is this proof lacking? Can anyone prove the other way. Thing is, I'm not even convinced this is true, but it says so in the slides I have.
A:
No, it is only true if the function is bijective.
If $f$ is not surjective, $f(A)$ and $f(A^\complement)$ will not cover all of the codomain, so they are in particular not each other's complements.
If $f$ is not injective, there may be elements in common between $f(A)$ and $f(A^\complement)$, which again prevents them from being complements.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
why is java.nio.FileChannel transferTo() and transferFrom() faster??? Does it use DMA?
Why is java.nio.FileChannel transferTo() and transferFrom() faster than byte-by-byte transfer (stream based or using ByteBuffer) on some JVM/OS combinations???
Do these methods use direct memory access (DMA) as opposed to issuing interrupt requests (IRQ) for each byte transfer??
A:
Do these methods use direct memory access (DMA) as opposed to issuing interrupt requests (IRQ) for each byte transfer?
The specifics are up to the actual implementation, and they are not required to make use of any particular mechanism. This is hinted at in the documentation for transferTo (emphasis mine):
This method is potentially much more efficient than a simple loop that reads from this channel and writes to the target channel. Many operating systems can transfer bytes directly from the filesystem cache to the target channel without actually copying them.
'Potentially', 'many'... so no guarantees.
It does make sense to assume that it's probably more efficient to use the method, if only marginally so, because you allow the JVM to shortcut through native code (if using supported channel types). The 'simple loop' they describe works sort of like below:
ByteBuffer buf = ByteBuffer.allocateDirect(BUF_SIZE);
while ( /* read more condition */ ) {
source.read(buf);
buf.flip();
target.write(buf);
buf.compact();
}
Note that, even though this snippet uses direct buffers, you're still poking back into Java for buffer management (read, flip, write, compact). An optimising compiler may be able to elide some of it, but it probably won't.
Using transferTo/transferFrom, however, leaves it up to the JVM to decide how to transfer the bytes. If the platform has native support for this kind of transfers, it may be able to do so without creating intermediary buffers. If there is no such support, the JVM can still implement a loop such as above.
Example: suppose a SocketChannel is told to read data directly from a FileChannel through transferFrom. The FileChannel was recently read from, and its contents are in the OS file cache. Rather than read and copy the bytes into a buffer, the SocketChannel can point directly into the OS file cache and start transmitting from there. At least one round of copying eliminated.
Now further suppose that the socket (A) is actually connected to some other local process, for instance using a sort of pipe, called SocketChannel B. When B starts reading what it got from A, it might actually be reading straight from the OS file cache again. If then B just uses transferTo to another channel... you get the idea.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should not allow the space in password field?
Need to show error message whenever i enter space in password input field using ng-pattern.
A:
Use of regEx - /^\S*$/ does not allow space anywhere in the string.
<form name="myForm">
<input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
<div data-ng-show="myForm.passInpt.$error.pattern" >White Space not allowed</div>
</form>
DEMO:
var app = angular.module("app", []);
app.controller("ctrl", function($scope) {});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="app" ng-controller="ctrl">
<form name="myForm">
<input type='password' name="passInpt" ng-model='pass' data-ng-pattern="/^\S*$/">
<div data-ng-show="myForm.passInpt.$error.pattern">White Space not allowed</div>
</form>
</body>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Hiding some of Intellij debugger and editor toolbars to reduce screen clutter
From this shot we can see four bars / toolbars of various sizes associated with debugging and an editor panel:
At the least I would like to remove /reclaim the real estate from the first one:
and the last one:
In addition it would be preferable to reduce the height of the two middle toolbars
Are any of these adjustments possible ? I am using Intellij 2018.3
A:
Breadcrumbs can be disabled in the IDE settings. I don't think you can do anything with the other toolbars. Request is welcome.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Возможно ли проигрывать онлайн-тв на html5?
Добрейшего всем времени суток! Подскажите, пожалуйста, как можно транслировать видео через html5? Есть несколько вариантов потока. Но, как я понял, их вообще невозможно завести в html5? Флешевые плееры находил, но не совсем вариант. Заранее спасибо за ответ.
Потоки есть такие:
***/playlist.m3u8
***/mpeg.2ts
rtmp://***
rtsp://***
A:
Технически 'Да'
(Но в реальности - зависит от браузера...)
HTML 5 тег <video> ничего не знает о протоколах. Вы размещаете протокол в атрибут src как часть URL. Например:
<video src="rtp://myserver.com/path/to/stream">
Ваш браузер не поддерживает VIDEO тег и/или потоки RTP.
</video>
Или:
<video src="http://myserver.com:1935/path/to/stream/myPlaylist.m3u8">
Ваш браузер не поддерживает VIDEO тег и/или протокол данного видео.
</video>
Или даже что-то вроде:
<video>
<source src="rtp://myserver.com/path/to/stream" type="video/rtp">
<source src="http://myserver.com:1935/path/to/stream/myPlaylist.m3u8" type="application/x-mpegURL">
Ваш браузер не поддерживает VIDEO тег
</video>
Это говорит о том, что реализация тега <video> зависит от браузера. Если браузер поддерживает данный вид потоков - всё должно работать.
Из спецификации HTML5 от W3C:
User agents may support any video and audio codecs and container formats
Браузеры могут поддерживать любые видео, аудио кодеки и форматы контейнеров
Перевод ответа
Например, Chromium заявляли, что никогда не собираются поддерживать RTSP.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sencha Touch 2 pie chart has no labels
I am attempting to follow this example for creating a pie chart but my chart does not display labels for the sections. I copied and used the exact code from the example linked above.
The chart display complete with color sections but there are no labels like in the example.
My code is pasted below:
Ext.define('RevivalTimes.view.Chart', {
extend: 'Ext.chart.PolarChart',
xtype: 'chart',
requires: [
'Ext.chart.series.Pie',
'Ext.chart.interactions.Rotate'
],
config: {
title: 'Statistics',
iconCls: 'settings',
layout: 'fit',
animate: true,
interactions: ['rotate'],
colors: ['#115fa6', '#94ae0a', '#a61120', '#ff8809', '#ffd13e'],
store: {
fields: ['name', 'data1', 'data2', 'data3', 'data4', 'data5'],
data: [
{name: 'metric one', data1: 10, data2: 12, data3: 14, data4: 8, data5: 13},
{name: 'metric two', data1: 7, data2: 8, data3: 16, data4: 10, data5: 3},
{name: 'metric three', data1: 5, data2: 2, data3: 14, data4: 12, data5: 7},
{name: 'metric four', data1: 2, data2: 14, data3: 6, data4: 1, data5: 23},
{name: 'metric five', data1: 27, data2: 38, data3: 36, data4: 13, data5: 33}
]
},
series: [{
type: 'pie',
label: {
field: 'name',
display: 'rotate'
},
xField: 'data3',
donut: 30
}]
} //config
});
A:
The labels show with the inclusion of labelField as shown in the code below:
series: [{
type: 'pie',
label: {
field: 'name',
display: 'rotate'
},
xField: 'data1',
donut: 30,
labelField: 'name',
showInLegend: true,
}],
|
{
"pile_set_name": "StackExchange"
}
|
Q:
My custom date format is not formatting date with newton soft json in mvc
I am trying to display date in dd-MM-yyyy but the date i am getting is always in this format:
2016-08-08T16:17:40.643
I am using asp.net mvc and returning data in json format but displaying this date with angular js.
Here is the answer i am trying from the Link and i have combined the answer given by Perishable Dave and dav_i:
public class JsonNetFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is JsonResult == false)
{
return;
}
filterContext.Result = new JsonNetResult(
(JsonResult)filterContext.Result);
}
private class JsonNetResult : JsonResult
{
private const string _dateFormat = "dd-MM-yyyy";
public JsonNetResult(JsonResult jsonResult)
{
this.ContentEncoding = jsonResult.ContentEncoding;
this.ContentType = jsonResult.ContentType;
this.Data = jsonResult.Data;
this.JsonRequestBehavior = jsonResult.JsonRequestBehavior;
this.MaxJsonLength = jsonResult.MaxJsonLength;
this.RecursionLimit = jsonResult.RecursionLimit;
}
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
var isMethodGet = string.Equals(
context.HttpContext.Request.HttpMethod,
"GET",
StringComparison.OrdinalIgnoreCase);
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet
&& isMethodGet)
{
throw new InvalidOperationException(
"GET not allowed! Change JsonRequestBehavior to AllowGet.");
}
var response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType)
? "application/json"
: this.ContentType;
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data != null)
{
// Using Json.NET serializer
var isoConvert = new IsoDateTimeConverter();
isoConvert.DateTimeFormat = _dateFormat;
response.Write(JsonConvert.SerializeObject(this.Data));
}
}
}
}
[JsonNetFilter]
public ActionResult GetJson()
{
return Json(new { hello = new Date(2016-08-02 05:49:11.000) }, JsonRequestBehavior.AllowGet)
}
How to date in dd-MM-yyyy format??
A:
You're not passing your isoConvert variable to JsonConvert.SerializeObject(this.Data), so it's never used. You need to pass it to SerializeObject using an appropriate overload:
response.Write(JsonConvert.SerializeObject(this.Data, new [] { isoConvert } ));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Create a strikethrough in wxpython listctrl
I am using a wx.listctrl inside a wxpython GUI. I have a list that updates when I click a button. Currently when I select an item and click the button, I do the following:
item = self.my_list.GetItem(row_in_list)
self.my_list.SetItemTextColour(row_in_list,'red')
In addition to turning the font red, I would like to "cross it out" or "strikethrough". I have found wx.FFont(8, wx.FONTFAMILY_SWISS, face='Tahoma', flags = wx.FONTFLAG_STRIKETHROUGH) but this does not seem to work. Any one have ideas? Thanks!
A:
As far as I can tell, strike-throughs are not supported in the ListCtrl widget itself. You would have to create some kind of custom widget or switch to using the aforementioned UltimateListCtrl, which is a very flexible pure Python widget. You can see it in action in the wxPython demo package or read about in the following links:
http://wxpython.org/Phoenix/docs/html/lib.agw.ultimatelistctrl.UltimateListCtrl.html
http://www.blog.pythonlibrary.org/2011/11/02/wxpython-an-intro-to-the-ultimatelistctrl/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ordering query result by numeric strings in django (postgres backend)
I have a table with a name (varchar) field that only holds numeric string and I want to order my queries by this field. But name fields are being ordered by alphabetically but I want them to be ordered numerically.
For instance if I get 1 2 200 100 as name fields values, It is being ordered like 1 100 2 200
but I need them to be 1 2 100 200.
I could be able to come up with following row query
select *
from my_table as t
where t.foo='bar'
order by cast(t.name as integer);
But cannot represent this as django orm querysets? is there any way to do that?
A:
I'd ask first of all why you have a varchar column that needs to be treated as numeric, but never mind.
You can use the extra queryset method to convert your string:
MyTable.objects.extra(select={'int_name': 'CAST(t.name AS INTEGER)'},
order_by=['int_name'])
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"Your python3 install is corrupted"
I want to upgrade from Ubuntu 16.04.5 LTS to 18.04, so ran sudo do-release-upgrade.
After downloading and extracting bionic.tar.gz I get:
Can not upgrade
Your python3 install is corrupted. Please fix the '/usr/bin/python3'
symlink.
I saw How to fix "python installation is corrupted"? and so I did sudo ln -sf /usr/bin/python3.6 /usr/bin/python3 thinking that it would be a similar problem. But that didn't work (still same error message).
I have a few python versions:
$ ls /usr/lib | grep python
python2.7
python3
python3.5
python3.6
$ update-alternatives --display python3
python3 - auto mode
link best version is /usr/bin/python3.6
link currently points to /usr/bin/python3.6
link python3 is /usr/bin/python3
/usr/bin/python3.5 - priority 1
/usr/bin/python3.6 - priority 2
How do I fix python3?
A:
I just ran into this problem on Pop!_OS 18.04, trying to upgrade to 18.10, and it turns out that the problem lay in the symlink for /usr/bin/python and not for /usr/bin/python3. I had had /usr/bin/python3.6 configured as an alternative for python (not python3), and when I changed this, then I could run do-release-upgrade as expected.
I wish the error message pointed to python and not python3.
Before, with the problem:
$ update-alternatives --display python
python - manual mode
link best version is /usr/bin/python3.6
link currently points to /usr/bin/python2.7
link python is /usr/bin/python
/usr/bin/python2.7 - priority 1
/usr/bin/python3.6 - priority 2
I fixed it this way:
$ sudo update-alternatives --remove-all python
$ sudo ln -sf /usr/bin/python2.7 /usr/bin/python
Also see this comment below which describes a more precise solution that also better explains what is going on and how to fix it.
A:
You need to use the default Python 3 version for 16.04. That's 3.5, not 3.6. So run:
sudo ln -sf /usr/bin/python3.5 /usr/bin/python3
If that doesn't work, try reinstalling the python3 package.
sudo apt-get install --reinstall python3
By the way, update-alternatives --display python3 should give you update-alternatives: error: no alternatives for python3. Different versions of Python are not alternatives in Ubuntu.
A:
I observed this error message on Windows 10 1903 running WSL Ubuntu when I wanted to upgrade from 16.04 LTS to 18.04 LTS.
After do-release-upgrade had failed, I switched python alternatives to every choice offered by update-alternatives --config python and ran the upgrade command again. That did not help.
Then I checked the log file /var/log/dist-upgrade/main.log which contained the lines
2019-09-02 20:58:08,686 DEBUG _pythonSymlinkCheck run
2019-09-02 20:58:08,687 DEBUG python symlink points to: '/etc/alternatives/python', but expected is 'python2.7' or
'/usr/bin/python2.7'
2019-09-02 20:58:08,688 ERROR pythonSymlinkCheck() failed, aborting
So although the error message mentions python3, the issue is about python2.
The upgrade script checks for /usr/bin/python linking to /usr/bin/python2, see the source code of DistUpgrade/DistUpgradeController.py here: ubuntu launchpad
So one solution is to completely remove python from the alternative system and add the link manually, as described in the most popular answer.
If you don't want to remove python from the alternative system, just change the link only for the time during the upgrade process:
# rm /usr/bin/python
# ln -sf /usr/bin/python2.7 /usr/bin/python
# do-release-upgrade
This worked for me.
During the upgrade process, the link is automatically repaired. So when the upgrade is finished, it points to the python entry in the alternatives directory:
$ ls -l /usr/bin/python
lrwxrwxrwx 1 root root 24 Sep 2 22:01 /usr/bin/python -> /etc/alternatives/python
Edit: for thorough information, the issue might also appear if you upgrade from 18.04 LTS to 19.04 and the anwser applies to this situation, too.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Program hangs on Estimator.evaluate in Tensorflow 1.6
As a learning tool, I am trying to do something simple.
I have two training CSV files:
One file with 36 columns (3500 records) with 0s and 1s. I am envisioning this file as a flattened 6x6 matrix.
I have another CSV file with 1 columnn of ground truth 0 or 1 (3500 records) which indicates if at least 4 of the 6 of elements in the 6x6 matrix's diagonal are 1's.
I also have two test CSV files which are the same structure as the training files except there are 500 records in each.
When I step through the program using the debugger, it appears that the...
estimator.train(
input_fn=lambda: get_inputs(x_paths=[x_train_file], y_paths=[y_train_file], batch_size=32), steps=100)
... runs OK. I see files in the checkpoint directory and see a loss function graph in Tensorboard.
But when the program gets to...
eval_result = estimator.evaluate(
input_fn=lambda: get_inputs(x_paths=[x_test_file], y_paths=[y_test_file], batch_size=32))
... it just hangs.
I have checked the test files and I also tried running the estimator.evaluate using the training files. Still hangs
I am using TensorFlow 1.6, Python 3.6
The following is all of the code:
import tensorflow as tf
import os
import numpy as np
x_train_file = os.path.join('D:', 'Diag', '6x6_train.csv')
y_train_file = os.path.join('D:', 'Diag', 'HasDiag_train.csv')
x_test_file = os.path.join('D:', 'Diag', '6x6_test.csv')
y_test_file = os.path.join('D:', 'Diag', 'HasDiag_test.csv')
model_chkpt = os.path.join('D:', 'Diag', "checkpoints")
def get_inputs(
count=None, shuffle=True, buffer_size=1000, batch_size=32,
num_parallel_calls=8, x_paths=[x_train_file], y_paths=[y_train_file]):
"""
Get x, y inputs.
Args:
count: number of epochs. None indicates infinite epochs.
shuffle: whether or not to shuffle the dataset
buffer_size: used in shuffle
batch_size: size of batch. See outputs below
num_parallel_calls: used in map. Note if > 1, intra-batch ordering
will be shuffled
x_paths: list of paths to x-value files.
y_paths: list of paths to y-value files.
Returns:
x: (batch_size, 6, 6) tensor
y: (batch_size, 2) tensor of 1-hot labels
"""
def x_map(line):
n_dims = 6
columns = [str(i1) for i1 in range(n_dims**2)]
# Decode the line into its fields
fields = tf.decode_csv(line, record_defaults=[[0]] * (n_dims ** 2))
# Pack the result into a dictionary
features = dict(zip(columns, fields))
return features
def y_map(line):
y_row = tf.string_to_number(line, out_type=tf.int32)
return y_row
def xy_map(x, y):
return x_map(x), y_map(y)
x_ds = tf.data.TextLineDataset(x_train_file)
y_ds = tf.data.TextLineDataset(y_train_file)
combined = tf.data.Dataset.zip((x_ds, y_ds))
combined = combined.repeat(count=count)
if shuffle:
combined = combined.shuffle(buffer_size)
combined = combined.map(xy_map, num_parallel_calls=num_parallel_calls)
combined = combined.batch(batch_size)
x, y = combined.make_one_shot_iterator().get_next()
return x, y
columns = [str(i1) for i1 in range(6 ** 2)]
feature_columns = [
tf.feature_column.numeric_column(name)
for name in columns]
estimator = tf.estimator.DNNClassifier(feature_columns=feature_columns,
hidden_units=[18, 9],
activation_fn=tf.nn.relu,
n_classes=2,
model_dir=model_chkpt)
estimator.train(
input_fn=lambda: get_inputs(x_paths=[x_train_file], y_paths=[y_train_file], batch_size=32), steps=100)
eval_result = estimator.evaluate(
input_fn=lambda: get_inputs(x_paths=[x_test_file], y_paths=[y_test_file], batch_size=32))
print('\nTest set accuracy: {accuracy:0.3f}\n'.format(**eval_result))
A:
There are two parameters that are causing this:
tf.data.Dataset.repeat has a count parameter:
count: (Optional.) A tf.int64 scalar tf.Tensor, representing the
number of times the dataset should be repeated. The default behavior
(if count is None or -1) is for the dataset be repeated indefinitely.
In your case, count is always None, so the dataset is repeated indefinitely.
tf.estimator.Estimator.evaluate has the steps parameter:
steps: Number of steps for which to evaluate model. If None, evaluates until input_fn raises an end-of-input exception.
Steps are set for the training, but not for the evaluation, as a result the estimator is running until input_fn raises an end-of-input exception, which, as described above, never happens.
You should set either of those, I think count=1 is the most reasonable for evaluation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Vector size() returning seemingly random large integers
I am working on a program for homework and ran into a strange problem. When trying to get the size of a 2D vector using the size() function, I get seemingly random large integers which stop my program from running. I need the size to access elements in the vector.
My header file:
#ifndef _MATRIX_H
#define _MATRIX_H
#include <iostream>
#include <vector>
class Matrix {
private:
//int dimension;
std::vector< std::vector<int> > matrix;
public:
Matrix();
Matrix(std::vector< std::vector<int> >);
void print();
Matrix operator-(Matrix operand);
};
#endif
My implementation file:
#include "Matrix.h"
#include <iostream>
#include <vector>
// Default constructor
Matrix::Matrix() {
}
// Parameterized constructor
Matrix::Matrix(std::vector< std::vector<int> >) {
}
void Matrix::print() {
std::cout << "Size of matrix in print() " << matrix.size() << std::endl;
for (int i = 0; i < matrix.size(); i++) {
for (int j = 0; j < matrix.size(); j++) {
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
}
Matrix Matrix::operator-(Matrix operand) {
Matrix difference;
std::vector< std::vector<int> > diffMatrix;
diffMatrix.resize(matrix.size());
for (int i = 0; i < matrix.size(); i++ ) {
diffMatrix[i].resize(matrix.size());
}
difference.matrix = diffMatrix;
if (operand.matrix.size() == matrix.size()) {
for (int i = 0; i < operand.matrix.size(); i++) {
for (int j = 0; j < operand.matrix.size(); j++) {
difference.matrix[i][j] = matrix[i][j] - operand.matrix[i][j];
}
}
}
}
and my main.cpp file:
#include "Matrix.h"
#include <iostream>
#include <vector>
using namespace std;
int main(int argc, char** argv) {
vector< vector<int> > testMatrixOne(4);
vector< vector<int> > testMatrixTwo(4);
// Creating a test matrix
testMatrixOne = {{1,2},{3,4}};
testMatrixTwo = {{5,6},{7,8}};
// Create Matrix object
Matrix matrixOne(testMatrixOne);
Matrix matrixTwo(testMatrixTwo);
// Create Matrix to store difference
Matrix diff;
diff = matrixOne - matrixTwo;
diff.print();
return 0;
}
I have simplified my code and hardcoded in two matrices. When running the program, the size() will return a very large integer. I have spent several hours searching online but couldn't find out what's the cause of this. Why is the size() function doing this?
A:
The problem is unfortunately that:
Matrix Matrix::operator-(Matrix operand) {
never returns a value. This causes undefined behaviour, and the symptoms you saw were the result of the - appearing to return garbage.
At the end of the function, you meant to have:
return difference;
}
The C++ standard doesn't require compilers to warn about this, but it's still nice if they do warn. My version of g++ doesn't (even with -Wall), however adding the flag -Wreturn-type does produce a warning. IDK why this isn't part of -Wall, at least for simple cases like this.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Баскетбольное кольцо
Разрабатываю 2D игру на unity с баскетбольным кольцом, думаю как осуществить подсчёт очков.
У меня сейчас по одному коллайдеру на мяч и кольцо, но очки прибавляются и без пролёта в кольцо (когда мяч пролетает рядом).
Есть одна идея:
Сделать два коллайдера на кольце, чуть повыше и пониже, и один на мяче. Мяч пролетает верхний коллайдер, потом нижний, и очко засчитывается.
Только не пойму как закодить это. Подскажите, пожалуйста.
A:
Ты можешь сделать 2-а коллайдера на кольце: 1-ый отвечает за столкновения с кольцом (т.е. основной коллайдер (если у тебя 3д игра можно использовать MeshCollider)) и 2-ой внутри этого кольца в форме блина меньшего диаметра чем кольцо и сделать его IsTrigger (если игра 3д)
Затем повесить на кольцо скрипт, назовём его BasketballHoop и вызывать начисление очков в OnTriggerExit c предварительной проверкой прошёл ли шар через кольцо. Например так:
private void OnTriggerExit(Collider other)
{
if (Vector3.Dot(gameObject.transform.up, other.gameObject.transform.position - gameObject.transform.position) > 0)
{
//не прошёл
}
else
{
//прошёл
}
}
То есть я беру скалярное произведение двух векторов
Какие преимущества данного решения:
1. Можно использовать мяч любого размера
2. Очки будут засчитываться только когда мяч попадает в кольцо сверху
и, соответственно, не будут засчитываться если мяч попадает снизу
или вылетает
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Express session not persisting between api calls from react front end
Before asking this, I did have a look at other similar questions, but none of them have been of help as of yet.
I have a react front-end using axios to make api calls to a node backend using express and express session. Once I enter login info on my front end, I send it to my backend where I set a session and return a response to the front end that I set in the localStorage to use for client side validation.
When I try to access a protected api endpoint - from the front end - after logging in, the session does not have any of the information I set in it and thus, gives me an error. However, if I try to login and access the protected endpoint from postman, it works perfectly fine.
Here is my express-session config:
router.use(session({
secret: 'notGoingToWork',
resave: false,
saveUninitialized: true
}))
Here is the api call (after logging in) I am making through axios:
axios.get(`http://localhost:5000/users/personNotes/${JSON.parse(userData).email}`)
.then(response => console.log(response);
I do not know what the issue is and would appreciate any help. Thank you in advance!
A:
try using withCredentials
axios(`http://localhost:5000/users/personNotes/${JSON.parse(userData).email}`, {
method: "get",
withCredentials: true
})
or
axios.defaults.withCredentials = true
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use PackageManager.setComponentEnabledSetting
I am trying to use Android's PackageManager.setComponentEnabledSetting that has been available since API 1.0
Trouble is, I don't understand how to use it correctly. I pass a string with the path of the package component but the the environment states the error:
The method setComponentEnabledSetting(ComponentName, int, int) in the type PackageManager is not applicable for the arguments (String, int, int)
What is the ComponentName and how do I find it?
A:
What is the ComponentName
ComponentName is made up of the package name of the app and the class name of the component.
how do I find it?
Since it is your app, you know your app's package (e.g., getPackageName() on your Context). Since it is your component, you know your component's class name. From there, just call the appropriate constructor.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to load and process files one at a time, using PowerShell
I got the following script for loading about hundred thousand .doc files and ran a program on them. Based on the output, files are grouped in to folders. I tested the script on a local directory with few files, and it works as expected.
But when loading from the large corpus of files, the script prints "Loading Files...." and stays there. It seems the script is waiting till it loads all the files from the corpus. If this is the case, is there a way to load and process one file at a time?
It would be great if you could comment on efficiency aspect too.
$path = "\\Storage\100kCorpus"
$filter = "*.doc"
$count = 0
Write-Host "Loading files....";
$files = @(get-childitem -recurse -path $path -filter $filter)
Write-Host "files loaded";
foreach ($file in $files) {
$count ++
Write-Host "$file.FullName";
$out = & "D:\Test\doc\Verify.exe" /i:$file.FullName
$failed_file_location="D:\Test\doc\2875555\$out";
if (($out -ne "passed") -and !(Test-Path -path $failed_file_location )){
[IO.Directory]::CreateDirectory($failed_file_location)
Copy-Item $file $failed_file_location
}
}
Write-Host "There are $count files with the pattern $filer in folder $path"
A:
It will work the way you want if you pipe the output of get-childitem, instead of saving it to an array, i.e.
get-childitem -recurse -path $path -filter $filter | % {
$file = $_
$count ++
# etc ...
}
Note that $file = $_ is just so you don't have to modify your script too much.
Efficiency-wise I don't have much to say, except that in this way you are also avoiding to store all the file objects into an array ($files), so this version is at least avoiding an unnecessary operation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Downloading all files in a FTP folder and then deleting them
I've created two methods in a class that allow me to download the contents of an FTP folder and if specified then delete them. Although the code operates as intended I think it's vastly bloated and I'm looking for direction on how to correct it.
Of note I believe that there's far too many FTP connections opened in a single file move (three I believe - list directory, download files, delete files). I'm a bit unsure how to refine this.
public void DownloadFolder(string localFilesPath, string remoteFTPPath, bool deleteAfterDownload = false)
{
remoteFTPPath = "ftp://" + Hostname + remoteFTPPath;
var request = (FtpWebRequest)WebRequest.Create(remoteFTPPath);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(Username, Password);
request.Proxy = null;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
List<string> directories = new List<string>();
var line = reader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
directories.Add(line);
line = reader.ReadLine();
}
reader.Close();
using (var ftpClient = new WebClient())
{
ftpClient.Credentials = new NetworkCredential(Username, Password);
for (var i = 0; i <= directories.Count - 1; i++)
{
if (!directories[i].Contains("."))
{
continue;
}
var path = remoteFTPPath + "/" + directories[i].Remove(0, directories[i].IndexOf(@"/") + 1);
var transferPath = localFilesPath + @"\" + directories[i].Replace(@"/", @"\");
PostEvent($"Attempting to download File: {path} to: {transferPath}", Debug);
try
{
ftpClient.DownloadFile(path, transferPath);
PostEvent($"Downloaded File: {path} to: {transferPath}", Info);
PostEvent($"Preparing to delete file: {path}\n\n", Debug);
if (deleteAfterDownload)
{
DeleteFile(path);
}
}
catch (WebException ex)
{
PostEvent($"Error downloading or deleting file {path} to {transferPath}", Error);
PostEvent($"Exception: {ex.Message}", Error);
}
catch (Exception ex)
{
PostEvent($"General Exception: {ex.Message}", Error);
}
}
}
response.Close();
}
public void DeleteFile(string remoteFTPPath)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(remoteFTPPath);
request.Method = WebRequestMethods.Ftp.DeleteFile;
request.Credentials = new NetworkCredential(Username, Password);
request.Proxy = null;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
PostEvent($"Deleting file {remoteFTPPath} returned status {response.StatusDescription}", Debug);
response.Close();
}
Here's the class initializer (where my credentials are passed into properties within this class):
public FtpHelper(string ftpHostname, string ftpUsername, string ftpPassword)
{
Hostname = ftpHostname;
Username = ftpUsername;
Password = ftpPassword;
}
And the postevent method that's referred to here come's from a base class I inherit to this class (unsure if this is bad practice, please let me know if so):
public class BaseHelper
{
private EventHandler<BaseExceptionEventArgs> _onEvent;
public event EventHandler<BaseExceptionEventArgs> OnEventHandler
{
add { _onEvent += value; }
remove { _onEvent += value; }
}
/// <exception cref="Exception">A delegate callback throws an exception.</exception>
public void PostEvent(string message, BaseExceptionEventArgs.ExceptionLevel exceptionLevel,
Exception exception = null)
{
if (_onEvent == null) return;
if (exception == null)
{
var e = new BaseExceptionEventArgs(message, exceptionLevel);
_onEvent(this, e);
}
else
{
var e = new BaseExceptionEventArgs(message, exceptionLevel, exception);
_onEvent(this, e);
}
}
}
A:
The first thing I would do is change your constructor:
private readonly NetworkCredential credentials;
public ftpHelper(string ftpHostname, string ftpUsername, string ftpPassword)
{
credentials = new NetworkCredential(ftpUsername, ftpPassword);
Hostname = ftpHostname;
}
That eliminates newing up credentials all over your code.
As for the rest of your code, I think a few well named functions will make the code much more readable. For example, getting a list of files:
private IEnumerable<string> ListDirectories(string remoteFtpPath)
{
var url = $"ftp://{Hostname}{remoteFtpPath}"; // Is this right? Not used C#6 yet...
var request = (FtpWebRequest)WebRequest.Create(url);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = credentials;
request.Proxy = null;
var directories = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream))
{
while (!reader.EndOfStream)
{
directories.Add(line);
}
}
return directories;
}
You could write the above using yield if you'd rather.
Go through your code and keep pulling out all of the methods aiming to get each one to do a single thing.
For example, I'd probably pull out another method from the above (ListDirectories) called CreateListDirectoriesRequest and have that create the WebRequest.
Other thoughts
Ftp or ftp never FTP in names.
What you're doing with your remoteFTPPath parameter is very confusing. I'd have no idea what it was for a lot of your method.
It's easier to use using than calling Close/Dispose most of the time.
You almost certainly want to log ex.ToString() rather than just the message. You'll want the stack trace when you're tracking down problems.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how do i add a drop down list item in a mule connector?
I've made a mule connector, everything works great. I got 4 main properties for an HTTP outbound connection: url, port, path and method.
I would like the method to be a drop down list with values: GET, POST.
Do you guys know how to do it? what annotation needs to be used in case that's the way to solve it? Or is it recognized by Mule when adding a Map or Enum property?
This is my current simple code
/**
* This file was automatically generated by the Mule Development Kit
*/
package com.web.testcomponent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.mule.api.MuleEventContext;
import org.mule.api.annotations.Configurable;
import org.mule.api.annotations.Module;
import org.mule.api.annotations.Processor;
import org.mule.api.annotations.display.Placement;
import org.mule.api.annotations.expressions.Lookup;
import org.mule.api.annotations.param.Default;
import org.mule.api.annotations.param.Optional;
import org.mule.api.annotations.param.Payload;
/**
* Generic module
*
* @author MuleSoft, Inc.
*/
@Module(name="testcomponent", schemaVersion="1.0-SNAPSHOT", friendlyName="HTTP/S Component", description="This is custom HTTP/S Component")
public class TestComponentModule
{
@Lookup("myMuleContext")
private MuleEventContext context;
/**
* Connection URL
*/
@Configurable
@Placement(order=1,group="Connection",tab="General")
private String url;
/**
* Connection Port
*/
@Configurable
@Placement(order=2,group="Connection",tab="General")
private String port;
/**
* Connection Path
*/
@Configurable
@Placement(order=3,group="Connection",tab="General")
private String path;
/**
* Connection Method (GET or POST)
*/
@Configurable
@Default(value="GET")
@Optional
@Placement(order=4,group="Connection",tab="General")
private String method;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public MuleEventContext getContext() {
return context;
}
public void setContext(MuleEventContext context) {
this.context = context;
}
/**
* Custom processor
*
* {@sample.xml ../../../doc/TestComponent-connector.xml.sample testcomponent:test-processor}
*
* @param content Random content to be processed
* @param payload The String payload itself
* @return Some string
*/
@Processor
public String testProcessor(@Payload String payload)
{
HttpURLConnection conn = null;
try {
URL url = new URL(getUrl() + "/" + getPath());
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(getMethod());
conn.setRequestProperty("Accept", "application/json");
if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Failed -> HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String output, buffer;
output = "";
while((buffer = br.readLine()) != null) {
output += buffer;
}
payload = output;
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return payload;
}
}
A:
I have no problem using an enum:
public enum HttpMethod
{
GET, POST
};
@Configurable
@Default(value = "GET")
@Optional
@Placement(order = 4, group = "Connection", tab = "General")
private HttpMethod method;
Doesn't this work for you too?
As a side note, looking at what your @Processor method does, I'm wondering if you're not re-inventing @RestCall processors. Also why using a raw HttpURLConnection when you can perform HTTP calls with the MuleClient?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
LWUIT in a enterprise J2ME application?
We are developing a J2ME application and sometimes we face constraints while working with the default lcdui library. Whenever we want some extra in the UI, the only option is to work with canvas which is not so easy. Now we are thinking to use LWUIT as UI library instead of ludui but having some question before starting -
Is LWUIT mature enough to be used in a enterprise J2ME application?
Can we mix LWUIT and LCDUI in same application ?
A:
In my point of view. lwuit is mature enough to be used in enterprise applications. It's still in permanent development and it's progressing fast.
Yes you can mix both of them. If you use an lwuit form you can only add lwuit components and vice versa. It should be possible to implement and draw you own container objects (canvas style).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I know what wood was used to construct our attic? Need to know how much load it can tolerate
I'm reading a book and it lists different max loads for different woods.
It lists loads for (1) Douglass Fir-Larch and (2) Hem-fir
My attic is made with a dark brown wood. How do I know what type of wood was used to construct the attic?
The house was built in 1939 in Southern California (don't know if this helps to identify it)
Here's a picture of the attic. (Could it be redwood?)
A:
It is not redwood it looks like fir. At the age of the house almost the wood was fir back then. Nice tight grain like what you have is almost impossible to purchase now unless you just won the lottery.
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.